Inheritance
Inheritance is the ability of one object to acquire some/all properties of another object. Implementation of the is-a relationship.
A child inherits the traits of his/her parents.
With inheritance, reusability is a major advantage. You can reuse the fields and methods of the existing class, i.e. class A
(parent) serves as partial blueprint for class B
(child):
- Child class
B
inherits all fields/methods of parent classA
- Child class
B
can add new field/methods, and override the definitions of methods inherited from parent classA
I was rusty
Remember that you DON’T need to redeclare the fields of the base class in the derived class.
Types of Inheritance
An inherited class is declared in the form
The Access Specifier specifies the type of inheritance. It is private
by default.
” ” members of the base class become ” ” members of the base class
- Public Inheritance (most common)
- “public” “public”Â
- “protected” “protected”
- private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class
- Protected InheritanceÂ
- “public” and “protected” “protected”
- Private Inheritance
- “public and protected” “private”
What gets inherited?
In principle, a publicly derived class inherits access to every member of a base class except:
- its constructors and its destructor
- its assignment operator members (operator=)
- its friends
- its private members
Example
Example 1: A generic shape as the base class and a rectangle as the derived class.
Ex 2: (not implemented) Parent Class is Person. Child class is Student, Teacher, so these inherit from the parent class.
Advanced Types of Inheritance
- Multiple Inheritance (dangerous to use due to Diamond Problem)
- Virtual Inheritance