OOP: Inheritance in C++
Contents
• Concept of Inheritance
• Relationship Between Base Class and Derived Class
• Constructor and Destructor in Derived Classes
• Public, Protected and Private Inheritance
Inheritance
• Inheritance is a form of software reuse in which we create a class that absorbs an existing class’s data and behaviors and enhances them with new capabilities.
• This existing class is called the base class, and the new class is referred to as the derived class.
• A direct base class is the base class from which a derived class explicitly inherits.
• An indirect base class is inherited from two or more levels up in the class hierarchy.
• Single inheritance: derived from one base class.
• Multiple inheritance: derived from multiple base classes.
Inheritance
• With public inheritance, every object of a derived class is also an object of that derived class’s base class. However, base-class objects are not objects of their derived classes.
• Example: Let us assume vehicle as a base class and car as a derived class, then all cars are vehicles, but not all vehicles are cars.
is-a relationship vs. has-a relationship
CompositionInheritance
Inheritance Examples
Inheritance hierarchy for university CommunityMembers.
Inheritance hierarchy for Shapes
• Public members of the base class become public members of the derived class.
• friend functions are not inherited
A simple example of inheritance
Protected Members
• A base class’s public members are accessible within its body and anywhere that the program has a handle to an object of that class or one of its derived classes.
• A base class’s private members are accessible only within its body and to the friends of that base class.
• A base class’s protected members can be accessed within the body of that baseclass, by members and friends of that base class, and by members and friends of any classes derived from that base class.
Relationship Between
Base Class and Derived Class
Commission Employee Class
For Source Code: Practice1
Bas
ePlu
sCo
mm
issi
on
Emp
loye
eC
lass
For Source Code: Practice2
CPM: Copied, Paste, and Modify
BasePlusCommissionEmployee using Inheritance
BasePlusCommissionEmployeeusing Inheritance with Protected Data
For Source code Practice3