Understanding Inheritance In C++

There are so many programming languages today, all with their advantages and limitations. These programming languages follow different operating principles to solve problems. The object-oriented technique is a type of programming language that looks upon a problem and solves it in terms of objects. It pays less heed to the procedure it follows. 

For example, consider the case of simulating traffic flow at a red light crossing. This problem in an OOP paradigm is viewed in terms of the objects involved, which are cars, trucks, buses, scooters, taxis, and people crossing by. These objects have some characteristics as well. Like a four-wheeler vehicle has a steering wheel, motor brakes, etc. and its behavior is its mobility.  So, here a car is an object for a class named Vehicle.

Overview of C++

The C++ programming language is based on the paradigm of Object-Oriented Programming (OOPs). Object-Oriented Programming is an umbrella under which the features of Object-Based programming reside. It consists of all the characteristics of object-based programming and gets the better of its limitations by executing inheritance. This way, through programming, you can solve problems based on real-life situations. 

Object-oriented programming was created to get better at the drawbacks of usual programming techniques. The OOPs method was developed based on concepts that make it achieve its aim of overcoming its drawbacks or deficiencies in usual programming techniques. 

FREE Java Certification Training

Learn A-Z of Java like never beforeEnroll Now
FREE Java Certification Training

The basic concepts of OOPs are the pillars of C++ and separate C++ conceptually from the traditional procedural paradigm. These general concepts of OOP are given below:

  • Data Abstraction:

Abstraction is referred to as the concept of giving access to only those details that are required to perform a specific task, giving no access to the internal details of that task. 

  • Data Encapsulation:

Data Encapsulation is one of the most important notions of OOPS. It is the way of binding both data and the functions that get executed on the given data under one hood. These functions are member functions in C++. You do not have the permission to access the data directly. You must create a member function, to manipulate or use that given data.

  • Modularity:

Modularity is the technique of dividing the program into subprograms or functions. It reduces the complex nature of the article and generates various well-structured documentation, increasing the quality of the program. A module is a separate unit in itself. Hence you can execute a separate module as it is connected to other modules in some manner. All the modules act as a single unit to achieve the aim of the program. In OOPs, classes and objects form the basic foundation of a system. 

  • Inheritance:

Inheritance is one of the most vital concepts of OOPs, which is essential to know to really understand the whole concept of Object-Oriented Programming. Inheritance in C++ has made it possible to use reusability as a tool to write clean and efficient programs.

  • Polymorphism:

Polymorphism is the notion that can hold up the ability of an object of a class to show a different reaction in response to an action. For a language to considered to be as an OOP language, it must support polymorphism.

In this article, you will look into the simple and subtle aspects of the inheritance concept and the way inheritance in C++ is implemented. It also allows the addition of extra features to an existing class without the need to modify it in any way. Inheritance is transitive, which benefits from the implementation of inheriting the properties of one class by another class.

What is Inheritance?

Inheritance in C++ is a vital concept and can not be overlooked. Understanding inheritance is critical for understanding the whole point behind object-oriented programming. For instance, you are a human. You inherit from the class ‘Humans’ characteristic features, such as walking, sitting, running, eating, and so on. The class ‘Humans’ inherits these characteristic features from the class ‘Mammal’ which makes the ‘Human' class a derived class of ‘Mammal’. This ‘Mammal’ class inherits its characteristic features from another class ‘Animal’ which makes the ’Mammal’ class a derived class of the class ‘Animal’ and makes the ‘Animal’ a base class.

One of the most astonishing features of inheritance is code reusability. This reusability also provides you with clean code, and the replication of code gets reduced to almost zero.

Reusing existing codes serves various advantages. It saves time, money, effort, and increases a program’s reliability. 

Inheritance in C++ is of 5 types. They are as follows:

  • Multiple Inheritance
  • Hierarchical Inheritance
  • Multilevel Inheritance
  • Hybrid Inheritance

This article will discuss the various types of inheritance with detailed examples later on. First, understand the use-cases of inheritance in object-oriented programming.

Uses of Inheritance

Inheritance is a useful concept of object-oriented programming. Inheritance in C++ serves many advantages. There are several reasons why inheritance was introduced in OOPs. You will see some of the major reasons behind the introduction of inheritance in C++, below:

  • Inheritance increases the relatability of the code to real-world scenarios drastically. 
  • Another reason is the idea of reusability. Code reusability ensures that a clean code is provided to the programmer. This also helps in the reduction of rewriting and serves as a bug-free code, as the replication of the code gets reduced to almost zero with the help of reusability. Other advantages of reusability are time management, maintenance, and ease of extension. You can do manipulations and add some desired features to a class that already exists through inheritance. 
  • One more reason is the transitive nature of inheritance. Transitive nature implies that if two objects that are in succession show a pattern, then all the objects of that order must show the exact pattern.  For example, if a new class TataSafari is declared as a subclass of Car, which itself is a subclass of Vehicle, then TataSafari must also be a Vehicle i.e., inheritance is transitive in nature.

Base Class and Derived Classes

  • Base Class:

A base class is also known as a parent class since all the classes that are termed as derived classes or subclasses, inherit their silent features from the base class. In a program, there could be one or more than one base class, depending on the type of inheritance of the class. For example, if the inheritance type is single inheritance, the class may contain only one base class whereas if the inheritance type is multilevel inheritance, the class may contain over one base class.

  • Derived Class:

A derived class is also known as a subclass. It is a child class that inherits its salient features or characteristics from its parent class. There can be one or over one derived class that inherits from the same base class, depending upon what type of inheritance you are talking about. There are three visibility modes in inheritance in C++, private, protected, and the public that determine the derivation of the features of the base class.

The Syntax for Inheritance in C++

The syntax for achieving inheritance in C++ is - 

class base-class-name 

{

  // members...

  // member function 

}

class derived-class-name : visibility-mode base-class-name 

{

  // members....

  // member function 

}

You can define the base class and derived classes using the syntax mentioned above. 

The key components of the syntax are - 

  • The keyword class: Just like defining any usual class in C++, which requires a keyword class, defining a subclass also follows a similar syntax.
  • Name of the subclass: You have to specify the name of the sub-class or the derived class that inherits the properties of some other class.
  • Visibility mode: After specifying the name of the base class, the visibility mode should be provided to specify in which mode the base class is deriving the properties and members from the base class.
  • Name of the base class: Finally, you need to provide the name of the class, from which the new subclass is deriving the data members and member functions.

Example for demonstrating the concept of the base class and the derived class that will help you to understand inheritance in C++:

#include <iostream>

using namespace std;

// A Base class 

class BaseClass {

public:

   int x;

};

// derived class inheriting 

// the class BaseClass publicly

class DerivedClass : public BaseClass {

public:

   int y;

};

// Driver Code

int main()

{

   // instantiating the derived class

   // sub is an instance of the derived class

   DerivedClass sub;

   // accessing the data member of

   // the derived class and assigning it a value 

   sub.y = 10;

   // derived have the access to the 

   // data member of its base class

   sub.x = 20;

   cout << "The derived class data member has value: "

      << sub.y << "\n";

   cout << "The base class data member has value: "

      << sub.x << "\n\n";

   return 0;

Inheritance_In_C_Plus_Plus_1

Modes of Inheritance

The visibility mode (private, public or protected) in the definition of the derived class specifies whether the features of the base class are privately derived, publicly derived or protected derived. The visibility modes control the access-specifier to be for inheritable members of base-class, in the derived class.

  • Public Visibility Mode:

Public Visibility mode gives the least privacy to the attributes of the base class. If the visibility mode is public, it means that the derived class can access the public and protected members of the base class, but not the private members of the base class. Below is the public derivation in classes:

class Super                     //The Base class, Super

{

   private:

      int x;

      void check(void);

   public:

      int y;

      void display(void);

   protected:

      int z;

      void getval(void);

};

class Sub: public Super         //The publicly derived class, Sub

{

   private:

      int a;

      void init(void);

   public:

      int b;

      void readit(void);

   protected:

      int c;

      void writeit(void);

};

  • Private Visibility Mode:

Public Visibility mode gives the most privacy to the attributes of the base class. If the visibility mode is private, that means THAT the derived class can privately access the public and protected members of the base class. Below is the private derivation in classes:

class Super                    //The Base class, Super

{

   private:

      int x;

      void check(void);

   public:

      int y;

      void display(void);

   protected:

      int z;

      void getval(void);

};

class Sub: private Super        //The privately derived class, Sub

{

   private:

      int a;

      void init(void);

   public:

      int b;

      void readit(void);

   protected:

      int c;

      void writeit(void);

};

  • Protected  Visibility Mode:

Protected visibility mode is somewhat between the public and private modes. If the visibility mode is protected, that means the derived class can access the public and protected members of the base class protectively. Below is the protected derivation in classes:

class Super                       //The Base class, Super

{

   private:

      int x;

      void check(void);

   public:

      int y;

      void display(void);

   protected:

      int z;

      void getval(void);

};

class Sub: protected Super         //The protected derived class, Sub

{

   private:

      int a;

      void init(void);

   public:

      int b;

      void readit(void);

   protected:

      int c;

      void writeit(void);

};

Access specifier for the base class

Visibility Modes

Public

Protected

Private

Public

Public

Protected

Private

Protected

Protected

Protected

Private

Private

Not Accessible

Not Accessible

Not Accessible

Types of Inheritance in C++

Inheritance in C++ is primarily of five types:

  • Single Inheritance:

Single inheritance is the most basic type of inheritance. In single inheritance, there is only one base class and one sub or derived class. The subclass is directly inherited from the base class.

The following example illustrates the single level inheritance in C++ :

#include <iostream>

using namespace std;

// declaring a base class named Fruit

class Fruit {

public:

   // default constructor of class

   Fruit()

   {

   cout << "This is an example of single level inheritance.";

   }

};

// declaring a base class named Mango

// derived from a single class Fruit

// in the public visibility mode.

class Mango: public Fruit{

}; 

int main()

{

   // creating an instance of the derived class

   // this will also invoke the base class constructor.

   Mango M; 

   cout << "\n\n";

   return 0;

}

Inheritance_In_C_Plus_Plus_2

  • Multiple Inheritance:

Multiple inheritance is another type of inheritance in C++. In this kind of inheritance, there is one sub or derived class but there is more than one base class. The s class is derived from more than one base class and inherits its characteristics.

The following example illustrates the multiple inheritance in C++ :

#include <iostream>

using namespace std;

// declaring a base class named Fruit

class Fruit {

public:

   // default constructor of class

    Fruit()

    {

    cout << "This is an example of multiple inheritance.\n";

    cout << "This is first base class.\n\n";

    }

};

// declaring another base class named tropicalFruit

class tropicalFruit {

public:

    tropicalFruit()

    {

    cout << "This is an example of multiple inheritance.\n";

    cout << "This is second base class.\n\n";

    }

};

// declaring a base class named Banana

// derived from two base classes Fruit and 

// tropicalFruit both in the public visibility mode.

class Banana: public Fruit, public tropicalFruit {

};

int main()

{

    // creating an instance of the derived class

    // this will also invoke all of the base class constructors.

    Banana B;

    return 0;

}

Inheritance_In_C_Plus_Plus_3

  • Hierarchical Inheritance:

As the name suggests, the hierarchical inheritance shows a tree-like structure. Many derived classes are directly inherited from a base class. 

The following example illustrates the hierarchical inheritance in C++ :

#include <iostream>

using namespace std;

// declaring a base class named Fruit

class Fruit

{

public:

    Fruit()

    {

    cout << "This is an example of hierarchical inheritance.\n";

    }

};

// declaring first base class named Mango

// derived from a class Fruit

// in the public visibility mode.

class Mango: public Fruit

{

};

// declaring second base class named Banana

// derived from a class Fruit

// in the public visibility mode.

class Banana: public Fruit

};

int main()

{

    // creating instances of the derived class will

    // this will also invoke the base class constructor.

    Mango M;

    Banana B;

    cout << "\n\n";

    return 0;

}

Inheritance_In_C_Plus_Plus_4

  • Multilevel Inheritance:

Multilevel Inheritance is the fourth type of inheritance that is found in C++. Multilevel inheritance can also be explained by a family tree. There is one base class. This base class inherits multiple subclasses. These subclasses (not every subclass necessarily) acts as base class and further inherits subclasses. This is just like a family having descendants over generations. 

The following example illustrates the multi-level inheritance in C++ :

#include <iostream>

using namespace std;

// declaring a base class named Fruit

class Fruit

{

public:

    Fruit()

    {

    cout << "This is an example of multi-level inheritance.\n" << endl;

    }

}; 

// declaring a base class named tropicalFruit

// derived from class Fruit

// in the public visibility mode.

class tropicalFruit: public Fruit

{ public:

    tropicalFruit()

    {

    cout<<"I am the constructor of tropicalFruit class.\n"<<endl;

    }

}; 

// declaring a base class named Banana

// derived from class tropicalFruit

// in the public visibility mode.

class Banana: public tropicalFruit{

public:

    Banana()

    {

    cout<<"I am constructor of Banana class.\n"<<endl;

    }

}; 

int main()

{

    // creating an instance of the derived class

   // this will also invoke the base class constructor.

    Banana B;    

    cout << "\n";

    return 0;

}

Inheritance_In_C_Plus_Plus_5

  • Hybrid Inheritance:

This inheritance has different concepts from the other mentioned inheritances, and hence is a bit more complex. As the name suggests, this type of inheritance includes more than one inheritance. It is a combinational inheritance where a derived class is inherited from two or more base classes and all of these classes are inherited from a single base class.

The following example illustrates the hybrid inheritance in C++ :

#include <iostream>

using namespace std;

// declaring a base class named Fruit

class Fruit

{

public:

    Fruit()

    {

    cout << "This is an example of single-level inheritance.\n";

    }

}; 

// declaring another base class named Cost

class Cost

{

    public:

    Cost()

    {

        cout << "I am the constructor of the base class Cost.\n";

    }

}; 

// declaring first base class named Mango

// derived from the class Fruit

// in the public visibility mode.

class Mango: public Fruit

}; 

// declaring second base class named Banana

// derived from two classes Fruit and Cost

// in the public visibility mode.

class Banana: public Fruit, public Cost

{   

}; 

int main()

{

    // creating an instance of the base class

    // this will also invoke the base class constructor.

    Banana B;

    cout << "\n";

    return 0;

}

Inheritance_In_C_Plus_Plus_6 

Full Stack Java Developer Course

The Gateway to Master Web DevelopmentExplore Course
Full Stack Java Developer Course

The Diamond Problem issue in the case of Multiple Inheritances

The diamond problem arises when there is a case in which there is a class structure like the one given below:

Inheritance_In_C_Plus_Plus_7

You can see here that two classes (Sub Class 1 & Sub Class 2) are derived from the same base class (Base Class). So when you create the objects of these two subclasses, multiple copies of the base class are created. This situation here is called the dreaded diamond problem. 

This problem can be avoided by the use of the keyword ‘virtual’ while declaring the subclasses, so that it removes ambiguities and the Sub Class 3 has only one copy of the members of the Base Class.  

The following program illustrateS how to overcome this ambiguous situation in multiple inheritances in C++ using the keyword virtual:

#include <iostream>

using namespace std;

class BaseClass 

{

    public:

    int a;

};

// inherit using the virtual keyword

class subClass1 : virtual public BaseClass

{

    public:

    int b;

};

// inherit using the virtual keyword

class subClass2 : virtual public BaseClass

{

    public:

    int c;

};

class subClass3 : public subClass1, public subClass2

{

    public:

    int total;

};

int main ()

{

    subClass3 s3;

    s3.a = 10;  // became unambiguous

    s3.b = 20;

    s3.c = 30;

    s3.total = s3.a + s3.b + s3.c;

    cout << s3.a << " " << s3.b << " " << s3.c << " " << s3.total;

    cout << "\n\n";

}

Inheritance_In_C_Plus_Plus_8

Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.

Conclusion

In this article, you have learned about one of the most important pillars of the object-oriented programming concept called inheritance. You dived deep into the uses, types, modes, and the concepts of inheritance.

To better understand the entire C++ programming language, you can go through our guide on C++ Programming for Beginners. To better understand Object Oriented Programming concepts, you can learn Java programming language by enrolling in Simplilearn’s Java Certification Training Course

Have any questions for us? Leave them in the comments section of this article. Our experts will bhget back to you on the same, ASAP!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.