Inheritance types in C++
Inheritance types in C++
Inheritance types in C++ are as follows
-
-
Single Inheritance
-
Multilevel Inheritance
-
Multiple Inheritance
-
Hierarchical Inheritance
-
1. Single Inheritance
In single-level inheritance, there is only one base class and has only one derived class. It is the simplest form of inheritance
Syntax of single inheritance
class subclass_name : access_mode base_class { //body };
Program of single inheritance
#include <iostream> using namespace std; // base class class Bike { public: Bike() { cout << "This is a Bike" << endl; } }; // sub class derived from a single base classes class Car: public Bike{ }; // main function int main() { Car obj; return 0; }
Output
This is a Bike
2. Multilevel Inheritance in C++
In multilevel inheritance, there will be a chain of inheritance with a class derived from only one parent and will have only one child class.
In multilevel inheritance, the derived class inherits from a class, which in turn inherits from some other class. The super class for one is sub-class for the other. It is also called the level of inheritance
Program of multilevel inheritance
#include <iostream> using namespace std; class Bike { public: Bike() { cout << "This is Bike" << endl; } }; class twoWheeler: public Bike { public: twoWheeler() { cout<<"Objects with 2 wheels are Bike"<<endl; } }; class Bike: public twoWheeler{ public: Car() { cout<<"Bike has 2 Wheels"<<endl; } }; // main function int main() { Bike obj; return 0; }
Output
This is a Bike Objects with 2 wheels are Bike Bike has 2 Wheels
3. Multiple Inheritance
In multiple inheritance, a one derived class inherit from two or more than two-parent classes
Program of multiple inheritance
#include <iostream> using namespace std; // first base class class Bike { public: Bike() { cout << "This is a Bike" << endl; } }; // second base class class twoWheeler { public: twoWheeler() { cout << "This is a 2 wheeler Bike" << endl; } }; class Car: public Bike, public twoWheeler { }; // main function int main() { Car obj; return 0; }
Output
This is a Bike This is a 2 wheeler Bike
4. Hierarchical Inheritance
In this type of inheritance, multiple derived classes inherit from a single parent class
Program of hierarchical inheritance
#include <iostream> using namespace std; class Bike { public: Bike() { cout << "This is a Bike" << endl; } }; class Car: public Bike { }; // second sub class class Bus: public Bike { }; // main function int main() { Car obj1; Bus obj2; return 0; }
Output
This is a Bike This is a Bike
Read more, Function Overriding in C++