PREV NEXT
C++ Multilevel & Multiple inheritance:
What is multilevel inheritance?
- In C++, we can not only derive a class from the base class but you can also derive a class from the derived class.
- Mulitlevel inheritance is one child class inheriting from another child class. This is known as multilevel inheritance.
Let us have a look at the example for C++ Multilevel & Multiple inheritance:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
#include <iostream> using namespace std; class A { public: void display() { cout<<"Base class content."; } }; class B : public A { public: void display1() { cout<<"\nClass B content."; } }; class C : public B { public: void display2() { cout<<"Class C content."; } }; int main() { C c; c.display(); c.display1(); return 0; } |
What is multiple inheritance?
- The multiple inheritance is a feature of C++ where a class can inherit from more than one class i.e. one sub class is inherited from more than one base class.
- In this type of inheritance a single child class can have multiple parent classes.
Let us have a look at the example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
#include <iostream> using namespace std; class X { public: X(){ cout<<"Constructor of X class"<<endl; } }; class Y { public: Y(){ cout<<"Constructor of Y class"<<endl; } }; class Z: public X, public Y { public: Z(){ cout<<"Constructor of Z class"<<endl; } }; int main() { //Creating object of class Z Z obj; return 0; } |