Site icon DataFlair

Explore the 5 Types of Inheritance in C++ with Syntax & Example

We all are familiar with the literal meaning of the term Inheritance i.e. deriving properties from ancestors. In programming terminology, Inheritance in C++ means inheriting the characteristics or properties of the parent class.

In this C++ tutorial, you are getting each and everything to master the concept of C++ Inheritance. Let’s start with the proper explanation with a real-life example.

1. What is Inheritance in C++?

As the name itself suggests, Inheritance is nothing but the ability of a class to inherit all the characteristics of another class.
It is one of the most significant features of object-oriented programming in C++.

Let us consider a real-life example.

A class named ‘Insect’ inherits its properties from another class ‘Arthropoda’ which itself inherits from another class ‘Animalia’.

Similarly, implementing the concept of inheritance allows you to generate a real-world model.

Before we discuss the example, you should know the concept of Constructor and Destructor in C++

C++ Inheritance Example

Suppose there are 3 sections in the 12th grade of your school: A, B, and C.

The functions that we need to perform in each class are taking the attendance, distributing newspapers to students who subscribed for it, and giving them their final grades.

This is how the above task would look like without using inheritance in C++:

After using inheritance, this task is easily simplified:

There are two terms you need to be familiar with in order to understand inheritance in C++.

2. Importance of Inheritance in C++

There are numerous reasons as to why the concept of inheritance was introduced in C++. Here are some of the reasons why:

Let us first try to understand what transitive means.

If a = b and b = c, by transitive law, a =c.

Similarly, if class B inherits all the properties of class A and class C inherits all the properties of class B, then class C has properties of both classes A and class B.

Key takeaway:

3. Types of Inheritance in C++

There are basically 5 types of inheritance in C++. The classification of inheritance is based on how the properties of the base class are inherited by the derived class(es).

3.1 Single Inheritance

This type of inheritance in C++ happens when the parent class has only one child class. In other words, this is only one derived class formed from a base class.

Syntax-

class Base
{
// BODY OF THE BASE CLASS
};
class Derived : acess_specifier Base
{
// BODY OF THE DERIVED CLASS
};

Let’s revise the concept of Classes and Objects in C++

Single Inheritance in C++ with Example

Let us better understand the concept by considering a C++ inheritance example:

#include <iostream> 
using namespace std;

class Base
{
public:
int base_value;
void base_input()
{
cout<<"Enter the integer value of base class: ";
cin>>base_value;
}
};
class Derived : public Base 
{
// private by default
int derived_value;
public:
void derived_input()
{
cout<<"Enter the integer value of derived class: ";
cin>>derived_value;
}
void sum()
{
cout << "The sum of the two integer values is: " << base_value + derived_value<<endl;
}
};

int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

Derived d; // Object of the derived class
d.base_input();
d.derived_input();
d.sum();
return 0;
}

Code-

Output-

3.2 Multiple Inheritance

This type of inheritance happens when the child class inherits its properties from more than one base class. In other others, the derived class inherits properties from multiple base classes.

Syntax

class A // Base class of B
{
// BODY OF THE CLASS A
};
class B // Derived class of A and Base class
{
// BODY OF THE CLASS B
};
class C : acess_specifier A, access_specifier A // Derived class of A and B
{
// BODY OF CLASS C
};

Do you know why Functions in C++ are important?

Example of Multiple Inheritance in C++

Let us better understand the concept of multiple inheritances by considering a C++ inheritance example:

#include<iostream> 
using namespace std;
class A
{
public:
int A_value;
void A_input()
{
cout<<"Enter the integer value of class A: ";
cin>>A_value;
}
};
class B
{
public:
int B_value;
void B_input()
{
cout<<"Enter the integer value of class B: ";
cin>>B_value;
}
};
class C : public A, public B //C is a derived class from classes A and B
{
public:
void difference()
{
cout<<"The difference between the two values is: " << A_value - B_value<<endl;
}
};

int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

C c; // c is an Object of derived class C
c.A_input();
c.B_input();
c.difference();
return 0;
}

Code-

Output-

3.3 Hierarchical Inheritance

When multiple child classes inherit their properties from just a single base class.

Syntax

class A // Base class of B
{
// BODY OF THE PROGRAM
};
class B : access_specifier A // Derived class of A
{
// BODY OF THE PROGRAM
};
class C : access_specifier A // Derived class of A
{
// BODY OF THE PROGRAM
};
class D : access_specifier A // Derived class of A
{
// BODY OF THE PROGRAM
};

Wait!! It’s time to uncover the secret behind Polymorphism in C++

Example of Hierarchical Inheritance in C++

Let us better understand the concept of hierarchical inheritance by considering C++ inheritance example:

#include <iostream> 
using namespace std;

class A 
{
public:
int x, y;
void A_input()
{
cout<<"Enter two values of class A: "; 
cin>>x>>y;
}
};
class B : public A // B is derived from A
{
public:
void product()
{
cout<<"The Product of the two values is: "<< x * y<<endl;
}
};
class C : public A //C is derived from A
{
public:
void division()
{
cout<<"The Division of the two values is: "<< x / y<<endl;
}
};
int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

B b; // Object b of derived class B
C c; // Object c of derived class C
b.A_input();
b.product();
c.A_input();
c.division();
return 0;
}

Code-

Output-

3.4 Multilevel Inheritance

This type of inheritance is the best way to represent the transitive nature of inheritance. In multilevel inheritance, a derived class inherits all its properties from a class that itself inherits from another class.

Syntax

class A // Base class
{
// BODY OF CLASS A
};
class B : acess_specifier A // Derived class of A
{
// BODY OF CLASS B
};
class C : access_specifier B // Derived from derived class B
{
// BODY OF CLASS C
};

Learn Data Encapsulation in C++ with Example in just 3 min

Example of Multilevel Inheritance in C++

Let us better understand the concept of multilevel inheritance by considering a C++ inheritance example:

#include <iostream>
using namespace std;

class Base
{
public:
int base_value;
void Base_input()
{
cout<<"Enter the integer value of base class: "; 
cin>>base_value;
}
};
class Derived1 : public Base // Derived class of base class
{
public:
int derived1_value;
void Derived1_input()
{
cout<<"Enter the integer value of first derived class: "; 
cin>>derived1_value;
}
};
class Derived2 : public Derived1 // Derived class of Derived1 class
{
// private by deafult
int derived2_value;
public:
void Derived2_input()
{
cout<<"Enter the integer value of the second derived class: "; 
cin>>derived2_value;
}
void sum()
{
cout << "The sum of the three intger values is: " << base_value + derived1_value + derived2_value<<endl;
}
};
int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

Derived2 d2; // Object d2 of second derived class
d2.Base_input();
d2.Derived1_input();
d2.Derived2_input();
d2.sum();
return 0;
}

Code-

Output-

3.5 Hybrid Inheritance

This type of inheritance essentially combines more than two forms of inheritance discussed above. For instance, when a child class inherits from multiple base classes all of its parent classes and that child class itself serves as a base class for 3 of its derived classes.

There are various combinations that can be made in hybrid inheritance. For instance:

Syntax

class A
{
// BODY OF THE CLASS A
};
class B : public A
{
// BODY OF THE CLASS A
};
class C
{
// BODY OF THE CLASS A
};
class D : public B, public C
{
// BODY OF THE CLASS A
};

Why don’t you try your hands in Data Abstraction in C++

Example of Hybrid Inheritance in C++

Let us better understand the concept of hybrid inheritance by considering a C++ inheritance example:

#include <iostream>
using namespace std;

class A
{
public:
int A_value;
};
class B : public A
{
public:
B() // Use of a constructor to initialize A_value
{
A_value = 20;
}
};
class C
{
public:
int C_value;
C() //Use of a constructor to initialize C_value
{
C_value = 40;
}
};
class D : public B, public C // D is derived from class B and class C
{
public:
void product()
{
cout<<"The product of the two integer values is: " << A_value * C_value<<endl;
}
};

int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

D d; // Object d of derived class D
d.product();
return 0;
}

Code-

Output-

4. Base Class and Derived Class in C++

As discussed earlier, a derived class in C++ is also called a child class or a subclass and a C++ base class is also called a parent class or a superclass.

While writing a C++ program, it is our duty to identify the class from which the derived class is being derived, that is, its base class.

Syntax 

class name_of_derived_class : visibilty_mode name_of_base_class
{
// BODY OF THE CLASS
};

The name of the derived class is followed by a colon ‘:’ followed by the visibility mode which is again followed by the name of the base class.

4.1 Visibility Modes in C++

There are 3 types of visibility modes in C++, that is:

4.1.1 public

The public visibility mode allows the derived class to access the public and protected but not private members of the base class

Here is a diagrammatic representation of how it works:

4.1.2 private

The private visibility mode allows the derived class to access the public and protected members of the base class privately.

Here is a diagrammatic representation of how it works:

4.1.3 protected

The protected visibility mode allows the derived class to access the public and protected members of the base class in the protected mode.

Here is a diagrammatic representation of how it works:

It helps the user to specify how the features of the base class are derived from the derived class.

Let us try to understand each visibility mode with the help of a C++ code fragment:

class Base 
{
public:
int a;
protected:
int b;
private:
int c;
};

class Derived_Public : public Base
{
/* a is public
b is protected
c is inaccessible */
};

class Derived_Protected : protected Base
{
/* a is protected
b is protected
c is inaccessible */
};

class Derived_private : private Base
{
/* a is private
b is private
c is inaccessible */
}

5. Access Control in C++

We have seen that during inheritance, all the properties of the base class are transferred to its derived classes. But, we might encounter certain situations where you don’t want the derived classes to be able to access all the properties, but rather only a few properties. We can control this activity with the help of the concept of access control of the inheritance.

We will discuss how access control is done in the publicly and privately derived class.

5.1 Publicly Derived Class

It is pretty obvious that a class is said to be derived publicly when the keyword ‘public’ is preceded over its class name.

For instance,

class Teacher : public Student, public Person
{

//BODY OF THE CLASS

};

Here, the keyword public refers to the object of the derived class that has permission to access the public members of the base class as if they were the public members of their own class.

5.2 Privately Derived Class

Again, it is pretty obvious that a class is said to be derived privately when the keyword ‘private’ is preceded over its class name.

For instance,

class Teacher : private Student
{

//BODY OF THE CLASS

};

Here, the keyword private means that the public and protected members of the base class can directly be accessed with the help of member functions or friend functions of the derived class as if they were the private members of the derived class.

It is important to note that the public and protected members of the base class act as the private members of the derived class.

Here is a table that summarizes the access restrictions in inheritance:

Access Mode
Base Class Member
Derived Class Member
public public public
protected protected
private
INACCESSIBLE
protected public protected
protected protected
private
INACCESSIBLE
private public private
protected private
private
INACCESSIBLE

6. Quiz on Inheritance in C++

Time limit: 0

Quiz Summary

0 of 15 Questions completed

Questions:

Information

You have already completed the quiz before. Hence you can not start it again.

Quiz is loading…

You must sign in or sign up to start the quiz.

You must first complete the following:

Results

Quiz complete. Results are being recorded.

Results

0 of 15 Questions answered correctly

Your time:

Time has elapsed

You have reached 0 of 0 point(s), (0)

Earned Point(s): 0 of 0, (0)
0 Essay(s) Pending (Possible Point(s): 0)

Categories

  1. Not categorized 0%
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  1. Current
  2. Review / Skip
  3. Answered
  4. Correct
  5. Incorrect
  1. Question 1 of 15
    1. Question

    #include <bits/stdc++.h>

    using namespace std;

     

    class Base

    {

        public:

          int b;

    };

     

    class inherit : public Base

    {

        public:

          int i;

    };

     

    int main()

       {

          

            inherit obj1;

            obj1.i = 1;

            obj1.b = 2;

            cout <<obj1.i <<obj1.b;

             

            return 0;

       }

    Correct
    Incorrect
  2. Question 2 of 15
    2. Question

    #include <bits/stdc++.h>

    using namespace std;

     

    class Base

    {

        public:

          int b;

    };

     

    class inherit : public Base

    {

        public:

          int i;

    };

     

    int main()

       {

          

            Base obj1;

            obj1.i = 1;

            obj1.b = 2;

            cout <<obj1.i <<obj1.b;

             

            return 0;

       }

    Correct
    Incorrect
  3. Question 3 of 15
    3. Question

    #include <bits/stdc++.h>

    using namespace std;

     

    class Base

    {

        private:

          int b;

    };

     

    class inherit : public Base

    {

        public:

          int i;

    };

     

    int main()

       {

          

            inherit obj1;

            obj1.i = 1;

            obj1.b = 2;

            cout <<obj1.i <<obj1.b;

             

            return 0;

       }

    Correct
    Incorrect
  4. Question 4 of 15
    4. Question

    #include <iostream>

    using namespace std;

     

    class base {

      public:

        base()

        {

          cout << “hi”;

        }

    };

    class inherit: public base{

     

    };

     

    int main()

        inherit obj;

        return 0;

    }

    Correct
    Incorrect
  5. Question 5 of 15
    5. Question

    #include <iostream>

    using namespace std;

     

    class base {

      public:

        base()

        {

          cout << “hi”;

        }

    };

    class inherit: public base{

     

     public:

     inherit()

     {

         cout<<“fi”;

     }

    };

     

    int main()

        inherit obj;

        return 0;

    }

     

    Correct
    Incorrect
  6. Question 6 of 15
    6. Question

    #include <iostream>

    using namespace std;

     

    class base {

      public:

        base()

        {

          cout << “1”;

        }

    };

    class inherit: public base{

     

      public:

        inherit()

        {

          cout << “2”;

        }

    };

    class inherit1: public inherit{

     

    public:

        inherit1()

        {

          cout << “3”;

        }

    };

    int main()

        inherit1 obj;

        return 0;

    }

    Correct
    Incorrect
  7. Question 7 of 15
    7. Question

    #include <iostream>

    using namespace std;

     

    class base {

      public:

        base()

        {

          cout << “1”;

        }

    };

    class inherit: public base{

     

      public:

        inherit()

        {

          cout << “2”;

        }

    };

    class inherit1: public base{

     

    public:

        inherit1()

        {

          cout << “3”;

        }

    };

    int main()

        inherit1 obj;

        return 0;

    }

    Correct
    Incorrect
  8. Question 8 of 15
    8. Question

    #include <iostream>

    using namespace std;

     

    class base {

      public:

        base()

        {

          cout << “1”;

        }

    };

    class inherit{

      public:

        inherit()

        {

          cout << “2”;

        }

    };

    class in: public base, public inherit{

     

    };

    int main()

        in obj;

        return 0;

    }

    Correct
    Incorrect
  9. Question 9 of 15
    9. Question

    #include <iostream>

    using namespace std;

     

    class base {

      public:

        base()

        {

          cout << “1”;

        }

    };

    class inherit: public base{

      public:

        inherit()

        {

          cout << “2”;

        }

    };

    class in: public base, public inherit{

     

    };

    int main()

        in obj;

        return 0;

    }

    Correct
    Incorrect
  10. Question 10 of 15
    10. Question

    #include <iostream>

    using namespace std;

     

    class base {

      public:

        base()

        {

          cout << “1”;

        }

    };

    class inherit: public base{

      public:

        inherit()

        {

          cout << “2”;

        }

    };

    class in: public inherit, public base{

     

    };

    int main()

         in obj;

         

        return 0;

    }

    Correct
    Incorrect
  11. Question 11 of 15
    11. Question

    Which among the following is a mode of inheritance?

    Correct
    Incorrect
  12. Question 12 of 15
    12. Question

     Identify the type of inheritance where a drive class is created by another derived class.

    Correct
    Incorrect
  13. Question 13 of 15
    13. Question

     Identify the type of inheritance where more than one sub class is inherited from one base class.

    Correct
    Incorrect
  14. Question 14 of 15
    14. Question

    Identify the type of inheritance where more than one type of inheritance is combined.

    Correct
    Incorrect
  15. Question 15 of 15
    15. Question

     Identify the type of inheritance where a class can inherit from more than one class.

    Correct
    Incorrect

7. Summary

Now you know the why Inheritance in C++ is important with some real-life examples. After developing an understanding of inheritance, we found motivation for studying this concept by discussing its significance. Thereafter, we carried on our discussion by studying the 5 major types of Inheritance with the help of diagrams and illustrative programs. Then, we discussed the visibility mode as a sub-topic of the derived class and base class.

Finally, we concluded our discussion by understanding the access control in inheritance in all the 3 modes. After completing this tutorial, it is safe is to say that we have developed a rigorous understanding of Inheritance in C++ and we are ready to deal with programs involving any of the 5 types of Inheritance.

Feel free to share your suggestions and queries in the comment section.

Next move – Different types of loops in C++ (An essential concept for every beginner)

Exit mobile version