C++ Hierarchical Inheritance

Introduction

Hierarchical inheritance in C++ is a type of inheritance where multiple derived classes inherit from a single base class. This allows you to create different classes that share common functionality from the base class while also extending and customizing their own unique features. Hierarchical inheritance promotes code reuse and logical organization of related classes.

Example: Implementing Hierarchical Inheritance

Let’s explore an example of hierarchical inheritance where we have a base class and multiple derived classes.

Base Class: Person

The Person class will contain basic information about a person.

Derived Classes: Student and Employee

The Student and Employee classes will inherit from the Person class and add attributes specific to students and employees, respectively.

Code Example

#include <iostream>
using namespace std;

// Base class
class Person {
public:
    string name;
    int age;

    // Constructor to initialize name and age
    Person(string n, int a) : name(n), age(a) {}

    // Method to display person details
    void displayPerson() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

// Derived class inheriting from Person
class Student : public Person {
public:
    double grade;

    // Constructor to initialize name, age, and grade
    Student(string n, int a, double g) : Person(n, a), grade(g) {}

    // Method to display student details
    void displayStudent() {
        displayPerson(); // Call base class method
        cout << "Grade: " << grade << endl;
    }
};

// Derived class inheriting from Person
class Employee : public Person {
public:
    double salary;

    // Constructor to initialize name, age, and salary
    Employee(string n, int a, double s) : Person(n, a), salary(s) {}

    // Method to display employee details
    void displayEmployee() {
        displayPerson(); // Call base class method
        cout << "Salary: $" << salary << endl;
    }
};

int main() {
    // Create an object of the Student class
    Student student("Aarav", 20, 88.5);
    // Display student details
    student.displayStudent();

    cout << endl;

    // Create an object of the Employee class
    Employee employee("Siya", 30, 50000);
    // Display employee details
    employee.displayEmployee();

    return 0;
}

Output

Name: Aarav, Age: 20
Grade: 88.5

Name: Siya, Age: 30
Salary: $50000

Explanation

  • The Person class is defined with name and age attributes and a constructor to initialize them. The displayPerson method prints the person’s details.
  • The Student class inherits from the Person class and adds an additional attribute, grade. It has a constructor to initialize all attributes, including those inherited from the Person class. The displayStudent method calls the displayPerson method and then prints the grade.
  • The Employee class inherits from the Person class and adds an additional attribute, salary. It has a constructor to initialize all attributes, including those inherited from the Person class. The displayEmployee method calls the displayPerson method and then prints the salary.
  • Objects of the Student and Employee classes are created in the main function, and their details are displayed using the displayStudent and displayEmployee methods, respectively.

Practical Examples

Example 1: Animal Hierarchy

In this example, we have an Animal base class, with Dog and Cat as derived classes.

#include <iostream>
using namespace std;

// Base class
class Animal {
public:
    string name;

    // Constructor to initialize name
    Animal(string n) : name(n) {}

    // Method to display animal details
    void displayAnimal() {
        cout << "Animal: " << name << endl;
    }
};

// Derived class inheriting from Animal
class Dog : public Animal {
public:
    string breed;

    // Constructor to initialize name and breed
    Dog(string n, string b) : Animal(n), breed(b) {}

    // Method to display dog details
    void displayDog() {
        displayAnimal(); // Call base class method
        cout << "Breed: " << breed << endl;
    }
};

// Derived class inheriting from Animal
class Cat : public Animal {
public:
    string color;

    // Constructor to initialize name and color
    Cat(string n, string c) : Animal(n), color(c) {}

    // Method to display cat details
    void displayCat() {
        displayAnimal(); // Call base class method
        cout << "Color: " << color << endl;
    }
};

int main() {
    // Create an object of the Dog class
    Dog dog("Buddy", "Golden Retriever");
    // Display dog details
    dog.displayDog();

    cout << endl;

    // Create an object of the Cat class
    Cat cat("Whiskers", "White");
    // Display cat details
    cat.displayCat();

    return 0;
}

Output

Animal: Buddy
Breed: Golden Retriever

Animal: Whiskers
Color: White

Explanation

  • The Animal class is the base class with a name attribute and a constructor to initialize it. The displayAnimal method prints the animal’s details.
  • The Dog class inherits from the Animal class and adds an additional attribute, breed. It has a constructor to initialize all attributes, including those inherited from the Animal class. The displayDog method calls the displayAnimal method and then prints the breed.
  • The Cat class inherits from the Animal class and adds an additional attribute, color. It has a constructor to initialize all attributes, including those inherited from the Animal class. The displayCat method calls the displayAnimal method and then prints the color.
  • Objects of the Dog and Cat classes are created in the main function, and their details are displayed using the displayDog and displayCat methods, respectively.

Example 2: Vehicle Hierarchy

In this example, we have a Vehicle base class, with Car and Motorcycle as derived classes.

#include <iostream>
using namespace std;

// Base class
class Vehicle {
public:
    string brand;

    // Constructor to initialize brand
    Vehicle(string b) : brand(b) {}

    // Method to display vehicle details
    void displayVehicle() {
        cout << "Brand: " << brand << endl;
    }
};

// Derived class inheriting from Vehicle
class Car : public Vehicle {
public:
    int numberOfDoors;

    // Constructor to initialize brand and number of doors
    Car(string b, int d) : Vehicle(b), numberOfDoors(d) {}

    // Method to display car details
    void displayCar() {
        displayVehicle(); // Call base class method
        cout << "Number of Doors: " << numberOfDoors << endl;
    }
};

// Derived class inheriting from Vehicle
class Motorcycle : public Vehicle {
public:
    bool hasSidecar;

    // Constructor to initialize brand and sidecar status
    Motorcycle(string b, bool s) : Vehicle(b), hasSidecar(s) {}

    // Method to display motorcycle details
    void displayMotorcycle() {
        displayVehicle(); // Call base class method
        cout << "Has Sidecar: " << (hasSidecar ? "Yes" : "No") << endl;
    }
};

int main() {
    // Create an object of the Car class
    Car car("Toyota", 4);
    // Display car details
    car.displayCar();

    cout << endl;

    // Create an object of the Motorcycle class
    Motorcycle motorcycle("Harley-Davidson", true);
    // Display motorcycle details
    motorcycle.displayMotorcycle();

    return 0;
}

Output

Brand: Toyota
Number of Doors: 4

Brand: Harley-Davidson
Has Sidecar: Yes

Explanation

  • The Vehicle class is the base class with a brand attribute and a constructor to initialize it. The displayVehicle method prints the vehicle’s details.
  • The Car class inherits from the Vehicle class and adds an additional attribute, numberOfDoors. It has a constructor to initialize all attributes, including those inherited from the Vehicle class. The displayCar method calls the displayVehicle method and then prints the number of doors.
  • The Motorcycle class inherits from the Vehicle class and adds an additional attribute, hasSidecar. It has a constructor to initialize all attributes, including those inherited from the Vehicle class. The displayMotorcycle method calls the displayVehicle method and then prints whether the motorcycle has a sidecar.
  • Objects of the Car and Motorcycle classes are created in the main function, and their details are displayed using the displayCar and displayMotorcycle methods, respectively.

Advantages of Hierarchical Inheritance

  1. Code Reusability: Derived classes reuse the attributes and methods of the base class, reducing code duplication.
  2. Logical Organization: Allows for a clear and logical organization of related classes, making the code easier to understand and manage.
  3. Extensibility: New functionality can be added to the system by introducing new derived classes without modifying existing classes.

Conclusion

Hierarchical inheritance in C++ allows multiple derived classes to inherit from a single base class, enabling the creation of different classes that share common functionality while extending and customizing their own unique features. This chapter covered the basics of implementing hierarchical inheritance, with practical examples demonstrating its usage. Understanding hierarchical inheritance is essential for writing modular, reusable, and maintainable C++ code.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top