
Single Inheritance: In single inheritance, a class is allowed to inherit from only one class according to data structures in c++.. i.e. one subclass is inherited by one base class only.
Syntax: class sub_class : access_mode base_class { //body of subclass };
Example: // base class class Vehicle { public: Vehicle() { cout << "This is a Vehicle" << endl; } }; // sub class derived from two base classes class Car: public Vehicle { }; // main function int main() { // creating object of sub class will invoke the constructor of base classes Car obj; return 0; } Output:
This is a vehicle
Multiple Inheritance: In this type of inheritance a single derived class may inherit from two or more than two base classes. The constructors of inherited classes are called in the same order in which they are inherited.
Syntax : class sub_class : access_mode base_class1, base_class2 { //body of subclass };
Example :
class A { public: A() { cout << "A's constructor called" << endl; } }; class B { public: B() { cout << "B's constructor called" << endl; } }; class C: public B, public A { // Note the order public: C() { cout << "C's constructor called" << endl; } }; int main() { C c; return 0; }
Output:
B’s constructor called
A’s constructor called
C’s constructor called
Multilevel Inheritance: In this type of inheritance, a derived class is created from another derived class.Example:
class A { public: A() { cout << "A's constructor called" << endl; } }; class B : public A { public: B() { cout << "B's constructor called" << endl; } }; class C: public B { public: C() { cout << "C's constructor called" << endl; } }; int main() { C c; return 0; }
Output:
A’s constructor called
B’s constructor called
C’s constructor called
Hierarchical Inheritance: In this type of inheritance more than one subclass inherits from a single base class.
Example:
// base class class A { public: A() { cout<<"This is A’s constructor"<< endl; } }; // first sub class class B: public A { }; // second sub class class C: public A { }; // main function int main() { /* creating object of sub class will invoke the constructor of base class */ B obj1; C obj2; return 0; } Output:
This is A’s constructor
This is B’s constructor
Hybrid Inheritance: It a combination of Hierarchical and Multilevel Inheritance.Example:
// base class class A { public: A() { cout << "This is A" << endl; } }; //base class class B { public: B() { cout<<"This is B " <<endl; } }; // first sub class class C: public A { }; // second sub class class D: public A, public B { }; // main function int main() { // creating object of sub class will invoke the constructor of base //class D d; return 0; }
Output:
This is A
This is B
So, in this blog, we have tried to explain different types of Inheritance in c++. If you want to improve your foundation in any language including C,C++,Java,Python then you can follow this link Prepbyte Courses.