• Articles
  • Interview Questions

Inheritance in C++: A Guide for Beginners and Experienced Programmers

Inheritance in C++ saves time and makes your code more adaptable and easier to manage. It is like giving your code an upgrade, ensuring it grows smarter and stronger with each step. This blog will help you understand the purpose of inheritance in C++, its types, syntax, and some design principles of the OOP concept.

Table of Contents

Watch the video below to understand C programming in detail:

What is Inheritance in C++?

Inheritance is a fundamental concept in object-oriented programming (OOP). Inheritance allows you to create a new class by inheriting properties and behaviors from an existing class. The class that is inherited from is called the “base” or “parent” class, and the new class is called the “derived” or “child” class.

Inheritance promotes code reuse, making it easier to create and maintain a codebase. It allows you to model relationships between classes naturally and hierarchically. 

Purpose and Benefits of Inheritance in C++

Inheritance in C++ provides a powerful mechanism for building on existing code, improving code structure, and facilitating the creation of flexible and extensible software. It’s a fundamental concept in object-oriented programming that contributes to writing cleaner, more maintainable, and scalable code. Let us now discuss the purpose and benefits of inheritance in C++ in detail.

Purpose of Inheritance

Inheritance in C++ serves the purpose of promoting code reusability and creating a hierarchical relationship between classes. It allows a new class (called the derived or child class) to inherit properties and behaviors from an existing class (called the base or parent class).

Benefits of Inheritance

There are a lot of benefits of inheritance; some of them have been listed below.

  • Code Reusability: Inheritance allows you to reuse the code from an existing class, reducing redundancy and making your code more efficient. You don’t have to rewrite the same code for similar functionalities.
  • Maintenance and Updates: If you need to make changes to the common functionality shared by multiple classes, you only need to update the code in the base class. All the derived classes automatically inherit the changes.
  • Polymorphism: Inheritance is a key component of polymorphism, which means “many forms.” This allows objects of different classes to be treated as objects of a common base class. It enables you to write more flexible and extensible code.
  • Structuring Code: Inheritance helps in organizing and structuring your code in a more logical and hierarchical manner. It reflects the relationships between different classes, making the code easier to understand and maintain.
  • Enhancement of Existing Classes: You can extend the functionality of existing classes without modifying their code. This is particularly useful when dealing with third-party libraries or classes that you don’t want to alter.
  • Encapsulation: Inheritance, when used with other object-oriented principles like encapsulation, helps in creating modular and encapsulated code. Each class can represent a specific functionality or feature, making the code more modular and easier to comprehend.

Parent and Child Classes in C++

Classes are used to describe how to make objects in object-oriented programming (OOP). One way to think of a class is as a plan or template. Objects are copies of that template. 

Some classes are more general or abstract than others. This is called a parent-child relationship. One class is called the parent or base class, and the other is called the child or derived class. Inheritance is the word for this kind of bond.

Parent Class

A parent class is a class that holds common attributes and behaviors that other classes can use. It is sometimes called a base or super class.

Here, Vehicle is the parent class with attributes like speed and color, along with a method start().

// Parent Class
class Vehicle {
public:
    int speed;
    string color;
    void start() {
        cout << "Vehicle started" << endl;
    }
};

Child Class

A child class is a class that inherits from another class, gaining access to its attributes and behaviors. It is also called a derived class.

In the below example, Car is the child class, and it inherits from the Vehicle class using : public Vehicle. It adds its attribute numDoors and a method honk().

// Child Class

class Car : public Vehicle {
public:
    int numDoors;
    void honk() {
        cout << "Car honked" << endl;
    }
};

In the diagram, the arrow indicates that the derived class/child class inherits from the base class/parent class.

Code Example of Parent and Child Class in C++

The below code is an example of parent and child class in C++:

int main() {
    // Creating an object of the Car class
    Car myCar;
    // Accessing attributes and methods from the parent class
    myCar.speed = 60;
    myCar.color = "Blue";
    myCar.start();
    // Accessing attributes and methods from the child class
    myCar.numDoors = 4;
    myCar.honk();
    return 0;
}

So, let us understand how this code works:

When you create an object of the child class (Car), it has the attributes and methods of the parent class (Vehicle) and its unique features.

In this example, myCar is an object of the Car class. It inherits attributes and methods from the Vehicle class and has its features.

  • There is a class named Car defined. This class has two attributes (speed and color) and a method (start).
  • An object of the Car class named myCar is created. This object will have the attributes speed and color, as well as the method start.
  • The code attempts to access attributes and methods that belong to a child class of Car (since numDoors and honk are not defined in the Car class). However, the definition of this child class is missing in the provided code.

Do you want to jumpstart your career in computer programming? Enroll in our C Programming Course and gain the skills to succeed!

Basic Syntax of Inheritance in C++

Let us now understand how we can declare base and derived classes in C++, followed by access specifiers and the creation of objects of the derived class. At the end, we will have a look at the concept of constructors and destructors.

Declaring Base and Derived Classes

In C++, inheritance is declared using a colon (:) followed by an access specifier after the derived class name.

// Base Class
class BaseClass {
    // Base class members
};
// Derived Class
class DerivedClass : access_specifier BaseClass {
    // Derived class members
};
  • BaseClass: This is the main or parent class that holds common attributes or methods.
  • DerivedClass: This is the class that inherits from the BaseClass. It gains access to the attributes and methods of the BaseClass.

Access Specifiers (Public, Protected, and Private)

When inheriting a class, you need to specify how the members of the base class are accessible in the derived class. There are three access specifiers: public, protected, and private.

Public Inheritance

  • Members of the base class are inherited as public members in the derived class. This means that all the attributes and methods (members) of the base class are accessible to anyone who uses an object of the derived class.
  • Uses a public access specifier

The below code snippet shows how you use the public access specifier:

class DerivedClass : public BaseClass {
    // Derived class members and methods
};

Protected Inheritance

  • Members of the base class are inherited as protected members in the derived class. It means that the attributes and methods of the base class become protected in the derived class. This allows the derived class and its subclasses to access them, but not outside code.
  • Uses a protected access specifier

The below code snippet shows how you use the protected access specifier:

class DerivedClass : protected BaseClass {
    // Derived class members and methods
};

Private Inheritance

  • Members of the base class are inherited as private members in the derived class. It means that the attributes and methods of the base class become private in the derived class. This means only the derived class itself can directly access them, and not any outside code.
  • Uses a private access specifier

The below code snippet shows how you use the private access specifier:

class DerivedClass : private BaseClass {
    // Derived class members and methods
};

Creating Objects of Derived Class

After defining a class, you can create objects of that class. 

For instance,

int main() {
    // Creating an object of the derived class
    Dog myDog;
    // Accessing methods from both base and derived classes
    myDog.eat();   // This comes from the base class
    myDog.bark();  // This is unique to the derived class
    return 0;
}

Creating an Object (myDog): We make an instance of the Dog class. Now, myDog has access to the eat method from the base class and the bark method from the derived class.

Constructors and Destructors in Inherited Classes

A constructor is a special function that gets called when an object is created. A destructor is called when an object is about to be destroyed (usually when the program ends). Inherited classes can use both the base class’s constructor and destructor.

// Base Class
class Animal {
public:
    // Constructor
    Animal() {
        cout << "Animal constructor" << endl;
    }
    // Destructor
    ~Animal() {
        cout << "Animal destructor" << endl;
    }
};
// Derived Class
class Dog : public Animal {
public:
    // Constructor
    Dog() {
        cout << "Dog constructor" << endl;
    }
    // Destructor
    ~Dog() {
        cout << "Dog destructor" << endl;
    }
};

Constructor (Animal(), Dog()): These are special functions that get executed when objects of the respective classes are created. They are used to set up initial values or do other setup work.

Destructor (~Animal(), ~Dog()): These special functions get executed when objects are about to be destroyed. They are used to clean up resources or do other finalization work.

When you create an object of the derived class, both the base class’s and derived class’s constructors get called, and when the program ends, both the derived class’s and base class’s destructors get called.

Check out our blog on What is Friend Function in C++? to learn more about C++ and its functions.

Types of Inheritance (Single, Multiple, Multilevel, and Hierarchical)

There are four types of inheritance in C++. They are:

Let us now discuss each one of them in detail below.

C++ Single Inheritance

Single inheritance in C++ is a concept where a class can inherit the properties and behaviors of only one other class. In simpler terms, it’s like a child inheriting traits from a single parent.

C++ Single Inheritance

Here, DerivedClass inherits from BaseClass.

Code Implementation for C++ Single Inheritance

#include<iostream>
// Base class
class BaseClass {
public:
    void baseMethod() {
        std::cout << "This is Base class method" << std::endl;
    }
};
// Derived class
class DerivedClass : public BaseClass {
public:
    void derivedMethod() {
        std::cout << "This is Derived class method" << std::endl;
    }
};
int main() {
    // Creating an object of the derived class
    DerivedClass myObject;
    // Accessing methods from the base class
    myObject.baseMethod();
    // Accessing methods from the derived class
    myObject.derivedMethod();
    return 0;
}

In the above code,

  • We have a BaseClass with a method baseMethod().
  • We have a DerivedClass that inherits from the BaseClass (: public BaseClass). It also has its method derivedMethod().
  • When you create an object of the DerivedClass (DerivedClass myObject), it can access both the methods from the BaseClass and its methods.

Output

This is Base class method

This is Derived class method

Check out the Top 20 C++ Project Ideas

C++ Multiple Inheritance

Multiple inheritance in C++ allows a class to inherit from more than one class. In simpler terms, it’s like a child inheriting qualities from the mother and the father.

C++ Multiple Inheritance

In the diagram, ChildClass inherits from both BaseClass1 and BaseClass2.

Code Implementation for C++ Multiple Inheritance

#include<iostream>
// Base class 1
class BaseClass1 {
public:
    void display1() {
        std::cout << "BaseClass1 Display" << std::endl;
    }
};
// Base class 2
class BaseClass2 {
public:
    void display2() {
        std::cout << "BaseClass2 Display" << std::endl;
    }
};
// Derived class
class DerivedClass : public BaseClass1, public BaseClass2 {
public:
    void displayDerived() {
        std::cout << "DerivedClass Display" << std::endl;
    }
};
int main() {
    // Creating an object of the derived class
    DerivedClass myObject;
    // Accessing methods from both base classes
    myObject.display1();
    myObject.display2();
    // Accessing method from the derived class
    myObject.displayDerived();
    return 0;
}

1. Class Definitions

BaseClass1

  • It represents the first base class.
  • It has a method display1() that prints “BaseClass1 Display” to the console.

BaseClass2

  • It represents the second base class.
  • It has a method display2() that prints “BaseClass2 Display” to the console.

DerivedClass

  • It represents the derived class that inherits from both BaseClass1 and BaseClass2.
  • It has its own method displayDerived() that prints “DerivedClass Display” to the console.

2. Main Function

Creating an Object

  • DerivedClass myObject;

This creates an object named myObject of the DerivedClass.

Accessing Methods

  • myObject.display1();: Calls the display1() method of BaseClass1 through the derived class object
  • myObject.display2();: Calls the display2() method of BaseClass2 through the derived class object
  • myObject.displayDerived();: Calls the displayDerived() method of the DerivedClass

Output

BaseClass1 Display

BaseClass2 Display

DerivedClass Display

C++ Multilevel Inheritance

Multilevel inheritance in C++ is a type of inheritance in which a derived class is created from another derived class. This creates a chain of inheritance with more than two levels.

C++ Multilevel Inheritance

In this diagram, BaseClass is the initial or root class, DerivedClass1 is derived from BaseClass, DerivedClass2 is further derived from DerivedClass1, and so on.

Code Implementation for C++ Multiple Inheritance

#include <iostream>
// Base Class
class Animal {
public:
    void eat() {
        std::cout << "Animal is eating" << std::endl;
    }
};
// Derived Class 1
class Mammal : public Animal {
public:
    void breathe() {
        std::cout << "Mammal is breathing" << std::endl;
    }
};
// Derived Class 2
class Dog : public Mammal {
public:
    void bark() {
        std::cout << "Dog is barking" << std::endl;
    }
};
int main() {
    // Creating an object of the derived class
    Dog myDog;
    // Accessing methods from all levels of inheritance
    myDog.eat();     // From the base class
    myDog.breathe(); // From the first derived class
    myDog.bark();    // From the second derived class
    return 0;
}

In the above example,

  • Animal is the base class, representing common features of all animals.
  • Mammal is derived from Animal, representing animals that are mammals and have additional features.
  • Dog is further derived from Mammal, representing a specific type of mammal.
  • The main function creates an object of the Dog class, and you can see that it can access methods from all levels of the inheritance chain:
  • myDog.eat() accesses the eat method from the base class (Animal). All animals can eat, and myDog uses the eating ability inherited from basic animal behavior.
  • myDog.breathe() accesses the breathe method from the first derived class (Mammal). Mammals can breathe, so myDog uses the ability to breathe inherited from being a mammal.
  • myDog.bark() accesses the bark method from the second derived class (Dog). Dogs have the unique ability to bark, so myDog uses the barking ability inherited from being a dog.

Output

Animal is eating

Mammal is breathing

Dog is barking

C++ Hierarchical Inheritance

Hierarchical inheritance is an inheritance in C++ where multiple derived classes inherit from a single base or parent class. This creates a hierarchical structure, forming a tree-like relationship.

C++ Hierarchical Inheritance

In the diagram, BaseClass is the parent, and DerivedClass1 and DerivedClass2 are its children. In hierarchical inheritance, the base class’s features are shared among multiple derived classes. In the below example, both Dog and Cat share the common behavior of eating from the Animal class, and each has its unique behavior.

Code Implementation for Hierarchical Multiple Inheritance

#include<iostream>
// Base class
class Animal {
public:
    void eat() {
        std::cout << "Animal is eating" << std::endl;
    }
};
// Derived class 1
class Dog : public Animal {
public:
    void bark() {
        std::cout << "Dog is barking" << std::endl;
    }
};
// Derived class 2
class Cat : public Animal {
public:
    void meow() {
        std::cout << "Cat is meowing" << std::endl;
    }
};
int main() {
    // Creating objects of the derived classes
    Dog myDog;
    Cat myCat;
    // Accessing methods from the base class
    myDog.eat();
    myCat.eat();
    // Accessing methods from the derived classes
    myDog.bark();
    myCat.meow();
    return 0;
}
  • We have a BaseClass called Animal with a method eat.
  • Dog and Cat are derived classes from Animal. They inherit the eat method.
  • In the main function, we create objects myDog and myCat.
  • Both myDog and myCat can access the eat method from the Animal class directly.
  • myDog can also access the bark method, and myCat can access the meow method.

Output

Animal is eating

Animal is eating

Dog is barking

Cat is meowing

Check out the top C++ Interview Questions to ace your next interview!

Composition Vs. Inheritance

Composition and inheritance in C++ are two approaches to achieving code reuse. While inheritance involves creating a new class by inheriting the properties of an existing one, composition involves creating objects within a class for flexibility and modularity. The further difference between composition and inheritance is demonstrated below in the table.

AspectCompositionInheritance
DefinitionCombining different classes to create a new oneCreating a new class by using properties of existing classes
FlexibilityMore flexibleYou can change components easily.Less flexibleChanges can affect the entire hierarchy.
Code ReusabilityFocused on using the functionality of existing classesFocused on using structure and behavior from parent classes
ComplexityGenerally results in less complex and more modular codeMay lead to more complex code, especially with deep hierarchies
ExampleA car composed of an engine, wheels, and seatsA car inheriting from a vehicle class

Learn more about Hybrid Inheritance in C++ – All you need to know.

Design Principles for Effective Inheritance

Design Principles for Effective Inheritance are crucial to maintaining code clarity and flexibility. They ensure that inheritance hierarchies are simple, focused, and adaptable to changes. Following the below-listed principles leads to more maintainable, reusable, and future-proof code in object-oriented programming.

  • Keep it Simple: Keep your inheritance hierarchy simple and easy to understand. Avoid unnecessary layers of abstraction.
  • Favor Composition Over Inheritance: If possible, prefer using composition when combining functionalities. It often leads to more flexible and maintainable code.
  • Follow the “is-a” Relationship: Use inheritance when there is a clear “is-a” relationship between the base and derived classes. For example, a “Car” is a “Vehicle.”
  • Avoid Deep Inheritance Hierarchies: Deep hierarchies can make the code harder to maintain. Try to keep the hierarchy shallow and focused on essential relationships.
  • Use Abstract Classes and Interfaces Wisely: Abstract classes and interfaces can be powerful tools, but use them judiciously. Abstract classes represent common behavior, while interfaces define a contract.
  • Prefer Composition for Code Reusability: Composition often provides better code reusability. Components can be easily reused in different contexts, making the code more modular.
  • Think About Future Changes: Consider how your design might evolve. If there’s a chance of future changes, a more flexible approach like composition might be beneficial.

Conclusion

Inheritance in C++ is a powerful tool for building flexible and reusable code. By allowing a new class to inherit properties from an existing one, it promotes code organization and modularity. The significance of inheritance lies in its ability to reduce redundancy and promote a maintainable codebase. Instead of duplicating code in multiple places, common attributes and methods can be centralized in a base class. providing a robust foundation for constructing scalable, well-organized, and modular software systems. 

If you have any doubts or queries, drop them on our Community!

FAQs

What is the main purpose of inheritance in C++?

Inheritance enables code reuse by allowing a new class to inherit properties and behaviors from an existing class, fostering a modular and efficient design.

Can a C++ class inherit from multiple classes?

Yes, C++ supports multiple inheritance, allowing a class to inherit properties from more than one base class. However, careful design is crucial to avoid ambiguity.

What is the difference between public, private, and protected inheritance?

Public inheritance allows public members of the base class to be public in the derived class. Private inheritance makes them private, and protected inheritance makes them protected.

When should I use composition instead of inheritance?

Use composition when a class needs to contain an object of another class for flexibility. Inheritance is suitable when a new class is a specialized version of an existing class.

How does inheritance contribute to polymorphism in C++?

Inheritance, combined with virtual functions, facilitates polymorphism in C++. Derived classes can override base class methods, allowing dynamic binding and flexibility in handling objects.

Course Schedule

Name Date Details
Data Analytics Courses 04 May 2024(Sat-Sun) Weekend Batch
View Details
Data Analytics Courses 11 May 2024(Sat-Sun) Weekend Batch
View Details
Data Analytics Courses 18 May 2024(Sat-Sun) Weekend Batch
View Details

Advanced-Certification-in-Data-Science-and-AI-IITR.png