Diamond Problem using Constructor in C++ Programming
The program demonstrates the concept of the "diamond problem" in C++ programming using multiple inheritance and virtual base class, along with the use of constructors. Let's understand it step by step:
- First, we define a class A with a public integer variable x and a constructor that prints the message "Constructing A" to the console when an object of class A is created.
- Next, we define a class B that is derived from class A using virtual inheritance. Class B has a constructor that prints the message "Constructing B" to the console when an object of class B is created.
- Then, we define a class C that is also derived from class A using virtual inheritance. Class C has a constructor that prints the message "Constructing C" to the console when an object of class C is created.
- Finally, we define a class D that is derived from both classes B and C. Class D has a constructor that prints the message "Constructing D" to the console when an object of class D is created.
- In the main function, we create an object of class D and set the value of its integer variable x to 10.
- Since class B and class C both virtually inherit from class A, the class A constructor is only called once during the construction of class D object, even though it is inherited by both class B and class C.
Source Code
#include<iostream>
using namespace std;
//Diamond Problem in C++ Programming
class A
{
public:
int x;
A(){ cout<<"Constructing A "<<endl;}
};
class B:virtual public A
{
public: B(){ cout<<"Constructing B "<<endl;}
};
class C:virtual public A
{
public: C(){ cout<<"Constructing C"<<endl;}
};
class D:public B,public C
{
public: D(){ cout<<"Constructing D "<<endl;}
};
int main()
{
D o;
o.x=10;
return 0;
}
Output
Constructing A
Constructing B
Constructing C
Constructing D
To download raw file
Click Here