Basic Example using Single Level Inheritance in C++


  • The program defines two classes A and B where B is derived from A.
  • Both classes have constructors which are called automatically when objects of those classes are created.
  • The program creates an object of class B named obj in the main() function.
  • When obj is created, the constructor of class A is called first, which prints the message "Constructor of A class" to the console.
  • After that, the constructor of class B is called, which prints the message "Constructor of B class" to the console.
  • Finally, the program terminates and returns 0.

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";
    }
};
int main()
{
  B obj;
  return 0;
}
To download raw file Click Here

Output

Constructor of A class
Constructor of B 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