TL;DR: C++ has five types of inheritance: single, multiple, multilevel, hierarchical, and hybrid. Multiple and hybrid inheritance can trigger the diamond problem, which you can fix with scope resolution or virtual inheritance. This guide covers all five types with verified code and a comparison table. Use it to pick the right inheritance pattern for your design.

Inheritance is one of the four pillars of Object-Oriented Programming (OOP). It lets a class, the derived or child class, acquire the properties and behavior of another class, the base or parent class, so you don't have to rewrite code that already exists. It works much like inheritance in real life: a child inherits traits from their parents, who in turn inherited them from a broader ancestry, each generation building on the one before it.

In C++, a base class's data members are copied into the derived class, with accessibility controlled by the visibility mode used, always moving from more open to more restricted, i.e., public to protected. There are five types of inheritance in C++, covered in detail in this article:

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

What is Inheritance in C++?

Inheritance is a method through which one class inherits the properties of its parent class. Inheritance is a feature in which one new class is derived from an existing one. The new class derived is termed a derived class, and the existing class is termed a parent or base class. Inheritance is one of the most essential features of Object Oriented Programming. Rather than defining new data and functions while creating a class, you can inherit the existing class's data and functions. The derived class takes over all the properties of the parent class and adds some new features to itself. For example, using inheritance, you can add new members and descriptions to a new class without rewriting what the parent class already provides.

AI-Powered Full Stack Developer ProgramExplore Program
Want a Top Software Development Job? Start Here!

What Are Child and Parent Classes?

To clearly understand the concept of inheritance, you must learn about two terms on which the whole concept is based: child class and parent class.

  • Child class: The class that inherits the characteristics of another class is known as the child class or derived class. The number of child classes that can be inherited from a single parent class depends on the type of inheritance used. A child class accesses the data members of the parent class according to the visibility mode specified during the declaration of the child class.
  • Parent class: The class from which the child class inherits its properties is called the parent class or base class. A single parent class can derive multiple child classes (Hierarchical Inheritance), or multiple parent classes can be inherited by a single derived class (Multiple Inheritance). This depends on the different types of inheritance in C++.

The syntax for defining the child class and parent class across all inheritance types in C++ is given below:

class parent_class
{
    //class definition of the parent class
};

class child_class : visibility_mode parent_class
{
   //class definition of the child class
};

Syntax Description

  • parent_class: name of the base class or the parent class.
  • child_class: name of the derived class or the child class.
  • visibility_mode: type of visibility mode (private, protected, or public) that specifies how the data members of the child class inherit from the parent class.
AI-Powered Full Stack Developer ProgramExplore Program
Get the Coding Skills You Need to Succeed

Importance of Inheritance in C++

Instead of trying to replicate what already exists, it is always ideal to reuse it, since it saves time and enhances reliability. In C++, inheritance is used to reuse code from existing classes. C++ heavily supports the principle of reusability. Inheritance is used when two classes in a program share the same domain, and the properties of the class and its superclass should remain the same.

Implementing Inheritance in C++

To create a class that derives from a base class, use the syntax below:

class <derived_class_name> : <access-specifier> <base_class_name>
{
    // body
}

Here, class is a keyword used to create a new class, derived_class_name is the new class's name, which will inherit the properties of a base class, access-specifier defines the mode in which the derived class has been created, whether public, private, or protected, and base_class_name is the name of the base class.

Public Inheritance: The public members of the base class remain public in the derived class; the same applies to protected members.

Private Inheritance: This makes the public and protected members of the base class become private in the derived class. The derived class has no access to the base class's private members.

Protected Inheritance: Keeps the public and protected members of the base class as protected members of the derived class.

Why and When to Use Inheritance?

Inheritance makes programming more efficient because of the benefits it provides. The most important reasons to use it are discussed below:

  1. Code reusability: One of the main reasons to use inheritance is that you can reuse code. Consider a group of animals as separate classes, Tiger, Lion, and Panther. For these classes, you can create member functions like predator(), since they're all predators, canine(), since they all have canine teeth for hunting, and claws(), since all three animals have sharp claws. Writing these functions separately for each class causes data redundancy and increases the chances of error. Instead, you can create a base class named Carnivores, add these functions to it, and let Tiger, Lion, and Panther inherit them.
  2. Transitive nature: Inheritance is also useful because of its transitive nature. Say you have a derived class Mammal that inherits its properties from the base class Animal. Because of the transitive nature of inheritance, every child class of Mammal will also inherit the properties of the Animal class. This helps a great deal with debugging: fix a bug in your base class, and every inherited class benefits automatically.
Java Certification TrainingENROLL NOW
Dive Deep Into Java Core Concepts

Visibility Modes

The visibility mode specifies how the features of the base class are inherited by the derived class. There are three visibility modes across all inheritance types in C++:

Public Visibility Mode

In public visibility mode, the accessibility of all base class members is retained. Members specified as public, protected, and private in the base class remain public, protected, and private, respectively, in the derived class. Public members are accessible by the derived class and all other classes. Protected members are accessible only inside the derived class and its members. Private members are not accessible to the derived class at all.

class base_class_1
{
    // class definition
};
class derived_class: public base_class_1
{
    // class definition
};

The following code displays the working of public visibility mode with all three access specifiers of the base class:

class base_class
{
private:
    int base_private;
protected:
    int base_protected;
public:
    int base_public;
};

class derived_class : public base_class
{
private:
    int derived_private;
protected:
    int derived_protected;
public:
    int derived_public;
};

int main()
{
    derived_class obj;
    obj.base_private;   // Not accessible
    obj.base_protected; // Not accessible
    obj.base_public;    // Accessible
}

In the above example, the derived class inherits the base class as public. The private members aren't accessible at all by the derived class. The protected members are only accessible inside the derived class, not outside it. The public members are accessible both inside and outside the class.

Private Visibility Mode

In private visibility mode, all members of the base class become private in the derived class. This restricts access to those members outside the derived class; they can only be accessed by the member functions of the derived class, which does not inherit the base class's private members at all.

class base_class_1
{
    // class definition
};
class derived_class: private base_class_1
{
    // class definition
};

The following code displays the working of private visibility mode with all three access specifiers of the base class:

class base_class
{
private:
    int base_private;
protected:
    int base_protected;
public:
    int base_public;
};

class derived_class : private base_class
{
private:
    int derived_private;
protected:
    int derived_protected;
public:
    int derived_public;
};

int main()
{
    derived_class obj;
    obj.base_private;   // Not accessible
    obj.base_protected; // Not accessible
    obj.base_public;    // Not Accessible
}

In the above example, the derived class inherits the base class privately, so all the members of the base class have become private in the derived class. An error is thrown when the object of the derived class tries to access these members outside the class.

Protected Visibility Mode

In protected visibility mode, all members of the base class become protected members of the derived class. These members are only accessible by the derived class and its member functions, and can also be inherited by, and accessible to, further subclasses. Objects of the derived class still cannot access these members from outside the class.

class base_class_1
{
    // class definition
};

class derived_class: protected base_class_1
{
    // class definition
};

The following code displays the working of protected visibility mode with all three access specifiers of the base class:

class base_class
{
private:
    int base_private;
protected:
    int base_protected;
public:
    int base_public;
};

class derived_class : protected base_class
{
private:
    int derived_private;
protected:
    int derived_protected;
public:
    int derived_public;
};

int main()
{
    derived_class obj;
    obj.base_private;   // Not accessible
    obj.base_protected; // Not accessible
    obj.base_public;    // Not Accessible
}

In the above example, the derived class inherits the base class in protected mode. All members of the base class are now only accessible inside the derived class, not anywhere outside it. It throws an error when the object obj of the derived class tries to access these members outside the class.

The following table illustrates the control derived classes have over the members of the base class under different visibility modes:

BASE CLASS

DERIVED CLASS PUBLIC

DERIVED CLASS PROTECTED

DERIVED CLASS PRIVATE

PUBLIC

Public

Protected

Private

PROTECTED

Protected

Protected

Private

PRIVATE

Not Inherited / Remains Private

Not Inherited / Remains Private

Not Inherited / Remains Private

Types of Inheritance in C++

There are five types of inheritance in C++, based on how the derived class inherits its features from the base class. Before going through each one in detail, here's how they compare at a glance:

Type

Structure

Real-World Analogy

Best Used When

Single

One base, one derived (A → B)

A Car is a kind of Vehicle

One class clearly extends another with no extra branching

Multilevel

A chain of derived classes (A → B → C)

A SportsCar is a Car, and a Car is a Vehicle

Behavior needs to build up gradually across stages

Multiple

One derived class, two or more bases (A, B → C)

A Smartwatch is both a Watch and a Computer

A class needs to combine features from two unrelated classes

Hierarchical

One base, several derived classes (A → B, A → C)

Car and Bus are both Vehicles

Several classes share common base behavior but differ afterward

Hybrid

A mix of the patterns above

A hybrid car blends the electrical system of an Electric Vehicle with the structure of a regular Car

Real systems that need more than one inheritance pattern at once

The pair that trips up the most learners is multiple versus multilevel inheritance, and the difference comes down to one question: how many direct parents does the derived class have? In multiple inheritance, one class inherits directly from two or more base classes at the same level, like Linux_based inheriting from both electronicDevice and Computer in the example below. In multilevel inheritance, every class inherits from exactly one parent, but that parent is itself already a derived class, forming a chain rather than a merge.

  • Single Inheritance

Single Inheritance is the most primitive of the types of inheritance in C++. In this inheritance, a single class inherits the properties of a base class. All the data members of the base class are accessed by the derived class according to the visibility mode (private, protected, or public) specified during the inheritance.

Syntax

class base_class_1{
    // class definition
};

class derived_class: visibility_mode base_class_1{
    // class definition
};

Description

A single derived_class inherits a single base_class. The visibility_mode is specified while declaring the derived class, and it controls how base class members are accessed within the derived class.

Example

The following example illustrates Single Inheritance in C++:

#include <iostream>
using namespace std;

// base class
class electronicDevice{
public:
    // constructor of the base class
    electronicDevice()
    {
        cout << "I am an electronic device.\n\n";
    }
};

// derived class
class Computer: public electronicDevice{
public:
    // constructor of the derived class
    Computer()
    {
        cout << "I am a computer.\n\n";
    }
};

int main(){
    // create object of the derived class
    Computer obj; // constructor of base class and
                  // derived class will be called
    return 0;
}

Output:

I am an electronic device.

I am a computer.

In the above example, the subclass Computer inherits the base class electronicDevice in public mode, so all the public and protected member functions and data members of the class electronicDevice are directly accessible to the class Computer. Since there is a single derived class inheriting a single base class, this is Single Inheritance.

  • Multiple Inheritance

The inheritance in which a class can inherit or derive the characteristics of multiple classes, or a derived class has more than one base class, is known as Multiple Inheritance. It specifies access specifiers separately for each base class at the time of inheritance. The derived class can derive the joint features of all these classes, and the data members of all the base classes are accessed by the derived class according to the access specifiers.

Yes, C++ supports multiple inheritance directly. Unlike Java or C#, where a class can implement multiple interfaces but extend only one class, C++ lets a class inherit straight from more than one base class. That flexibility is powerful, but it's also exactly what causes the diamond problem, covered later in this article.

Syntax

class base_class_1{
    // class definition
};

class base_class_2{
    // class definition
};

class derived_class: visibility_mode_1 base_class_1, visibility_mode_2 base_class_2{
    // class definition
};

Description

The derived_class inherits the characteristics of two base classes, base_class_1 and base_class_2. The visibility_mode is specified for each base class while declaring a derived class, and these modes can differ for every base class.

Example

The following example illustrates Multiple Inheritance in C++:

#include <iostream>
using namespace std;

// class_A
class electronicDevice{
public:
    // constructor of the base class 1
    electronicDevice()
    {
        cout << "I am an electronic device.\n\n";
    }
};

// class_B
class Computer{
public:
    // constructor of the base class 2
    Computer()
    {
        cout << "I am a computer.\n\n";
    }
};

// class_C inheriting class_A and class_B
class Linux_based : public electronicDevice, public Computer{};

int main(){
    // create object of the derived class
    Linux_based obj; // constructor of base class A,
                     // base class B and derived class
                     // will be called
    return 0;
}

Output:

I am an electronic device.

I am a computer.

In the above example, there are separate base classes, electronicDevice and Computer. The derived class Linux_based inherits both classes, forming a Multiple Inheritance structure, in public mode. When you create an object of the derived class, it calls the constructor of both base classes.

Java Certification TrainingENROLL NOW
Master Core Java 8 Concepts, Java Servlet, & More!

  • Multilevel Inheritance

The inheritance in which a class is derived from another derived class is known as Multilevel Inheritance. Suppose there are three classes, A, B, and C. A is the base class from which B derives. So B is the derived class of A. Now C is derived from B, which makes B the base class for C, while B itself is still the derived class of A. This is Multilevel Inheritance. The data members of each base class are accessed by their respective derived classes according to the specified visibility modes.

Syntax

class class_A{
    // class definition
};

class class_B: visibility_mode class_A{
    // class definition
};

class class_C: visibility_mode class_B{
    // class definition
};

Description

class_A is inherited by the subclass class_B, and class_B is inherited by the subclass class_C. A subclass inherits a single class at each succeeding level.

Example

The following example illustrates Multilevel Inheritance in C++:

#include <iostream>
using namespace std;

// class_A
class electronicDevice{
public:
    // constructor of the base class 1
    electronicDevice()
    {
        cout << "I am an electronic device.\n\n";
    }
};

// class_B inheriting class_A
class Computer: public electronicDevice{
public:
    // constructor of the base class 2
    Computer()
    {
        cout << "I am a computer.\n\n";
    }
};

// class_C inheriting class_B
class Linux_based : public Computer{
public:
    // constructor of the derived class
    Linux_based()
    {
        cout << "I run on Linux.\n\n";
    }
};

int main(){
    // create object of the derived class
    Linux_based obj; // constructor of base class 1,
                     // base class 2, derived class will be called
    return 0;
}

Output:

I am an electronic device.

I am a computer.

I run on Linux.

In the above example, the base class electronicDevice is inherited by the subclass Computer, which is further inherited by the subclass Linux_based. Since one class is inherited by a single class at each level, this is Multilevel Inheritance. The object of the derived class Linux_based can access the members of both electronicDevice and Computer directly.

  • Hierarchical Inheritance

The inheritance in which a single base class is inherited by multiple derived classes is known as Hierarchical Inheritance. This inheritance has a tree-like structure, since every class acts as a base class for one or more child classes. The visibility mode for each derived class is specified separately during inheritance, and each accesses the data members accordingly.

Syntax

class class_A{
    // class definition
};

class class_B: visibility_mode class_A{
    // class definition
};

class class_C : visibility_mode class_A{
    // class definition
};

class class_D: visibility_mode class_B{
    // class definition
};

class class_E: visibility_mode class_C{
    // class definition
};

Description

The subclasses class_B and class_C both inherit the attributes of the base class class_A. Further, these two subclasses are inherited by other subclasses, class_D and class_E, respectively.

Example

The following example illustrates Hierarchical Inheritance in C++:

#include <iostream>
using namespace std;

// base class
class electronicDevice{
public:
    // constructor of the base class 1
    electronicDevice()
    {
        cout << "I am an electronic device.\n\n";
    }
};

// derived class inheriting base class
class Computer: public electronicDevice{};

// derived class inheriting base class
class Linux_based : public electronicDevice{};

int main(){
    // create object of the derived classes
    Computer obj1;     // constructor of base class will be called
    Linux_based obj2;  // constructor of base class will be called
    return 0;
}

Output:

I am an electronic device.

I am an electronic device.

In the above example, the base class electronicDevice is inherited by two subclasses, Computer and Linux_based. This class structure represents Hierarchical Inheritance. Both derived classes can access the public members of the base class electronicDevice, and creating objects of these two derived classes calls the constructor of the base class for both.

  • Hybrid Inheritance

Hybrid Inheritance, as the name suggests, is a combination of two or more types of inheritance. For example, the classes in a program might be arranged so that they show both single inheritance and hierarchical inheritance at the same time. Such an arrangement is Hybrid Inheritance, arguably the most complex of the types of inheritance in C++. The data members of the base class are accessed according to the specified visibility mode.

Syntax

class class_A{
    // class definition
};

class class_B{
    // class definition
};

class class_C: visibility_mode class_A, visibility_mode class_B{
    // class definition
};

class class_D: visibility_mode class_C{
    // class definition
};

class class_E: visibility_mode class_C{
    // class definition
};

Description

The derived class class_C inherits two base classes, class_A and class_B; this is the structure of Multiple Inheritance. Two subclasses, class_D and class_E, further inherit class_C; this is the structure of Hierarchical Inheritance. Together, the overall structure of Hybrid Inheritance combines more than one inheritance type.

Example

The following example illustrates Hybrid Inheritance in C++:

#include <iostream>
using namespace std;

// base class 1
class electronicDevice{
public:
    // constructor of the base class 1
    electronicDevice()
    {
        cout << "I am an electronic device.\n\n";
    }
};

// base class 2
class Computer{
public:
    // constructor of the base class 2
    Computer()
    {
        cout << "I am a computer.\n\n";
    }
};

// derived class 1 inheriting base class 1 and base class 2
class Linux_based : public electronicDevice, public Computer{};

// derived class 2 inheriting derived class 1
class Debian: public Linux_based{};

int main(){
    // create an object of the derived class
    Debian obj; // constructor of base classes and
                // derived class will be called
    return 0;
}

Output:

I am an electronic device.

I am a computer.

In the above example, the three classes electronicDevice, Computer, and Linux_based form the structure of Multiple Inheritance, and the class Debian inherits Linux_based, forming the structure of Single Inheritance. When an object of the derived class Debian is created, the constructors of all its superclasses are called.

Learn 45+ in-demand full-stack development skills and tools, including Frontend Development, Backend Development, Version Control and Collaboration, Database Management, and AI-Assisted Development, with our AI-Powered Full Stack Developer Course.

Diamond Problem

The diamond problem in inheritance happens when a derived class inherits the attributes of two superclasses, and those superclasses share a common base class.

In a diamond problem, when two classes, class_1 and class_2, inherit the same base class, it creates two copies of Base_class. So when an object of derived_class tries to access a member of the base class, it causes ambiguity, since the compiler can't tell which copy of the base_class member it should use. In this situation, the compiler throws an error.

The following example illustrates the ambiguous situation caused by a diamond-structured inheritance:

#include <iostream>
using namespace std;

// base class
class Base_class{
public:
    int x;
};

// class 1
class class_1 : public Base_class{
public:
    int y;
};

// class 2
class class_2 : public Base_class{
public:
    int z;
};

// derived class 3
class derived_class : public class_1, public class_2{
public:
    int sum;
};

int main(){
    // create an object of the derived_class
    derived_class obj;
    obj.x = 10;  // ambiguous
    obj.y = 20;
    obj.z = 30;
    obj.sum = obj.x + obj.y + obj.z;

    cout << "The sum is: " << obj.sum << "\n\n";
    return 0;
}

This code throws a compiler error because of the ambiguity it creates: there are two copies of the data member x, one belonging to class_1 and one to class_2. When the object obj of derived_class tries to access this member, the compiler can't determine which copy of x to use.

There are two ways to resolve the ambiguous situation in a diamond problem:

  1. Using the scope resolution operator.
  2. Using the virtual base class keyword.

Fix 1: The Scope Resolution Operator

The following example illustrates using the scope resolution operator to remove ambiguity in the diamond problem:

#include <iostream>
using namespace std;

// base class
class Base_class{
public:
    int x;
};

// class 1
class class_1 : public Base_class{
public:
    int y;
};

// class 2
class class_2 : public Base_class{
public:
    int z;
};

// derived class 3
class derived_class : public class_1, public class_2{
public:
    int sum;
};

int main(){
    // create an object of the derived_class
    derived_class obj;
    obj.class_1::x = 10;  // it is now unambiguous
    obj.y = 20;
    obj.z = 30;
    obj.sum = obj.class_1::x + obj.y + obj.z;

    cout << "The sum is: " << obj.sum << "\n\n";
    return 0;
}

Output:

The sum is: 60

The expression obj.class_1::x uses the scope resolution operator to specify which copy of x should be used, in this case, class_1's version. No error is thrown, since the ambiguous statement has been resolved.

The scope resolution operator removes the ambiguity and produces the correct output, but there are still two separate copies of the base class sitting inside derived_class. If you only need one copy of the base class, that's what virtual inheritance is for.

Fix 2: Virtual Inheritance

Virtual inheritance is a C++ feature that ensures only one shared copy of a common base class exists in a derived class's hierarchy, no matter how many paths lead to it. You enable it by adding the virtual keyword when a class inherits from the shared base class.

Without virtual, each path to the base class (through class_1 and through class_2) creates its own separate copy, which is exactly what causes the ambiguity in the diamond problem above. With virtual, both paths point to the same single copy, so there's nothing left to be ambiguous about, and the object of the derived class can access the members of the base class in the usual way, with no scope resolution needed.

The following example illustrates using the virtual keyword to remove ambiguity in the diamond problem:

#include <iostream>
using namespace std;

// base class
class Base_class{
public:
    int x;
};

// class 1
class class_1 : virtual public Base_class{
public:
    int y;
};

// class 2
class class_2 : virtual public Base_class{
public:
    int z;
};

// derived class 3
class derived_class : public class_1, public class_2{
public:
    int sum;
};

int main(){
    // create an object of the derived_class
    derived_class obj;
    obj.x = 10;  // it is now unambiguous
    obj.y = 20;
    obj.z = 30;
    obj.sum = obj.x + obj.y + obj.z;

    cout << "The sum is: " << obj.sum << "\n\n";
    return 0;
}

Output:

The sum is: 60

In this example, class_1 and class_2 both inherit Base_class as virtual. Any multiple inheritance involving these subclasses now creates only a single copy of Base_class, so derived_class has just one copy of it, which makes obj.x = 10; valid and unambiguous, without needing the scope resolution operator at all.

Want to strengthen your Java development skills? Simplilearn’s Java Course covers Java, Java EE, and service-oriented architecture to help you build practical expertise for enterprise software development.

How to Make a Private Member Inheritable?

In inheritance, the private members of a base class are not inherited by the derived classes, so they're not accessible to objects of the derived class. Only public and protected members are inherited and can be accessed by derived classes.

The private members of a base class can be made inheritable in two ways:

  • Modifying the Visibility Mode From Private to Public

Making the access modifier of the private member public makes it inheritable by derived classes. However, this comes at a cost: the data-hiding property is no longer there for that member, since it's now accessible to every other function in the program.

  • Modifying the Visibility Mode From Private to Protected

This approach retains the data-hiding property of the private member. Changing a private member's access specifier to protected makes it inheritable and accessible by the derived class. If those members need to be inheritable beyond the immediately derived class, they should be inherited as public; otherwise, they should be inherited as private, which ends the inheritance hierarchy beyond the immediately derived class.

AI-Powered Full Stack Developer ProgramEXPLORE COURSE
Become a Job-Ready Full-Stack Developer

Advantages of Inheritance in C++

  • Reusability of Code

In C++, inheritance enables you to build new classes based on existing ones, letting you reuse code instead of writing the same function from scratch. This can save significant time and effort when developing new applications.

  • Overriding

The ability to alter functions in a derived class lets you modify a program's behavior without changing the base class's source code, which is a clean way to adapt existing code to new needs.

  • Polymorphism

Through inheritance, you can build objects that take different forms depending on the parent class they inherit from; this is polymorphism, and it helps keep code flexible and responsive to changing requirements.

  • Organization

Inheritance helps organize your code logically and hierarchically. By defining classes that derive from other classes, you build a structure of related classes that makes it easier to understand how the codebase works.

Disadvantages of Inheritance in C++

  • Increased Coupling

Derived classes become tightly bound to their base class, so a change to the base class can unexpectedly break every class that inherits from it.

  • Ambiguity From the Diamond Problem

Multiple and hybrid inheritance can create ambiguous references to inherited members, as covered in the Diamond Problem section above. Resolving that ambiguity requires extra tools, like the scope resolution operator or virtual inheritance, which adds complexity to the code.

  • Reduced Encapsulation

Because derived classes get direct access to their base class's protected members, inheritance can weaken the encapsulation that's supposed to separate a class's internal details from the classes that use it.

  • Harder to Trace and Debug

In deep multilevel or hybrid hierarchies, it can become difficult to tell which class a particular member or behavior actually comes from, especially for someone new to the codebase.

  • Overhead From Unused Features

A derived class inherits everything from its base class, even members it never uses, which can bloat the class and waste memory in performance-sensitive applications.

Base Class and Derived Class in C++

  • Base Class: Also called the parent class, a base class is a pre-existing class from which other classes inherit their properties. All of a base class's members are present in the class that inherits it, which can also add new properties of its own.
  • Derived Class: Also called the child class, this class is derived from a pre-existing class. The derived class inherits functions from a base class and can add its own operations on top of what it inherits.

Access Control in C++

Access control is used to hide data in object-oriented programming. It allows you to distinguish between a class's public interface and the protected elements that are only accessible to derived classes. A derived class has access to its base class's non-private members, so any base-class features that shouldn't be available to derived class member functions should be made private in the base class.

  • Publicly Derived Class: When a class is derived from a public base class, the base class's members become public members of the derived class, and the base class's protected members become protected members of the derived class. The private members of the base class are never directly available from a derived class.
  • Privately Derived Class: When a class is derived through private inheritance, the base class's public and protected elements are converted into private members. This means the derived object's public interface does not inherit the base class's methods.
The step-by-step Software Engineer Roadmap is designed for professionals seeking to understand the full scope of the profession. Explore the skills, tools, salary potential, and career roadmap needed to build a successful career as a software engineer.

Modes of Inheritance

The features of a base class can be publicly, privately, or protectedly derived, depending on the visibility mode specified in the derived class's declaration.

  • Public Visibility Mode: The base class's attributes have the least privacy under public visibility mode. The derived class can access the base class's public and protected members, but not its private members.
  • Private Visibility Mode: This setting provides the most privacy for base class attributes. With private visibility mode, the derived class can only privately access the public and protected members of a base class.
  • Protected Visibility Mode: Between public and private visibility modes sits protected visibility mode. The derived class can access the base class's protected and public members protectively.

Final Thoughts!

You now have a working grip on all five types of inheritance in C++, single, multiple, multilevel, hierarchical, and hybrid, along with the visibility modes that control how each one behaves, the diamond problem and both ways to fix it, and where inheritance's benefits stop paying off against its disadvantages. For more C++ fundamentals, explore our guide on C++ for beginners.

Inheritance is one piece of a much bigger skill set. If you're ready to build on it, Simplilearn's AI-Powered Full Stack Developer Course covers front-end and back-end development, database management, API security, testing, and deployment, guided by industry experts throughout the course.

Key Takeaways

  • C++ has five types of inheritance, single, multiple, multilevel, hierarchical, and hybrid, distinguished by how many base and derived classes are involved and how they connect.
  • Multiple inheritance lets one class inherit from more than one base class directly; multilevel inheritance chains classes together, with each one having exactly one parent.
  • The diamond problem happens only when multiple inheritance paths share a common ancestor, and it's resolved with the scope resolution operator or, more cleanly, with virtual inheritance.
  • Visibility mode (public, private, protected) controls how much of the base class's members a derived class, and anything further down the chain, can actually access.
  • Inheritance boosts code reuse and organization, but it also increases coupling and can weaken encapsulation, so it's worth weighing against alternatives like composition.

FAQs

1. Does Java support multiple inheritance the way C++ does?

No. Java doesn't let a class extend more than one class, specifically to avoid the diamond problem. Instead, it allows a class to implement multiple interfaces, which provide method signatures without state, so there's no ambiguity about which parent's data a subclass inherits.

2. What is the order of constructor and destructor calls in multiple or hybrid inheritance?

Constructors run in the order the base classes are listed in the derived class's declaration, left to right, followed by the derived class's own constructor. Destructors always run in the exact reverse order, derived class first, then base classes right to left, so objects are torn down in the opposite order they were built.

3. Does multiple inheritance always cause the diamond problem?

No. The diamond problem only occurs when two or more of a class's base classes share a common ancestor. If a derived class inherits from two unrelated base classes with no shared parent, like the Multiple Inheritance example above, there's nothing to disambiguate.

4. What is the difference between inheritance and composition in C++?

Inheritance models an "is-a" relationship, a Car is a Vehicle, by letting a derived class reuse and extend a base class. Composition models a "has-a" relationship, a Car has an Engine, by including an object of one class as a member of another. Composition is often preferred where inheritance's downsides, like tight coupling, become a problem, since the two classes stay independent of each other.

5. Is inheritance in C++ resolved at compile time or runtime?

The inheritance relationship itself, which class inherits from which, is fixed at compile time. What can happen at runtime is polymorphism: if the base class declares a function as virtual, C++ decides which version to call, base or derived, based on the object's actual type at runtime rather than its declared type.

Our Software Development Program Duration and Fees

Software Development programs typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Full Stack Development Program with Generative AI20 weeks$4,000