Understanding Inheritance in C++

  • Last updated Apr 25, 2024

Inheritance is a fundamental concept in the world of object-oriented programming. When it comes to C++, this powerful language offers robust support for inheritance, making it a cornerstone for creating efficient and reusable code. In this tutorial, you will learn what inheritance is, how it works in C++, and why it's a crucial element in building software systems.

What is Inheritance?

Inheritance is one of the four primary principles of object-oriented programming (OOP), which include encapsulation, abstraction, polymorphism, and, of course, inheritance. At its core, inheritance allows you to create a new class that is based on an existing class. The new class inherits the attributes and behaviors of the parent class, which is often referred to as the base or superclass. This relationship enables the creation of a hierarchy of classes, which is central to code organization and reusability.

Base Class and Derived Class

Inheritance starts with the creation of a base class (also known as a parent class) that defines the common attributes and methods. Then, you can derive one or more child classes from this base class. These derived classes (also known as subclasses) inherit the properties and methods of the base class. This hierarchical structure allows you to reuse and extend the functionality of the base class.

Access Specifiers

C++ supports three types of access specifiers in inheritance:

  • Public: In this case, the derived class can access the base class's public members as if they were its own.
  • Protected: With protected access, the derived class can access the base class's protected members, but they remain hidden from external code.
  • Private: Private members of the base class are inaccessible to the derived class.
Syntax

The syntax for declaring a derived class in C++ is as follows:

class BaseClass {
    // Base class members
};

class DerivedClass : access_specifier BaseClass {
    // Derived class members
};
The Advantages of Inheritance

Now that we understand the basics of inheritance in C++, let's explore why it is essential:

  • Inheritance promotes code reusability. You can inherit common attributes and methods in each new class from a base class, thereby reducing redundancy and errors.
  • Inheritance helps you better organize and manage your code by allowing the creation of a structured hierarchy of classes.
  • When you need to make changes to shared attributes or methods, you only need to update the base class, and the changes will automatically apply to all derived classes.
  • Inheritance is closely related to polymorphism, another essential OOP concept. Polymorphism enables you to treat derived classes as instances of their base class, enhancing flexibility in your code.
Example

Here's a simple example of inheritance in C++ to demonstrate a real-world scenario:

#include <iostream>
#include <string>

// Base class: Vehicle
class Vehicle {
private:
    std::string make;
    std::string model;
    int year;

public:
    Vehicle(std::string make, std::string model, int year)
        : make(make), model(model), year(year) {}

    void start() {
        std::cout << "The " << year << " " << make << " " << model << " is starting." << std::endl;
    }

    void stop() {
        std::cout << "The " << year << " " << make << " " << model << " is stopping." << std::endl;
    }
};

// Derived class: Car
class Car : public Vehicle {
private:
    int numDoors;

public:
    Car(std::string make, std::string model, int year, int doors)
        : Vehicle(make, model, year), numDoors(doors) {}

    void honk() {
        std::cout << "The car honks." << std::endl;
    }

};

// Derived class: Motorcycle
class Motorcycle : public Vehicle {
private:
    std::string bikeType;
    
public:
    Motorcycle(std::string make, std::string model, int year, std::string type)
        : Vehicle(make, model, year), bikeType(type) {}

    void wheelie() {
        std::cout << "The motorcycle pops a wheelie." << std::endl;
    }

};

int main() {
    Car myCar("Toyota", "Camry", 2023, 4);
    Motorcycle myMotorcycle("Honda", "CBR", 2023, "Sport");

    myCar.start();
    myCar.honk();
    myCar.stop();

    myMotorcycle.start();
    myMotorcycle.wheelie();
    myMotorcycle.stop();

    return 0;
}

In this example, we have a base class Vehicle with common attributes and methods for starting and stopping. Two derived classes, Car and Motorcycle, inherit from the Vehicle class and add their own specific methods (honk for cars and wheelie for motorcycles) and attributes.

The program demonstrates how inheritance can be used to model a hierarchy of classes, where derived classes inherit and extend the functionality of the base class. This allows you to represent different types of vehicles while reusing common code and providing specialized behavior.

The output of the above code is as follows:

The 2023 Toyota Camry is starting.
The car honks.
The 2023 Toyota Camry is stopping.
The 2023 Honda CBR is starting.
The motorcycle pops a wheelie.
The 2023 Honda CBR is stopping.