The Wayback Machine - https://web.archive.org/web/20240917192624/https://www.geeksforgeeks.org/cpp-hierarchical-inheritance/
Open In App

C++ Hierarchical Inheritance

Last Updated : 27 Oct, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Inheritance is a feature of Object-Oriented-programming in which a derived class (child class) inherits the property (data member and member functions) of the Base class (parent class). For example, a child inherits the traits of their parents.

In Hierarchical inheritance, more than one sub-class inherits the property of a single base class. There is one base class and multiple derived classes. Several other classes inherit the derived classes as well. Hierarchical structures thus form a tree-like structure. It is similar to that, mango and apple both are fruits; both inherit the property of fruit. Fruit will be the Base class, and mango and apple are sub-classes. 

The below diagram shows, Class A is a Base class, B is a subclass inherited from class A, and C is a subclass it also inherits from class A.

Hierarchical Inheritance In C++

 

Similarly, if another subclass inherits property from B class and so on then there will be a hierarchy, and a tree-like structure is formed, below is the diagram.

Hierarchical Inheritance In C++

 

Here X and Y are sub-class (child class) that inherits property from class B, and M and N are sub-class (child class) that inherits property from class C. B is the parent class of X and Y, and C is the parent class of M and N. access_specifier provides the visibility mode in the class declaration. By inheriting from the base class, the derived class inherits the members of the base class.

Syntax:

Class A  
{  
   ............  
};  
Class B: access_specifier A  
{  
   .........  
};  
Class C: access_specifier A 
{  
  ............. 
};  

Example 1:

C++




// C++ program for Hierarchical Inheritance
#include<iostream>
using namespace std;
  
class A   //superclass A
{
  public:
  void show_A() {
    cout<<"class A"<<endl;
  }
};
class B : public A   //subclass B
{
  public:
  void show_B() {
    cout<<"class B"<<endl;
  }
};
  
class C : public A   //subclass C
{
  public:
  void show_C() {
    cout<<"class C"<<endl;
  }
};
  
int main() {
  B b;  // b is object of class B
  cout<<"calling from B: "<<endl;
  b.show_B();
  b.show_A();
    
  C c;  // c is object of class C
  cout<<"calling from C: "<<endl;
  c.show_C();
  c.show_A();
  return 0;
}
   


Output

calling from B: 
class B
class A
calling from C: 
class C
class A

Explanation: In the above program A is the superclass also known as a parent class, and B and C are subclasses also known as the child class. class B and class C inherit property from class A.

Example 2:

C++




// C++ program to illustrate the above concept
  
#include <iostream>
using namespace std;
  
// Base class
class shape {
public:
    string name;
    int sides;
  
    shape(string name, int sides) // constructor
    {
        this->name = name; // this pointer
        this->sides = sides;
    }
};
  
// Derived class
class triangle : public shape // mode is public
{
  
private:
    int base;
    int height;
  
public:
    // shape constructor taking arguments
    // from triangle constructor
    triangle(string name, int sides, int base, int height) : shape(name, sides)
  
    {
        this->base = base;
        this->height = height;
    }
  
    void area()
    {
        cout << "area of triangle: "
             << (0.5 * base * height) << endl;
    }
    void details()
    {
        cout << "shape is: " << name << endl;
        cout << "no. of sides are: " << sides << endl;
        cout << "base is: " << base << endl;
        cout << "height is: " << height << endl;
        area(); // calling area()
    }
};
  
// Derived class
class square : public shape {
private:
    int height;
  
public:
    // shape constructor taking arguments
    // from square constructor
    square(string name, int sides, int height) : shape(name, sides)
    {
        this->height = height;
    }
  
    void area()
    {
        cout << "area of square: " << (height * height)
             << endl;
    }
  
    void details()
    {
        cout << "shape is: " << name << endl;
        cout << "no. of sides are: " << sides << endl;
        cout << "height is: " << height << endl;
        area(); // calling area()
    }
};
  
int main()
{
    // Creating objects
    triangle t("triangle", 3, 2, 3);
    square s("square", 4, 2);
  
    t.details();
    cout << endl << endl;
  
    s.details();
    return 0;
}


Output

shape is: triangle
no. of sides are: 3
base is: 2
height is: 3
area of triangle: 3


shape is: square
no. of sides are: 4
height is: 2
area of square: 4

Explanation: In the above code, we created three classes: shape, Triangle, and square. In this example, the shape class is a superclass. triangle and square are subclasses that inherit from the shape class. A constructor in every class is used to initialize data members. Then we created triangle and square objects and used details() to produce information for the triangle and square. Here, access modifiers are public.



Previous Article
Next Article

Similar Reads

Difference between Single and Multiple Inheritance in C++
Single InheritanceSingle inheritance is one in which the derived class inherits the single base class either public, private, or protected access specifier. In single inheritance, the derived class uses the features or members of the single base class. These base class members can be accessed by a derived class or child class according to the acces
4 min read
Constructor in Multilevel Inheritance in C++
Constructor is a class member function with the same name as the class. The main job of the constructor is to allocate memory for class objects. Constructor is automatically called when the object is created. Multilevel Inheritance Derivation of a class from another derived class is called Multilevel Inheritance. Class A is the base class for the d
2 min read
Constructor in Multiple Inheritance in C++
Constructor is a class member function with the same name as the class. The main job of the constructor is to allocate memory for class objects. Constructor is automatically called when the object is created. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can derive from several(two or more) base classes. The construct
2 min read
Inheritance Ambiguity in C++
Pre-requisites: Inheritance in C++, Multiple Inheritance in C++ In multiple inheritances, when one class is derived from two or more base classes then there may be a possibility that the base classes have functions with the same name, and the derived class may not have functions with that name as those of its base classes. If the derived class obje
6 min read
C++ Multilevel Inheritance
Multilevel Inheritance in C++ is the process of deriving a class from another derived class. When one class inherits another class it is further inherited by another class. It is known as multi-level inheritance. For example, if we take Grandfather as a base class then Father is the derived class that has features of Grandfather and then Child is t
2 min read
Hybrid Inheritance In C++
Before jumping into Hybrid Inheritance, let us first know what is inheritance. Inheritance is a fundamental OOP concept in C++ that allows a new class, also known as a subclass or derived class, to inherit properties and methods from an already-existing class, also known as a superclass or base class. C++ supports 5 types of inheritance: Single Inh
6 min read
Inheritance and Friendship in C++
Inheritance in C++: This is an OOPS concept. It allows creating classes that are derived from other classes so that they automatically include some of the functionality of its base class and some functionality of its own. (See this article for reference) Friendship in C++: Usually, private and protected members of a class cannot be accessed from ou
2 min read
Comparison of Inheritance in C++ and Java
The purpose of inheritance is the same in C++ and Java. Inheritance is used in both languages for reusing code and/or creating an ‘is-a’ relationship. The following examples will demonstrate the differences between Java and C++ that provide support for inheritance. 1) In Java, all classes inherit from the Object class directly or indirectly. Theref
4 min read
Multiple Inheritance in C++
Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes. The constructors of inherited classes are called in the same order in which they are inherited. For example, in the following program, B's constructor is called before A's constructor. A class can be derived from more than one base class. Eg: (i) A CHILD
5 min read
C++ Inheritance Access
Prerequisites: Class-Object in C++Inheritance in C++Before learning about Inheritance Access we need to know about access specifiers. There are three Access specifiers in C++. These are: public - members are accessible from outside the class, and members can be accessed from anywhere.private - members cannot be accessed (or viewed) from outside the
4 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
Difference between Inheritance and Polymorphism
Inheritance is one in which a new class is created that inherits the properties of the already exist class. It supports the concept of code reusability and reduces the length of the code in object-oriented programming. Types of Inheritance are:Single inheritanceMulti-level inheritanceMultiple inheritancesHybrid inheritanceHierarchical inheritanceEx
5 min read
Does overloading work with Inheritance?
If we have a function in base class and another function with the same name in derived class, can the base class function be called from derived class object? This is an interesting question and as an experiment, predict the output of the following C++ program: [GFGTABS] C++ #include &lt;iostream&gt; using namespace std; class Base { public: int f(
5 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
30 OOPs Interview Questions and Answers (2024) Updated
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
C++ Interview Questions and Answers (2024)
C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent in C++. It is utilized by top IT companies such as
15+ min read
Left Shift and Right Shift Operators in C/C++
In C/C++, left shift (&lt;&lt;) and right shift (&gt;&gt;) operators are binary bitwise operators that are used to shift the bits either left or right of the first operand by the number of positions specified by the second operand allowing efficient data manipulation. In this article, we will learn about the left shift and right shift operators. Le
6 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is &lt;string&gt;. The substring function takes two values pos and len as an argument
8 min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
9 min read
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read
C++ Data Types
All variables use data type during declaration to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data they can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared. Every data type
10 min read
Convert String to int in C++
Converting a string to int is one of the most frequently encountered tasks in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we can convert numbers that are stored as strings. Exa
8 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
11 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the &lt;map&gt; header file. Basic std::map Member FunctionsSome basic functions associated with std::
8 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
10 min read
Operator Overloading in C++
in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning. In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot overload in C++. C++ Operator OverloadingC++ has
8 min read
Templates in C++ with Examples
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types. Rather than writing and maintaining multiple codes, we can write one sort() and pass the dat
10 min read
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the
6 min read
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time an object of a class is created. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor
7 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read