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
Personclass is defined withnameandageattributes and a constructor to initialize them. ThedisplayPersonmethod prints the person’s details. - The
Studentclass inherits from thePersonclass and adds an additional attribute,grade. It has a constructor to initialize all attributes, including those inherited from thePersonclass. ThedisplayStudentmethod calls thedisplayPersonmethod and then prints the grade. - The
Employeeclass inherits from thePersonclass and adds an additional attribute,salary. It has a constructor to initialize all attributes, including those inherited from thePersonclass. ThedisplayEmployeemethod calls thedisplayPersonmethod and then prints the salary. - Objects of the
StudentandEmployeeclasses are created in themainfunction, and their details are displayed using thedisplayStudentanddisplayEmployeemethods, 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
Animalclass is the base class with anameattribute and a constructor to initialize it. ThedisplayAnimalmethod prints the animal’s details. - The
Dogclass inherits from theAnimalclass and adds an additional attribute,breed. It has a constructor to initialize all attributes, including those inherited from theAnimalclass. ThedisplayDogmethod calls thedisplayAnimalmethod and then prints the breed. - The
Catclass inherits from theAnimalclass and adds an additional attribute,color. It has a constructor to initialize all attributes, including those inherited from theAnimalclass. ThedisplayCatmethod calls thedisplayAnimalmethod and then prints the color. - Objects of the
DogandCatclasses are created in themainfunction, and their details are displayed using thedisplayDoganddisplayCatmethods, 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
Vehicleclass is the base class with abrandattribute and a constructor to initialize it. ThedisplayVehiclemethod prints the vehicle’s details. - The
Carclass inherits from theVehicleclass and adds an additional attribute,numberOfDoors. It has a constructor to initialize all attributes, including those inherited from theVehicleclass. ThedisplayCarmethod calls thedisplayVehiclemethod and then prints the number of doors. - The
Motorcycleclass inherits from theVehicleclass and adds an additional attribute,hasSidecar. It has a constructor to initialize all attributes, including those inherited from theVehicleclass. ThedisplayMotorcyclemethod calls thedisplayVehiclemethod and then prints whether the motorcycle has a sidecar. - Objects of the
CarandMotorcycleclasses are created in themainfunction, and their details are displayed using thedisplayCaranddisplayMotorcyclemethods, respectively.
Advantages of Hierarchical Inheritance
- Code Reusability: Derived classes reuse the attributes and methods of the base class, reducing code duplication.
- Logical Organization: Allows for a clear and logical organization of related classes, making the code easier to understand and manage.
- 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.