What is Inheritance in C++?

The class which inherits the members of another class is called derived class and the class whose members are inherited is called base class. The derived class is the specialized class for the base class.

Inheritance is a process in which one object acquires all the properties and behaviors of its parent object automatically. In such way, you can reuse, extend or modify the attributes and behaviors which are defined in other class.

C++ offers 5 types of inheritance:

  • Single inheritance - Where ‘A’ is the base class, and ‘B’ is the derived class.
  • Multiple inheritance - class ‘C’ inherits two base classes ‘A’ and ‘B’
  • Hierarchical inheritance
  • Multilevel inheritance - Class C inherits from Class B which in turn inherits from Class A
  • Hybrid inheritance - Mixed inheritance from all the other types.

CODE:


class Shape                 
{  
    public:  
    int a;  
    int b;  
    void get_data(int n,int m)  
    {  
        a= n;  
        b = m;  
    }  
};  
class Rectangle : public Shape  
{  
    public:  
    int rect_area()  
    {  
        int result = a*b;  
        return result;  
    }  
};  
class Triangle : public Shape   
{  
    public:  
    int triangle_area()  
    {  
        float result = 0.5*a*b;  
        return result;  
    }  
};