There are two ways to solve Diamond Problem in C++, one is by using virtual and the other is by using scope resolution operator.
I am facing some issues in doing it by Scope Resolution Operator.
Following is my program,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include <iostream>
using namespace std;
class A {
protected:
int a;
int b;
public:
A()
{
a = 0;
b = 0;
}
void print()
{
a = 5;
}
};
class B : public A
{
int c;
public:
B()
{
c = 0;
}
};
class C :public A
{
int d;
public:
C()
{
d = 0;
}
};
class D : public B, public C
{
int z;
public:
D()
{
z = 0;
}
void print()
{
A::print();
cout << B::a;
cout << C::a;
}
};
int main()
{
D sss;
sss.print();
system("pause");
return 0;
}
|
Now, what I did here is this that I initialized a in void print function of the parent class (Class A) with "5"... Now, by my understanding, when I print these values in the function of D class, it should give value 5 for both the copies of "a" (one coming from Class B and the other coming from Class C)
However, it is doing something else. It does show correct output for the "a" of Class B... but for the Class C, it is giving the output 0.
I don't understand as to how this is happening? Can anyone elaborate, please?
(Also, by initializing a in constructor of A, it gives correct output for both "a"'s in Class D... )