1 / 187

Inheritance

Inheritance. Object Oriented Programming Concepts. Encapsulation Data Hiding Inheritance Polymorphism . Reuse. Inheritance. In our daily lives we use the concept of classes divided into subclasses, for example vehicles are divided into cars, buses and motor cycles.

chrisbyrd
Télécharger la présentation

Inheritance

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Inheritance

  2. Object Oriented Programming Concepts • Encapsulation • Data Hiding • Inheritance • Polymorphism Reuse

  3. Inheritance • In our daily lives we use the concept of classes divided into subclasses, for example vehicles are divided into cars, buses and motor cycles. • The principle in this sort of division is that each sub-class shares some common features with the base class from which it is derived, but also has its own particular features. base class Vehicle wheels engine Car Truck wheels engine trunk wheels engine trailer sub-classes or derived classes trunk trailer

  4. Introduction • A class defines the behavior of a set of objects • E.g., Vehicle, Animals, Books, etc. • There may be another set of objects that posses a specialization of this behavior • E.g., Cars, Jeeps, Busses, Reptiles, Notebooks etc • Only define the specialization while reusing the existing code.

  5. Inheritance In object-oriented language, a class can obtain the properties of another class through the mechanism of inheritance. • In C++, inheritance is supported by class derivation. • A derived classinherits the properties of its base class.

  6. Inheritance

  7. Inheritance The class that is being inherited from is called the base class. The new class is called the derived class. The set of the base and derived class instances is called the class inheritance hierarchy. A derived class inherits data members and member functions of its base class, and can also add its own list of generalization and specialization.

  8. Inheritance Generalization: Extend the behavior of the base class. Add new member functions and/or data to derived class. e.g. doResearch() for class Gradstudent. Specialization: Modify the behavior of the base class. Change implementations in the derived class without changing the base class interface. e.g. getPaid() for class Student and Gradstudent.

  9. Inheritance Benefits of Class Inheritance: • Increase software reuse and quality – Programmers can reuse the base classes instead of writing new classes – Using well-tested base classes helps reduce bugs in software. – Reduce code size. • Enhance software extensibility and comprehensibility – Helps support more flexible and extensible architectures. – Useful for modeling and classifying hierarchically related domains.

  10. Basic Syntax of class inheritance Example: class Pen { public: void SetLocation(int, int); void SetStatus(int); private: int x, y, status; }; //end class declaration. class ColorPen : public Pen { public: void SetColor(int); private: int color; };

  11. Basic Syntax of class inheritance class derived_class_name: publicbase_class_name; In which public can be replaced by protected and private access specifier to describes the access for the inherited members.

  12. Basic Syntax of class inheritance Pen is the base class; ColorPen is the derived class. The keyword public indicates here the type of inheritance is public.

  13. Base class and Derived class

  14. Basic Syntax of class inheritance A derived class object consists of sub-objects of its base classes and a derived class portion.

  15. Think of a Bicycle

  16. Think of a Tandem Bike

  17. Think of a Racing Bike

  18. Think of a Mountain Bike

  19. Thinking About Bicycles • A tandem bicycle is a kind of bicycle • Bicycle with two seats • A mountain bicycle is a kind of bicycle • Bicycle with shocks • A racing bicycle is a kind of bicycle • Lightweight aerodynamic construction • Tandem, mountain, and racing bicycles are specialized bicycles

  20. Inheritance • Be able to create specialized program objects without starting from scratch • Inheritance is the object-oriented programming mechanism for specialization

  21. Inheritance • Ability to define new classes of objects using existing classes as a basis • The new class inherits the attributes and behaviors of the parent classes • New class is a specialized versionof the parent class

  22. Inheritance • A natural way to reuse code • Programming by extension rather than reinvention • Object-oriented paradigm is well-suited for this style ofprogramming • Terminology • Base class (superclass) • Derived class (subclass)

  23. Shape class Base class Circle class Triangle class Derived class Derived class Isosceles Triangle Equilateral Triangle Right-angle Triangle Class Inheritance

  24. Shape class Shape class Circle class Circle class Triangle class Triangle class Isosceles Triangle Isosceles Triangle Equilateral Triangle Equilateral Triangle Right-angle Triangle Right-angle Triangle Specialization – Generalization • Specialization goes down the way. • Generalization goes up the way.

  25. The Student Class Hierarchy student print()year_group() student_id,year, name inherits (isa) CR dept,thesis print()

  26. Can you build Inheritance Hierarchy out of this Venn-Diagram

  27. Inheritance Syntax • The simplest example of inheritance requires two classes: a base classand a derived class. • The base class OR super-class does not need any special syntax. • The derived class OR subclass on the other hand, must indicate that it’s derived from the base class. • This is done by placing a colon after the name of the derived class, followed by a keyword such as public and then the base class name.

  28. Syntax for Inheritance classderivedClass : publicbaseClass { private : // Declarations of additional members, if needed. public: // Declarations of additional members, if needed. } The derived class inherits from the base class: all public members (see later) The additional members defined can have the same name (and type) as thoseof the base class (as when some base members are to be redefined)

  29. Inheritance Syntax class Teacher{ // Base class private: string name; int age, numOfStudents; public: void setName (string new_name){ name = new_name; } }; class Principal : public Teacher{ // Derived class string school_name; intnumOfTeachers; public: void setSchool(const string & s_name){ school_name = s_name; } };

  30. Inheritance Syntax int main() { Teacher t1; Principal p1; p1.setName(" Principal 1"); t1.setName(" Teacher 1"); p1.setSchool(" Elementary School"); return 0; } • The p1 object can also access, in addition to its own member function setSchool(), the member function from Parent (Base), which is setName().

  31. Constructor An object of the derived class consists of sub-object of its base classes and the derived class portion. To construct an object of the derived class, objects of the base classes are constructed first.

  32. Constructor

  33. Constructor Example: class B_class { // ... }; class D_class : public B_class{ // ... }; class DD_class : public D_class{ // ... }; DD_class dd;

  34. Constructor

  35. Constructor In an inheritance hierarchy, constructors execute in a base class to derived class order.

  36. Constructor Derived objects are constructed by the following steps: 1. Allocate space for the entire object( base class members and derived class members) 2. Invoke the base class constructor to initialize the base class part of the object. 3. Initialize the members of derived class directed by the derived class constructor initializer 4. Executing the body of the derived class constructor

  37. Constructor Now in step 2, which constructor in based class will be invoked?

  38. Constructor Example: class B_class { B_class(){ cout << ``Creating B_class\n'';}; // line 1 }; class D_class : public B_class{ public: D_class(){ cout << ``constructing D_class\n''; } }; int main(){ D_class d; // output? }

  39. Constructor Question: What happens if the line 1 is removed? If the base class has no constructor, then a system provided default constructor for base class is invoked when creating an object of the derived class.

  40. Consider the following code. What is wrong? class B_class { public: B_class(int xx, int yy) : x(xx), y(yy) {} private: int x, y; }; class D_class : public B_class{ public: D_class( int zz ) : z(zz) {} private: int z; }; int main(){ D_class d( 10 ); // ... }

  41. Solution 1: Provide a default constructor to the base class B class. class B_class { public: B_class(int xx = 0, int yy = 0) : x(xx), y(yy) {} private: int x, y; }; class D_class : public B_class{ public: D_class( int zz ) : z(zz) {} private: int z; }; int main(){ D_class d( 10 ); }

  42. Solution 2: Explicitly invokes a B class constructor in D class constructor initializer. class B_class { public: B_class(int xx, int yy) : x(xx), y(yy) {} private: int x, y; }; class D_class : public B_class{ public: D_class( int zz ) : B_class(0,0), z(zz) {} // here ! private: int z; }; int main(){ D_class d( 10 ); }

  43. Example: class Animal{ public: Animal() : species("Animal") {} Animal( string s ) : species(s) {} private: string species; }; class Primate : public Animal { public: Primate() : Animal( "Primate" ), heart_cham(0) {} Primate( int n ) : Animal( "Primate" ), heart_cham(n) {} private: int heart_cham; };

  44. class Human : public Primate { public: Human() : Primate(4) {} // ... }; int main(){ Primate Whazat(7); Human Jenny; // ... }

  45. Destructor When a derived class object is destroyed, the derived class portion is destroyed first. In an inheritance hierarchy, destructors execute in a derived class to base class order, which is the reverse order of constructors.

  46. Example: class B_class { public: B_class(){ cout << ``Creating B_class \n''; } ~B_class(){ cout << ``Destroying B_class \n''; } }; class D_class : public B_class{ public: D_class(){ cout << ``Creating D_class \n''; } ~D_class(){ cout << ``Destroying D_class \n''; } }; int main(){ D_class d; // Output? }

  47. Copy constructor and operator = The user defined copy constructor and operator= in derived class should explicitly invoke the copy constructor and operator= of its base class.

  48. Copy constructor and operator = Example: D_class::D_class( const D_class& x) : B_class(x){ // then performs copy for members of derived class ... } D_class& D_class::operator=( const D_class& x ){ B_class::operator=(x); // then performs copy for members of derived class ... }

  49. Member Access Public Member In public inheritance, public members from the base class are public in its derived classes. Private Member Private members in a base class are accessible only in the base class; they are not accessible in its derived classes.

More Related