Types of inheritance with examples
Types of Inheritance in C++
1) Single inheritance
2) Multilevel inheritance
3) Multiple inheritance
4) Hierarchical inheritance
5) Hybrid inheritance
2) Multilevel inheritance
3) Multiple inheritance
4) Hierarchical inheritance
5) Hybrid inheritance
Single inheritance
In Single inheritance one class inherits one class exactly.
For example: Lets say we have class A and B
For example: Lets say we have class A and B
B inherits A
Example of Single inheritance:
#include <iostream> using namespace std; class A { public: A(){ cout<<"Constructor of A class"<<endl; } }; class B: public A { public: B(){ cout<<"Constructor of B class"; } }; int main() { //Creating object of class B B obj; return 0; }
Output:
Constructor of A class Constructor of B class
2)Multilevel Inheritance
In this type of inheritance one class inherits another child class.
C inherits B and B inherits A
Example of Multilevel inheritance:
#include <iostream> using namespace std; class A { public: A(){ cout<<"Constructor of A class"<<endl; } }; class B: public A { public: B(){ cout<<"Constructor of B class"<<endl; } }; class C: public B { public: C(){ cout<<"Constructor of C class"<<endl; } }; int main() { //Creating object of class C C obj; return 0; }
Output:
Constructor of A class Constructor of B class Constructor of C class
Multiple Inheritance
In multiple inheritance, a class can inherit more than one class. This means that in this type of inheritance a single child class can have multiple parent classes.
For example:
For example:
C inherits A and B both
Example of Multiple Inheritance:
#include <iostream> using namespace std; class A { public: A(){ cout<<"Constructor of A class"<<endl; } }; class B { public: B(){ cout<<"Constructor of B class"<<endl; } }; class C: public A, public B { public: C(){ cout<<"Constructor of C class"<<endl; } }; int main() { //Creating object of class C C obj; return 0; }
Constructor of A class Constructor of B class Constructor of C class
4)Hierarchical Inheritance
In this type of inheritance, one parent class has more than one child class. For example:
Class B and C inherits class A
Example of Hierarchical inheritance:
#include <iostream> using namespace std; class A { public: A(){ cout<<"Constructor of A class"<<endl; } }; class B: public A { public: B(){ cout<<"Constructor of B class"<<endl; } }; class C: public A{ public: C(){ cout<<"Constructor of C class"<<endl; } }; int main() { //Creating object of class C C obj; return 0; }
Output:
Constructor of A class Constructor of C class
5) Hybrid Inheritance
Hybrid inheritance is a combination of more than one type of inheritance. For example, A child and parent class relationship that follows multiple and hierarchical inheritance both can be called hybrid inheritance.
Comments
Post a Comment