Browse by Domains

C++ Inheritance

In our daily lives, we often hear people say that you are like your mom; some say you are like your dad, some say your nose is like your grandfather, etc. But have you questioned yourself how all of them have a resemblance to you? The answer is INHERITANCE      

What is Inheritance?

Inheritance is basically a process in which the traits of our ancestor or we can say of our parents are transferred from them to us.

     Like humans,object oriented language C++ also follows the same concept.

What is C++ inheritance?

  • C++ inheritance is defined as a mechanism in which one class can access the property and attributes from an existing class.
  • Inheritance provides Reusability and Maintainability of code
  1. Reusability : Since you are creating a new class using an existing class. So you don’t have  to type in all the data members and member function and all the feature of that class again. Reusing already tested and debugged class will saves a lot of effort and time of developing and debugging the same thing again.
  2. Maintainbility : When the property of the existing class changes automatically the new class gets those property. So we don’t have to make changes two times.
  • In Inheritance, the class from which the new class inherits properties (data members and member function) is called Base and the newly created class is called Class Derived Class.

    Syntax :
 class derived-class name: access specifier base-class  name
       {
      body of class which includes data members and member functions  of the derived class
       }

Example:

          Suppose we have a class named Vehicle. The subclass of this class may share similar properties such as wheels and motor etc. Additionally, a child class may have its own particular characteristics and personal traits. For example, a subclass Bus may have seats for people but another subclass truck may have space to carry goods.

       A class of software can be divided into subclasses like windows, linux, ubunto, android. A class of vehicles could be divided into subclasses like cars, trucks, buses and motorcycles. A class of shapes can be divided into ellipses, line, boxes etc.

Also Read: C++ Interview questions

TYPES OF INHERITANCE 

  1. Single Inheritance
  2. Multiple Inheritance
  3. Multi-level Inheritance
  4. Hierarchical Inheritance
  5. Hybrid Inheritance

1.SINGLE INHERITANCE :

        A Inheritance in which a derived class is with only one base class. The derived class in the inheritance inherits all data members and member functions of the base class. It can also further have its own capabilities.

  ↓

where A is base class and B is derived class.

  • PARENT CLASS IS ANOTHER NAME FOR BASE CLASS.
  • CHILD CLASS IS ANOTHER NAME FOR DERIVED CLASS.
  • Visibility Modes           

 Visibility modes are classified into three types

  • Public: When the visibility mode is public. All the data members and member functions are accessible to all the functions of the program. 
  • Private: When the visibility mode is private. All the data members and member functions are accessible within the class only.
  • Protected: When the visibility mode is protected. All the data members and member functions are accessible within its own class as well as the class immediately derived from it.
  • Public Inheritance :

In public inheritance, the accessibility of parent class members in the derived class remains the same. The public members of the parent class become public members of the derived class. The protected members of parent class become protected members of derived class and the private members of base class become private members of derived class.

                   Derived class can access the following in public inheritance:

  • The public members of the parent class are accessible to the derived class.
  • The protected members of the parent class are accessible to the derived class.
  • The private members of the parent class are not accessible to the derived class.

    The object can access the following in public inheritance:

  • The public members of parent class are accessible to object of derived class.
  • The protected members of parent class are not accessible to object of derived class.
  • The private members of parent class are not accessible to object of derived class.

Example: Write a program that declares two classes and define a relationship between them using public inheritance:

#include <iostream>  
using namespace std;  
  class Parent
 {  
   public:  
   int a;
   protected:    
   int b;
   private:    
   int c;
 };  
   class Child: public Parent {  
   public:  
   void In()
 {
   cout<<”Enter a:”;
   cin>>a;
   cout<<”Enter b:”;
   cin>>b;
  }
   void Out()
   {
     cout<<"a "<<a<<endl;    
     cout<<"b"<<b<<endl;    
    }
   };       
   int main(void)
   {  
     Child obj;  
     obj.In();
     obj.Out();
     getch();  
   }

Output:

   Enter a:10

   Enter b:20

   a=10

   b=20

How does the above program work?

                 The above program declares two classes. The parent class has three data members ‘a’ declared as public, ’b’ declared as protected, ‘c’ declared as private. The Child class inherits the member function of the parent class with public inheritance. The child class can access public and protected data members but not the private data members of the parent class in public inheritance.

  • Protected Inheritance :

                     In Protected Inheritance, the access status of the parent class members in the child class is restricted. The public members of the parent class become protected members of the child class. The private members of the parent class become private members of the child class.

               The Derived class can access the following in protected inheritance:

  • The public members of the parent class are accessible to the derived class.
  • The protected members of the parent class are accessible to the derived class.
  • The private members of the parent class are not accessible to the derived class.

    The object can access the following in protected inheritance:

  • The public members of the parent class are not accessible to the object of the derived class.
  • The protected members of the parent class are not accessible to the object of derived class.
  • The private members of parent class are not accessible to the object of derived class.

Example:

#include <iostream>  
using namespace std;  
  class Parent
 {  
   public:  
   int a;
   protected:    
   int b;
   private:    
   int c;
 };  
   class Child: protected Parent {  
   public:  
   void In()
 {
   cout<<”Enter a:”;
   cin>>a;
   cout<<”Enter b:”;
   cin>>b;
  }
   Void Out()
   {
     cout<<"a "<<a<<endl;    
     cout<<"b"<<b<<endl;    
    }
   };       
   int main(void)
   {  
     Child obj;  
     obj.In();
     obj.Out();
     getch();  
   }

Output:

   Enter a:50

   Enter b:100

   a=50

   b=100

How does the above program work?

                 The above program declares two classes. The parent class has three data members ‘a’ declared as public, ’b’ declared as protected, ‘c’ declared as private. The Child class inherits the parent class with protected inheritance. The child class can access public and protected data members but not the private data members of the parent class. The main difference between public and protected inheritance is that public members of the parent class become protected for child class in protected inheritance.

  • Private Inheritance :

                     In this, the access status of parent class members in the child class is restricted. The public, protected and private members of the parent class all become private members of child class.

               The Derived class can access the following in private inheritance:

  • The public members of the parent class are accessible to the derived class.
  • The protected members of the parent class are  accessible to the derived class.
  • The private members of the parent class are not accessible to the derived class.

    The object can access the following in private inheritance:

  • The public members of the parent class are not accessible to the object of the derived class.
  • The protected members of the parent class are not accessible to the object of the derived class.
  • The private members of parent class are not accessible to the object of derived class.

Example:

#include <iostream>  
using namespace std;  
  class Parent
 {  
   public:  
   int a;
   protected:    
   int b;
   private:    
   int c;
 };  
   class Child: private Parent {  
   public:  
   void In()
 {
   cout<<”Enter a:”;
   cin>>a;
   cout<<”Enter b:”;
   cin>>b;
  }
   void Out()
   {
     cout<<"a "<<a<<endl;    
     cout<<"b"<<b<<endl;    
    }
   };       
   int main(void)
   {  
     Child obj;  
     obj.In();
     obj.Out();
     getch();  
   }

How does the above program work?

                 The above program declares two classes. The parent class has three data members ‘a’ declared as public, ’b’ declared as protected, ‘c’ declared as private. The Child class inherits the parent class with private inheritance. The child class can access public and protected data members but not the private data members of the parent class. The main difference between private and other inheritance is that all data members of the parent class become private members for child class. Any class that inherits the child class cannot access any member of the child class.

  • C++ Single Level Inheritance Example: Inheriting Fields

   Let’s see the example of a single level inheritance that inherits the fields only.

#include <iostream>  
using namespace std;  
  class Library
 {  
   public:  
   float price = 60;   
 };  
   class Book: public Library {  
   public:  
   float reg_no = 50;    
   };       
   int main(void)
   {  
     Book b1;  
     cout<<"price: "<<b1.price<<endl;    
     cout<<"reg_no: "<<b1.reg_no<<endl;    
    return 0;  
}  

Output:

price: 60

reg_no: 50

In the above example, Library is the base class and Book is the derived class.

C++ Single Level Inheritance Example: Inheriting Methods

Let’s see another example of inheritance in C++ which inherits methods only.

#include <iostream>  
using namespace std;  
 class Human {  
   public:  
 void talk() {   
    cout<<"Talking..."<<endl;   
 }    
   };  
   class Boy: public Human    
   {    
       public:  
     void walk(){  
    cout<<"Walking...";   
     }    
   };   
int main(void) {  
    Boy b1;  
    b1.talk();  
    b1.walk();  
    return 0;  
}  

Output:

Talking…

Walking…

  • Let’s see a simple example.
#include <iostream>  
using namespace std;  
class Num 
{  
    int a = 2;  
    int b = 3;  
    public:  
    int mul()  
    {  
        int c = a*b;  
        return c;  
    }     
};  
  
class Result: private Num  
{  
    public:  
    void display()  
    {  
        int result = mul();  
        std::cout <<"Multiplication of a and b is : "<<result<< std::endl;  
    }  
};  
int main()  
{  
   Result r;  
   r.display();  
  
    return 0;  
}  

Output:

Multiplication of a and b is : 6

In the above example, class A is privately inherited. Therefore, the mul() function of class ‘A’ cannot be accessed by the object of class B. It can only be accessed by the member function of class B.     

2.Multilevel Inheritance

Multilevel inheritance is a type of inheritance in which a class is derived from another derived class. Here, the members of the parent class are inherited to the child class and the members of the child class are inherited to the grand child class. In this way, the members of the parent class and child class are combined in the grand child class.

C++ Inheritance

Multi Level Inheritance Example

When the parent class inherits a child class which is further inherited by the grandchild class, it is known as multi-level inheritance in C++. Inheritance takes place futhermore so the last derived class acquires all the members of all its base classes.

The example of multi-level inheritance in C++.

#include <iostream>  
using namespace std;  
 class Human{  
   public:  
 void talk() {   
    cout<<"Talking..."<<endl;   
 }    
   };  
   class Father: public Human   
   {    
       public:  
     void walk(){  
    cout<<"Walking..."<<endl;   
     }    
   };   
   class Son: public Father   
   {    
       public:  
     void run() {  
    cout<<"Running...";   
     }    
   };   
int main(void) {  
    Son s1;  
    s1.talk();  
    s1.walk();  
     s1.run();  
     return 0;  
}  

Output:

Talking…

Walking…

Running…

3.Multiple Inheritance

Multiple inheritance is the type of inheritance in which a derived class inherits multiple base classes. In multiple inheritance, the derived class combines the members of all the base classes.

C++ Inheritance

Syntax of the Derived class:

class Child_class : visibility parent_class1, visibility parent_class2,…. 
{  
    // Body of the class;  
}  

Let’s see a simple example of multiple inheritance.

#include <iostream>  
using namespace std;  
class A  
{  
    private:  
     int a;  
    public:  
    void In()  
    {  
    cout<<”Enter a:”;
   cin>>a;
    }  
     void Out()  
     {
       cout<<”a=”<<a<<endl;
     }
};  
  
class B  
{  
    private:  
    int b;  
    public:  
        void Input()  
    {  
    cout<<”Enter b:”;
   cin>>b;
    }  
     void Output()  
     {
       cout<<”b=”<<b<<endl;
     }
};  
class C : public A,public B  
{  
   private c:  
    int c;  
    public:  
        void get()  
    {  
         A::In();
         B::Input();
    cout<<”Enter c:”;
   cin>>c;
    }  
     void Show()  
     {
          A::Out();
         B::Output();
         cout<<”c=”<<c<<endl;
     }
  };  
   int main()  
 {  
    C c;  
    c.get();  
   c.show();  
   getch();  
  
    return 0;  
}  

Output:

Enter a : 10

Enter b : 20

Enter c : 30

a=10

b=20

c=30

In the above example, class ‘C’ inherits two base classes ‘A’ and ‘B’ in a public mode.

Ambiguity Resolution in Multiple Inheritance

Ambiguity occurs in the multiple inheritance when a function with the same name occurs in more than one parent class. One of the most serious issues in multiple inheritance is the issue of ambiguity. When the names of functions are similar in two or more parent classes the ambiguity is created. The compiler cannot determine which function to execute when the object of derived class attempts to execute such function.

Let’s understand this through an example:

#include <iostream.h>
#include<conio.h>  


using namespace std;  
class A  
{  
    public:  
    void show()  
    {  
        cout << "Class A" << endl;  
    }  
};  
class B  
{  
    public:  
    void show()  
    {  
        cout << "Class B" << endl;  
    }  
};  
class C : public A, public B  
{  
    void view()  
    {  
      show();  
    }  
};  
int main()  
{  
    C c;  
    c.show();  
    return 0;  
}  

Output:

error: reference to ‘show’ is ambiguous

show();

How does the above program work?

             The above program declares three classes. The class A and class B both have the member function show(). The class C inherits both classes. The program declares an object of class C. The object has two functions with the same name show(). One function comes from class A and second comes from class B. The compiler will generate an error when the above program is compiled.

Removing Ambiguity

   The ambiguity can be removed from the above program as follows:

obj.A::show();

obj.B::show();

  Another way to remove ambiguity in multiple inheritance is to overload both function in derived class as follows:

#include <iostream.h>
#include<conio.h>  


using namespace std;  
class A  
{  
    public:  
    void show()  
    {  
        cout << "Class A" << endl;  
    }  
};  
class B  
{  
    public:  
    void show()  
    {  
        cout << "Class B" << endl;  
    }  
};  
class C : public A, public B  
{ 
    public 
    void show()  
    {  
      A::show();
      B::show();
      cout<<"Class C" <<endl;  
    }  
};  
int main()  
{  
    C c;  
    c.show();  
    return 0;  
}  

4.Hybrid Inheritance

When two or more combinations of inheritance occur together is called Hybrid Inheritance.

C++ Inheritance

Let’s see a simple example:

#include <iostream>  
using namespace std;  
class A  
{  
    protected:  
    int a;  
    public:  
    void in_a()  
    {  
       std::cout << "Enter the value of 'a' : " << std::endl;  
       cin>>a;  
    }  
};  
  
class B : public A   
{  
    protected:  
    int b;  
    public:  
    void in_b()  
    {  
        std::cout << "Enter the value of 'b' : " << std::endl;  
       cin>>b;  
    }  
};  
class C   
{  
    protected:  
    int c;  
    public:  
    void in_c()  
    {  
        std::cout << "Enter the value of c is : " << std::endl;  
        cin>>c;  
    }  
};  
  
class D : public B, public C  
{  
    protected:  
    int d;  
    public:  
    void mul()  
    {  
         in_a();  
         in_b();  
         in_c();  
         std::cout << "Multiplication of a,b,c is : " <<a*b*c<< std::endl;  
    }  
};  
int main()  
{  
    D d;  
    d.mul();  
    return 0;  
}  

Output:

Enter the value of ‘a’ :

10              

Enter the value of ‘b’ :    

20      

Enter the value of c is :   

30  

Multiplication of a,b,c is : 6000

5.Hierarchical Inheritance

Hierarchical inheritance is defined as the process of deriving more than one class from a base class. In these inheritance we can have multiple child classes from a single parent class.

C++ Inheritance

Syntax of Hierarchical inheritance:

class A  
{  
    // body of the class A.  
}    
class B : public A   
{  
    // body of class B.  
}  
class C : public A  
{  
    // body of class C.  
}   
class D : public A  
{  
    // body of class D.  
} 

Let’s see a simple example:

#include <iostream>  
using namespace std;  
class Shape                 // Declaration of base class.  
{  
    public:  
    int a;  
    int b;  
    void in(int n,int m)  
    {  
        a= n;  
        b = m;  
    }  
};  
class Rectangle : public Shape  // inheriting Shape class  
{  
    public:  
    int rect_area()  
    {  
        int area = a*b;  
        return area;  
    }  
};  
class Triangle : public Shape    // inheriting Shape class  
{  
    public:  
    int triangle_area()  
    {  
        float area = 0.5*a*b;  
        return area;  
    }  
};  
int main()  
{  
    Rectangle r;  
    Triangle t;  
    int length,breadth,base,height;  
    std::cout << "Enter the length and breadth of a rectangle: " << std::endl;  
    cin>>length>>breadth;  
    r.in(length,breadth);  
    int m = r.rect_area();  
    std::cout << "Area of the rectangle is : " <<m<< std::endl;  
    std::cout << "Enter the base and height of the triangle: " << std::endl;  
    cin>>base>>height;  
    t.get_data(base,height);  
    float n = t.triangle_area();  
    std::cout <<"Area of the triangle is : "  << n<<std::endl;  
    return 0;  
}

Output:

Enter the length and breadth of a rectangle:

23  

20  

Area of the rectangle is : 460          

Enter the base and height of the triangle:  

2   

5

Area of the triangle is : 5 

If you are interested in learning c/c++ in detail you can join this free course and also practice coding with the help of a great learning academy.

Avatar photo
Great Learning Team
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

Your email address will not be published. Required fields are marked *

Great Learning Free Online Courses
Scroll to Top