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 derived class B, which in turn serves as a base class for the derived class C. Class B provides a link for the inheritance between A and C and is known as an intermediate base class. The chain A, B, C is known as the inheritance path.
Constructor in Multilevel Inheritance
Example 1: Below is the C++ program to show the concept of constructor in multilevel Inheritance.
C++
#include<iostream>
using namespace std;
class A
{
public :
A()
{
cout << "Base class A constructor \n" ;
}
};
class B: public A
{
public :
B()
{
cout << "Class B constructor \n" ;
}
};
class C: public B
{
public :
C()
{
cout << "Class C constructor \n" ;
}
};
int main()
{
C obj;
return 0;
}
|
Output
Base class A constructor
Class B constructor
Class C constructor
Example 2: Below is the C++ program to implement multilevel inheritance.
C++
#include<iostream>
using namespace std;
class A
{
public :
A()
{
int a = 5, b = 6, c;
c = a + b;
cout << "Sum is:" <<
c << endl;
}
};
class B: public A
{
public :
B()
{
int d = 50,e = 35, f;
f = d - e;
cout << "Difference is:" <<
f << endl;
}
};
class C: public B
{
public :
C()
{
int g = 10, h = 20, i;
i = g * h;
cout << "Product is:" <<
i << endl;
}
};
int main()
{
C obj;
return 0;
}
|
Output
Sum is:11
Difference is:15
Product is:200
Last Updated :
07 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...