As we already know that inheritance is one of the most important pillar of object oriented programming.
C++ allows us to implement various inheritance models in a program. These inheritance models are,
Lets discuss them one by one.
According to this model we can derive a class from a derived class which is derived from another derived class or base class. This forms layers of inheritance.
Syntax for multilevel inheritance
class A { ... .. ... }; class B: public A { ... .. ... }; class C: public B { ... ... ... };
In above syntax, we are deriving class B from base class A and from B class C is derived.
Lets take an example for better understanding
Example 1:
#include <iostream> using namespace std; class A { public: void display() { cout<<"this is base class"; } }; class B : public A { }; class C : public B { }; int main() { C obj; obj.display(); return 0; }
Output:
this is base class
in this program, we have three classes A,B and C deriving from each other respectively, when we called function of class C, we got function of A. this due to multilevel inheritance.
According to this model, a derived class can be derived from multiple base classes.
Lets understand it with an example
Example 2:
#include <iostream> using namespace std; class A { public: A() { cout << "A's constructor" << endl; } }; class B { public: B() { cout << "B's constructor" << endl; } }; class C: public B, public A { public: C() { cout << "C's constructor" << endl; } }; int main() { C c; return 0; }
Output:
B’s constructor A’s constructor C’s constructor
in the above program, you can see both the classes A and B are inherited in class C.
Note: look at the order class C: public B, public A, that is why functions are inherited in the order as given in output.
According to this model, more than one classes can be derived from the base class.
Syntax of hierarchical inheritance is given below
class A { ... .. ... } class B: public A { ... .. ... } class C: public A { ... .. ... } class D: public A { ... .. ... }