Hierarchical Inheritance
In C++, hierarchical inheritance is a type of inheritance where multiple derived classes inherit from a single base class, meaning one parent class has multiple child classes. This allows for code reusability, as common methods and properties in the base class can be shared across different derived classes.
Syntax
The following syntax can be used to achieve hierarchical inheritance in C++:
class BaseClass {
// Base class members (properties and methods)
};
class DerivedClass1 : accessSpecifier BaseClass {
// Derived class 1 members
};
class DerivedClass2 : accessSpecifier BaseClass {
// Derived class 2 members
};
Example
The following example demonstrates hierarchical inheritance in C++:
#include <iostream>using namespace std;// Base classclass Animal {public:void eat() {cout << "This animal eats food." << endl;}};// Derived class 1class Dog : public Animal {public:void bark() {cout << "Dog barks." << endl;}};// Derived class 2class Cat : public Animal {public:void meow() {cout << "Cat meows." << endl;}};int main() {// Create object of Dog classDog dog1;cout << "Dog Class:" << endl;dog1.eat(); // Inherited from Animal classdog1.bark(); // Dog's own function// Create object of Cat classCat cat1;cout << "\nCat Class:" << endl;cat1.eat(); // Inherited from Animal classcat1.meow(); // Cat's own functionreturn 0;}
The output for the above code is:
Dog Class:This animal eats food.Dog barks.Cat Class:This animal eats food.Cat meows.
In this example, the base class Animal
has a function eat()
. The derived classes Dog
and Cat
inherit from Animal
, allowing them to access the eat()
function. Each derived class also has its own unique function: bark()
for Dog
and meow()
for Cat
.
Codebyte Example
Run the following codebyte to understand how hierarchical inheritance works in C++:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours