inheritance. lecture contents inheritance class hierarchy types of inheritance derived and base...
TRANSCRIPT
Inheritance
Lecture contents
• Inheritance
• Class hierarchy
• Types of Inheritance
• Derived and Base classes
• derived class constructors
• protected access identifier
• multiple inheritance
Introduction
• Inheritance– Software reusability– Create new class from existing class
• Absorb existing class’s data and behaviors• Enhance with new capabilities
– Derived class inherits from base class• Derived class
– More specialized group of objects– Behaviors inherited from base class
» Can customize– Additional behaviors
Class hierarchy
– Direct base class• Inherited explicitly (one level up hierarchy)
– Indirect base class• Inherited two or more levels up hierarchy
– Single inheritance• Inherits from one base class
– Multiple inheritance• Inherits from multiple base classes
– Base classes possibly unrelated
Types of inheritance• Three types of inheritance
– public • Every object of derived class also object of base class
– Base-class objects not objects of derived classes
• Can access non-private members of base class
– private• Alternative to composition
– protected • Rarely used
• Abstraction– Focus on commonalities among objects in system
• “is-a” vs. “has-a”– “is-a”
• Inheritance• Derived class object treated as base class object• Example: Car is a vehicle
– Vehicle properties/behaviors also car properties/behaviors
– “has-a”• Composition• Object contains one or more objects of other classes as members• Example: Car has a steering wheel
Vehicle
Car
Base Classes and Derived Classes– Object of one class “is an” object of another
class• Example: Rectangle is quadrilateral.
– Class Rectangle inherits from class Quadrilateral– Quadrilateral: base class– Rectangle: derived class
– Base class typically represents larger set of objects than derived classes
• Example: – Base class: Vehicle
» Cars, trucks, boats, bicycles, …– Derived class: Car
» Smaller, more-specific subset of vehicles
What a derived class inherits
• Every data member defined in the parent class (although such members may not always be accessible in the derived class!)
• Every ordinary member function of the parent class (although such members may not always be accessible in the derived class!)
• The same initial data layout as the base class
What a derived class doesn't inherit
• The base class's constructors and destructor
• The base class's assignment operator
• The base class's friends
What a derived class can add
– New data members
– New member functions
– New constructors and destructor
– New friends
What happens when a derived-class object is created and destroyed
• Space is allocated (on the stack or the heap) for the full object (that is, enough space to store the data members inherited from the base class plus the data members defined in the derived class itself)
• The base class's constructor is called to initialize the data members inherited from the base class
• The derived class's constructor is then called to initialize the data members added in the derived class
• The derived-class object is then usable
• When the object is destroyed (goes out of scope or is deleted) the derived class's destructor is called on the object first
• Then the base class's destructor is called on the object
• Finally the allocated space for the full object is reclaimed
Base Classes and Derived Classes
• Inheritance examplesBase class Derived classes
Student GraduateStudent UndergraduateStudent
Shape Circle Triangle Rectangle
Loan CarLoan HomeImprovementLoan MortgageLoan
Employee FacultyMember StaffMember
Account CheckingAccount SavingsAccount
Base Classes and Derived Classes
• Inheritance hierarchy– Inheritance relationships: tree-like hierarchy
structure– Each class becomes
• Base class– Supply data/behaviors to other classes
OR• Derived class
– Inherit data/behaviors from other classes
Single inheritance
CommunityMember
Employee Student
Administrator Teacher
AdministratorTeacher
StaffFaculty
Alumnus
Single inheritance
Single inheritance
Multiple inheritance
Inheritance hierarchy for university CommunityMembers.
Shape
TwoDimensionalShape ThreeDimensionalShape
Circle Square Triangle Sphere Cube Tetrahedron
Inheritance hierarchy for Shapes.
Base Classes and Derived Classes• public inheritance
– Specify with:
Class TwoDimensionalShape : public Shape
• Class TwoDimensionalShape inherits from class Shape
– Base class private members• Not accessible directly• Still inherited
– Manipulate through inherited member functions
– Base class public and protected members• Not inherited
protected Members• protected access
– Intermediate level of protection between public and private
– protected members accessible to• Base class members• Base class friends• Derived class members• Derived class friends
#include <iostream> using namespace std; class CPolygon { protected:
int width, height; public:
void set_values (int a, int b) { width=a; height=b;}
}; class CRectangle: public CPolygon { public: int area () { return (width * height); } };
Example
class CTriangle: public CPolygon { public: int area () { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; rect.set_values (4,5); trgl.set_values (4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0; }
Output
• 20
• 10
Relationship between Base Classes and Derived Classes
• Using protected data members– Advantages
• Derived classes can modify values directly• Slight increase in performance
– Avoid set/get function call overhead
– Disadvantages• No validity checking
– Derived class can assign illegal value
• Implementation dependent– Derived class member functions more likely dependent on base class
implementation
– Base class implementation changes may result in derived class modifications
Constructors and Destructors in Derived Classes
• Instantiating derived-class object– Chain of constructor calls
• Derived-class constructor invokes base class constructor– Implicitly or explicitly
• Base of inheritance hierarchy– Last constructor called in chain
– First constructor body to finish executing
– Example: Point3/Circle4/Cylinder hierarchy» Point3 constructor called last» Point3 constructor body finishes execution first
• Initializing data members– Each base-class constructor initializes data members
» Inherited by derived class
Constructors and Destructors in Derived Classes
• Destroying derived-class object– Chain of destructor calls
• Reverse order of constructor chain• Destructor of derived-class called first• Destructor of next base class up hierarchy next
– Continue up hierarchy until final base reached» After final base-class destructor, object removed
from memory
Example// constructors and derived classes #include <iostream> using namespace std; class mother { public:
mother () { cout << "mother: no parameters\n"; }
mother (int a) { cout << "mother: int parameter\n"; }
}; class daughter : public mother { public:
daughter (int a) { cout << "daughter: int parameter\n\n"; }
};
class son : public mother { public:
son (int a) : mother (a) { cout << "son: int parameter\n\n"; }
}; int main () { daughter cynthia (0); son daniel(0); return 0; }
Output
• mother: no parameters
• daughter: int parameter
• mother: int parameter
• son: int parameter
Multiple Inheritance• A class inherits members from more than one class. This
is done by simply separating the different base classes with commas in the derived class declaration.
• For example, if we had a specific class to print on screen (COutput) and we wanted our classes CRectangle and CTriangle to also inherit its members in addition to those of CPolygon we could write:
• class CRectangle: public CPolygon, public COutput; • class CTriangle: public CPolygon, public COutput;
Example// multiple inheritance #include <iostream> using namespace std; class CPolygon { protected:
int width, height; public:
void set_values (int a, int b) { width=a; height=b;}
}; class COutput { public:
void output (int i); };
void COutput::output (int i) {
cout << i << endl; } class CRectangle: public CPolygon, public COutput { public:
int area () { return (width * height); }
}; class CTriangle: public CPolygon, public COutput { public:
int area () { return (width * height / 2); }
};
int main () { CRectangle rect; CTriangle trgl; rect.set_values (4,5); trgl.set_values (4,5); rect.output (rect.area()); trgl.output (trgl.area()); return 0;}
Output
• 20
• 10