Summarise With AI
ChatGPT
Perplexity
Claude
Gemini
Grok
ChatGPT
Perplexity
Claude
Gemini
Grok
Back

Inheritance in C++: Types & its Examples

17 Nov 2025
7 min read

Key Takeaways From the Blog

  • Inheritance allows a derived class to reuse attributes and methods of a base class.
  • Access specifiers (public, protected, private) control how members are inherited.
  • Types of inheritance: single, multiple, multilevel, hierarchical, hybrid.
  • Protected members enable controlled access across derived classes.
    Function overriding lets derived classes redefine base class methods.
  • Advantages: code reuse, maintainability, and modularity; disadvantages: complexity and tight coupling.

Inheritance is one of the core principles of object-oriented programming (OOP), and through inheritance, a class (derived class) inherits the attributes and behaviour (methods) of another class (base class). The inheritance in C++ enables code reuse and develops an association between classes such that classes can share common characteristics and functionalities.

This article discusses the definition, types, syntax, examples, advantages, disadvantages, and real-world implementation of inheritance in C++. Let us explore the key features of inheritance and its usage in C++.

What is Inheritance in C++

Inheritance is a system where the members and methods of a base class are inherited into a derived class. This supports code reuse and helps you maintain a more structured hierarchy in your code. The derived class may have other additional features of its own or override the ones inherited.

Syntax of Inheritance in C++

The inheritance syntax in c++ is defined below:

class DerivedClass : accessSpecifier BaseClass {
    // Derived class members
};
  • DerivedClass: The class which will have the characteristics.
  • BaseClass: The class in which the attributes are inherited.
  • accessSpecifier: Specifies how members of the base class are inherited. The most frequently applied access specifiers are public, protected, and private.

Key Takeaways so far:

  • Inheritance enables reusing code and maintaining a structured hierarchy.
  • Access specifiers define how base class members are exposed to derived classes.
  • Derived classes can override or extend base class functionality.

Implementing Inheritance in C++

Now we know about inheritance and private members, let's understand how to implement inheritance in C++ through examples.

Access Specifiers in C++

Access specifiers control the accessibility of class members to other classes. The three primary access specifiers are:

  • Public: Members are visible outside the class.
  • Protected: Members are visible within the class and derived classes.
  • Private: Members are only available within the class itself.

How to Make a Private Member Inheritable?

Private members of the base class are not directly accessible by default to the derived class. Private members may be made accessible through the following ways:

1. Use Protected Access Specifier

By declaring members safe in the base class, they can be inherited by the derived class.

Example

Here is an example of protected inheritance c++:

#include <iostream>

class Base {
protected:
    int x;
public:
    Base() : x(5) {}
};

class Derived : public Base {
public:
    void display() {
        std::cout << "Value of x: " << x << std::endl; // x is inherited and accessible
    }
};

int main() {
    Derived obj;
    obj.display();  // Calling the display function
    return 0;
}

Explanation

  • In this case, x is defined as protected inside the Base class. This indicates that x cannot be used directly outside the Base class but is accessible within the derived classes.
  • So, in the Derived class, the display() method can invoke x and print its value.

Output

Value of x: 5

2. Provide Public or Protected Accessor Methods

Alternatively, you can supply getter/setter methods through which private members are accessed in the derived class.

Example

Here is an example of public or protected inheritance c++:

#include <iostream>

class Base {
private:
    int x;
public:
    Base() : x(10) {}
    int getX() { return x; } // Accessor method
};

class Derived : public Base {
public:
    void display() {
        std::cout << "Value of x: " << getX() << std::endl; // Using accessor method
    }
};

int main() {
    Derived obj;
    obj.display();  // Calling the display function
    return 0;
}

Explanation

  • The private member variable x of the Base class cannot be accessed by any code other than the Base class, including the Derived class.
  • The getX() method gives a public interface for obtaining the value of x. This is encapsulation, where internal workings (i.e., the private variable x) are obscured, yet remain accessible or modifiable by a controlled interface (i.e., the getX() method).
  • Although x is protected in the Base class, the Derived class can access the value of x through the getX() method because the getX() method is public.

Output

Value of x: 10

Protected Members in C++ Inheritance

Protected members play a crucial role in C++ inheritance by balancing data encapsulation with code reusability. The protected access specifier allows certain class members to be accessible within the base class and all derived classes, but not from outside the class hierarchy.

What Are Protected Members?

A protected member is a class data member or method declared with the protected access specifier. Protected members are not accessible from outside the class, but they are accessible to:

  • The class itself
  • Any derived class
  • Friend functions of the class

This makes protected members ideal for scenarios where you want derived classes to have direct access to certain data or functionality, while still keeping those details hidden from other parts of the program.

Accessing Protected Members in Inheritance

  • Public Inheritance: Protected members of the base class remain protected in the derived class. They can be accessed directly within the derived class but not from outside objects.
  • Protected Inheritance: Protected members of the base class remain protected in the derived class, maintaining similar accessibility.
  • Private Inheritance: Protected members of the base class become private in the derived class and can only be accessed within the derived class itself.

Example: Using Protected Members

#include <iostream>
using namespace std;
class Base {
protected:
int value;
public:
void setProtectedMember(int v) {
value = v;
}
int getProtectedMember() {
return value;
}
};
class Derived : public Base {
public:
void showValue() {
cout << "Accessing protected member in derived class: " << value << endl;
}
};
int main() {
Derived obj;
obj.setProtectedMember(42); // Using public setter from base class
obj.showValue(); // Accesses protected member directly in derived class
cout << "Getting protected member via public getter: "
<< obj.getProtectedMember() << endl;
return 0;
}

Explanation

  • The value data member in the Base class is protected.
  • The Derived class can access and modify value directly, demonstrating code reusability and controlled accessibility.
  • Public methods like setProtectedMember and getProtectedMember provide safe access to the protected member from outside the class hierarchy.

Friend Functions and Protected Members

Friend functions can access protected members of a class, providing flexibility when external functions need to interact with internal class data.

Key Takeaways so far:

  • Private members are not directly inherited.
  • Protected members balance encapsulation and accessibility.
  • Getter/setter methods provide controlled access to private members.

Types of Inheritance in C++

C++ supports several kinds of inheritance. Let us review the most inheritance types in c++

with example programs:

1. Single Inheritance

Single inheritance is where a derived class is inherited from one base class and supports reuse and extension of the functions.

Syntax

The syntax of single inheritance in c++ is defined below:

class DerivedClass : public BaseClass 
{ ... };

Example

Animal (base class)
  |
 Dog (derived class)

C++ Code

The single inheritance program in c++

#include <iostream>
using namespace std;

class Animal {
public:
    void eat() {
        cout << "Eating food." << endl;
    }
};

class Dog : public Animal {
public:
    void bark() {
        cout << "Barking." << endl;
    }
};

int main() {
    Dog d;
    d.eat();  // Inherited from Animal
    d.bark(); // Defined in Dog
    return 0;
}

Explanation

  • Dog extends eat() from Animal and adds a bark() method.
  • The main() function makes a Dog object, demonstrating inheritance of eat().

Output

Eating food.
Barking.

2. Multiple Inheritance

Multiple inheritance is when the derived class is inherited by more than one base class and gains access to more than one class member.

Syntax

The syntax of multiple inheritance in c++ is defined below:

class DerivedClass : public BaseClass1, public BaseClass2
{ ... };

Example

             Person             
             /   \                 
          Car    Vehicle  

C++ Code

The multiple inheritance program in c++:

#include <iostream>
using namespace std;

class Person{
public:
    void eat() {
        cout << "Eating food." << endl;
    }
};

class Vehicle {
public:
    void drive() {
        cout << "Driving vehicle." << endl;
    }
};

class Car : public Person, public Vehicle {
public:
    void honk() {
        cout << "Honking." << endl;
    }
};

int main() {
    Car c;
    c.eat();   // Inherited from Person
    c.drive(); // Inherited from Vehicle
    c.honk();  // Defined in Car
    return 0;
}

Explanation

  • Car extends methods from Person and Vehicle.
  • The main() method shows the calling of methods from the base classes and the derived class.

Output

Eating food.
Driving vehicle.
Honking.

3. Hierarchical Inheritance

Hierarchical inheritance in c++ is where more than one derived class inherits from a single base class, with common attributes and methods.

Syntax

The syntax of hierarchical inheritance in c++ is defined below:

class DerivedClass1 : public BaseClass 
{ ... };
class DerivedClass2 : public BaseClass 
{ ... };

Example

           Animal
           /    \
        Dog      Cat

C++ Code

The hierarchical inheritance program in c++:

#include <iostream>
using namespace std;

class Animal {
public:
    void eat() {
        cout << "Eating food." << endl;
    }
};

class Dog : public Animal {
public:
    void bark() {
        cout << "Barking." << endl;
    }
};

class Cat : public Animal {
public:
    void meow() {
        cout << "Meowing." << endl;
    }
};

int main() {
    Dog d;
    Cat c;
    d.eat();   // Inherited from Animal
    d.bark();  // Defined in Dog
    c.eat();   // Inherited from Animal
    c.meow();  // Defined in Cat
    return 0;
}

Explanation

  • Dog and Cat both inherit from Animal but each one of them has its own methods.
  • The main() function instantiates objects of both the derived classes to demonstrate inheritance.

Output

Eating food.
Barking.
Eating food.
Meowing.

4. Multilevel Inheritance

Multilevel or multi inheritance in c++ is defined when a class inherits from a derived class, creating an inheritance chain.

Syntax

The syntax of multilevel inheritance in c++ defined below:

class DerivedClass1 : public BaseClass { ... };
class DerivedClass2 : public DerivedClass1 { ... };

Example 

           Animal
          /      \
        Dog      Puppy

C++ Code

The multilevel inheritance program in c++

#include <iostream>
using namespace std;

class Animal {
public:
    void eat() {
        cout << "Eating food." << endl;
    }
};

class Dog : public Animal {
public:
    void bark() {
        cout << "Barking." << endl;
    }
};

class Puppy : public Dog {
public:
    void play() {
        cout << "Playing." << endl;
    }
};

int main() {
    Puppy p;
    p.eat();   // Inherited from Animal
    p.bark();  // Inherited from Dog
    p.play();  // Defined in Puppy
    return 0;
}

Explanation

  • Both Cat and Dog inherit from Animal and do this in their respective way.
  • The main() function declares objects of both the derived classes to demonstrate inheritance.

Output

Eating food.
Barking.
Playing.

5. Hybrid Inheritance

Hybrid inheritance in c++ is a combination of two or more inheritances like multilevel and multiple inheritance in a program.

Syntax

The syntax of hybrid inheritance in C++ is defined below:

class DerivedClass1 : public BaseClass { ... };
class DerivedClass2 : public DerivedClass1, public AnotherBaseClass { ... };

Example       

            Animal
            /    \
         Car    FlyingCar

C++ Code

The hybrid inheritance program in c++

#include <iostream>
using namespace std;

class Animal {
public:
    void eat() {
        cout << "Eating food." << endl;
    }
};

class Vehicle {
public:
    void drive() {
        cout << "Driving vehicle." << endl;
    }
};

class Car : public Animal {
public:
    void honk() {
        cout << "Honking." << endl;
    }
};

class FlyingCar : public Car, public Vehicle {
public:
    void fly() {
        cout << "Flying." << endl;
    }
};

int main() {
    FlyingCar fc;
    fc.eat();  // Inherited from Animal
    fc.drive(); // Inherited from Vehicle
    fc.honk();  // Inherited from Car
    fc.fly();   // Defined in FlyingCar
    return 0;
}

Explanation

  • FlyingCar both inherits Car (which in turn inherits Animal) and Vehicle.
  • The main() function shows how to call methods of the base classes and the derived class.

Output

Eating food.
Driving vehicle.
Honking.
Flying.

Key Takeaways so far:

  • C++ supports single, multiple, multilevel, hierarchical, and hybrid inheritance.
  • Inheritance types define the relationship and accessibility of class members.
  • Hybrid inheritance combines multiple structures for complex hierarchies.

Function Overriding in C++

Function overriding (also called method overriding) allows a derived class to provide its own implementation of a member function that is already defined in its base class. This is a key feature of object-oriented programming in C++, supporting code reusability and enabling polymorphism.

How Function Overriding Works?

When a derived class defines a member function with the same name, return type, and parameters as a member function in its base class, the derived class's version overrides the base class version. This means that when the function is called on an object of the derived class, the derived class's implementation is executed—even if the object is referenced through a base class pointer or reference (when using virtual functions).

Example: Member Function Overriding

#include <iostream>
using namespace std;

class Base {
public:
    void display() {
        cout << "Display from Base class" << endl;
    }
};

class Derived : public Base {
public:
    void display() {
        cout << "Display from Derived class" << endl;
    }
};

int main() {
    Derived obj;
    
    obj.display();       // Calls Derived's display()
    obj.Base::display(); // Calls Base's display()
    
    return 0;
}

Explanation

  • The display() function is defined in both the base class and the derived class.
  • When display() is called using a Derived object, the derived class version is used.
  • The base class version can still be accessed using the scope resolution operator.

Rules and Effects of Overriding

  • The function in the derived class must have the same signature as the one in the base class.
  • Overriding supports code reusability by allowing derived classes to modify or extend the behavior of base class member functions.
  • If the base class function is declared as virtual, overriding enables runtime polymorphism.

Ambiguity and Multiple Inheritance

In multiple inheritance, ambiguity can occur if two base classes have member functions with the same signature. The derived class must specify which base class's function to use, often with the scope resolution operator, to avoid ambiguity.

Private Members and Overriding

Private members (data members or methods) of the base class are not accessible directly in the derived class, so they cannot be overridden. Overriding applies only to accessible (usually public or protected) member functions.

Fragile Base Class Problem and Hidden Dependencies

When overriding functions in derived classes, changes to the base class's member functions can lead to unexpected behavior or bugs in the derived class, a situation known as the fragile base class problem. Hidden dependencies between base and derived classes can make maintenance more difficult, especially in complex inheritance hierarchies.

Example: The getderiveddata() Method

If a derived class overrides a method like getderiveddata(), it can provide specialized behavior while still maintaining compatibility with the base class interface.

Key Takeaways so far:

  • Overriding allows modifying base class behavior.
  • Only accessible (public/protected) functions can be overridden.
  • Care required in multiple inheritance to avoid ambiguity.

Advantages of Inheritance in C++

Here are the advantages of inheritance in C++:

  • Inheritance enables a derived class to inherit the properties and methods of a base class, avoiding duplication and encouraging efficient coding.
  • Inherited classes share similar functionalities; hence, modifying and maintaining the code in one place (the base class) is easier.
  • New classes or functionality can be added to an existing class structure with minimal modification, allowing scalable and adaptable code.
  • It encourages a class hierarchy, making the program structure logical and easy to maintain.
  • Because standard functionality is taken care of in the base class, bugs in common functions must be corrected only once, thus making debugging easier.

Disadvantages of Inheritance in C++

Here are the disadvantages of inheritance in C++:

  • Overusing inheritance can lead to a complex class structure, making the code harder to understand and maintain.
  • Derived classes are closely coupled with the base classes, and changes in the base class can necessitate changes in derived classes.
  • Changes in the base class might unintentionally influence the derived classes, resulting in bugs.
  • When multiple inheritance is applied, there can be uncertainty in accessing members of two or more base classes, leading to confusing code and bugs.
  • Inheritance may introduce increased overhead, particularly when the methods of base classes are repeatedly overridden in derived classes, which can impact performance.

Quick Note: Inheritance is a powerful tool in C++ for code reuse and structure, but it should be used thoughtfully. Overusing it can make programs complex and more challenging to maintain. Keep hierarchies simple for best results.

Conclusion

In conclusion, C++ inheritance is an effective means of ensuring code reuse, modularity, and maintainability by allowing derived classes to inherit characteristics and behaviours from base classes. It provides more formal and structured programming, simplifying existing functionality. However, excessive use of inheritance leads to greater complexity, tight coupling, and some maintainability problems, particularly in multi-inheritance or deep inheritance. Thus, although inheritance is an important feature in object-oriented programming, care must be taken with code reuse and program simplicity.

Why It Matters?

 Inheritance in C++ is crucial for building reusable, organized, and scalable code. It enables developers to extend existing functionality without rewriting code, fosters a clear class hierarchy, and supports object-oriented principles like polymorphism and encapsulation, making programs easier to maintain, debug, and enhance over time.

Practical Advice for Learners:

  • Begin with single inheritance to grasp fundamental concepts.
  • Use public and protected access specifiers appropriately.
  • Avoid deep or multiple inheritance unless required.
  • Practice function overriding and understand access rules.
  • Keep class hierarchies simple, clear, and maintainable.
  • Use inheritance to enhance functionality, not complicate code.

Frequently Asked Questions

1. What is the is-a relationship in C++ inheritance?
The is-a relationship refers to the connection where a derived class is a specialized form of its base class. For example, if Dog is derived from Animal, then a Dog is an Animal. This relationship is the foundation of simple inheritance in C++ and helps structure code logically.

2. What are the types of inheritance in C++ and how do they relate to access specifiers?
C++ supports several types of inheritance:

  • Simple (Single) Inheritance: One derived class inherits from one base class.
  • Multiple Inheritance: A derived class inherits from more than one base class.
  • Multilevel Inheritance: A class is derived from a derived class, forming a chain.
  • Hierarchical Inheritance: Multiple derived classes inherit from a single base class.
  • Hybrid Inheritance: A combination of two or more types of inheritance.
    Access specifiers—public inheritance, protected inheritance, and private inheritance—determine how base class members are accessible in the derived class.
  • Public inheritance: The most common; establishes a true is-a relationship. Public and protected members of the base class retain their access in the derived class.
  • Protected inheritance: Public and protected base members become protected in the derived class.
  • Private inheritance: Public and protected base members become private in the derived class.

3. What is public inheritance in C++?
Public inheritance is when a derived class publicly inherits from a base class (class Derived : public Base). This means the derived class is a specialized form of the base class, supporting the is-a relationship. Public members of the base class remain public in the derived class, and protected members remain protected.

4. What is protected inheritance in C++?
Protected inheritance (class Derived : protected Base) means that public and protected members of the base class become protected in the derived class. This limits the accessibility of inherited members to the derived class and its subclasses, but not to outside code.

5. What is private inheritance in C++?
Private inheritance (class Derived : private Base) means that public and protected members of the base class become private in the derived class. This form of inheritance does not establish an is-a relationship, but rather an implemented-in-terms-of relationship, often used for code reuse without exposing the base class interface.

6. What is virtual inheritance and when is it used?
Virtual inheritance is a technique used to prevent multiple "instances" of a base class when using multiple inheritance, particularly to resolve the diamond problem. By declaring a base class as virtual (class Derived : virtual public Base), C++ ensures that only one instance of the base class's members is inherited, avoiding ambiguity.

7. What is simple inheritance?
Simple inheritance is another term for single inheritance, where one derived class inherits from a single base class. It is the most straightforward and commonly used form of inheritance in C++.

8. What is simple inheritance in C++?
Simple inheritance, also called single inheritance, means a single derived class inherits from a single base class. It is the most straightforward way to reuse code and establish an is-a relationship.

Read More Articles

Chat with us
Chat with us
Talk to career expert