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