Basic Example using Hierarchical Inheritance in C++


This program demonstrates the concept of inheritance in C++. It defines three classes: A, B, and C. Class A is the base class, and classes B and C are derived from class A. The program creates an object of class C, and when the object is created, the constructor of class A is called first, followed by the constructor of class C.

Here is a brief explanation of what happens when the program is executed:

  • The program starts executing, and the main function is called.
  • The object of class C is created.
  • Since class C is derived from class A, the constructor of class A is called first.
  • After the constructor of class A finishes executing, the constructor of class C is called.
  • The program prints the output to the console, which displays the message "Constructor of A class" followed by "Constructor of C class".

Source Code

#include<iostream>
using namespace std;
class A
{
   public:
    A()
    {
      cout<<"Constructor of A class"<<endl;
    }
};
class B: public A
{
  public:
    B()
    {
      cout<<"Constructor of B class"<<endl;
    }
};
class C: public A
{
  public:
    C()
    {
      cout<<"Constructor of C class"<<endl;
    }
};
int main()
{
  C obj;
  return 0;
}
To download raw file Click Here

Output

Constructor of A class
Constructor of C class

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples