Inheritance is one of the four major pillars of Object-Oriented Programming (OOP) in C++. It allows a class to acquire the properties and behaviors of another class, promoting code reuse and modularity.
In this post, we’ll explore the different types of inheritance supported by C++, complete with simple code examples for each.
Understanding Inheritance in C++ with Example
Types of Inheritance in C++
C++ supports the following types of inheritance:
-
Single Inheritance
-
Multiple Inheritance
-
Multilevel Inheritance
-
Hierarchical Inheritance
- Hybrid Inheritance
1️⃣ Single Inheritance:-
#include <iostream>
using namespace std;
class c1{
public:
int a=5;
c1(){
cout<<"Hi i am c1"<<endl;
}
};
class c2:public c1{
public:
int b=6;
c2(){
cout<<"Hi i am c2"<<endl;
}
};
int main() {
c2 obj1;
cout<<obj1.a<<" "<<obj1.b;
return 0;
}
Output:-
Hi i am c1 Hi i am c2 5 6
2️⃣ Multiple Inheritance:-
#include <iostream>
using namespace std;
class c1{
public:
int a=5;
c1(){
cout<<"Hi i am c1"<<endl;
}
};
class c2{
public:
int b=6;
c2(){
cout<<"Hi i am c2"<<endl;
}
};
class c3:public c1,public c2{
public:
int d=7;
c3(){
cout<<"Hi i am c3"<<endl;
}
};
int main() {
c3 obj1;
cout<<obj1.a<<" "<<obj1.b<<" "<<obj1.d;
return 0;
}
Output:-
Hi i am c1 Hi i am c2 Hi i am c3 5 6 7
3️⃣ Multilevel Inheritance:-
#include <iostream>
using namespace std;
class c1{
public:
int a=5;
c1(){
cout<<"Hi i am c1"<<endl;
}
};
class c2:public c1{
public:
int b=6;
c2(){
cout<<"Hi i am c2"<<endl;
}
};
class c3:public c2{
public:
int d=7;
c3(){
cout<<"Hi i am c3"<<endl;
}
};
int main() {
c3 obj1;
cout<<obj1.a<<" "<<obj1.b<<" "<<obj1.d;
return 0;
}
Output:-
Hi i am c1 Hi i am c2 Hi i am c3 5 6 7
4️⃣ Hierarchical Inheritance:-
#include <iostream>
using namespace std;
class c1{
public:
int a=5;
c1(){
cout<<"Hi i am c1"<<endl;
}
};
class c2:public c1{
public:
int b=6;
c2(){
cout<<"Hi i am c2"<<endl;
}
};
class c3:public c1{
public:
int d=7;
c3(){
cout<<"Hi i am c3"<<endl;
}
};
int main() {
c3 obj1;
c2 obj2;
cout<<obj1.a<<" "<<obj1.d;
cout<<endl;
cout<<obj2.a<<" "<<obj2.b;
return 0;
}
Output:-
Hi i am c1 Hi i am c3 Hi i am c1 Hi i am c2 5 7 5 6
5️⃣ Hybrid Inheritance:-
#include <iostream>
using namespace std;
class c1{
public:
int a=5;
c1(){
cout<<"Hi i am c1"<<endl;
}
};
class c2: virtual public c1{
public:
int b=6;
c2(){
cout<<"Hi i am c2"<<endl;
}
};
class c3:virtual public c1,public c2{
public:
int d=7;
c3(){
cout<<"Hi i am c3"<<endl;
}
};
int main() {
c3 obj1;
c2 obj2;
cout<<obj1.a<<" "<<obj1.b<<" "<<obj1.d;
cout<<endl;
cout<<obj2.a<<" "<<obj2.b;
return 0;
}
Output:-
Hi i am c1 Hi i am c2 Hi i am c3 Hi i am c1 Hi i am c2 5 6 7 5 6