Diamond Problem solving by scope Resolution Operator

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... )
Last edited on
Now, what I did here is this that I initialized a in void print function of the parent class (Class A) with "5"...

Is it a good idea to call “print()” a function that doesn’t print anything?
Anyway, that function doesn’t initialize ‘a’, it assigns 5 to ‘a’.

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)

Wrong. The compiler cannot know if you want to assign 5 to D::B::A::a or D::C::A::a.

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.

No, it does not. Actually it does not compile:
In member function 'void D::print()':
46:12: error: 'A' is an ambiguous base of 'D'


(Also, by initializing a in constructor of A, it gives correct output for both "a"'s in Class D... )

That’s obvious: all the instances of ‘a’ are initialized, so there’s no ambiguity.
Enoizat wrote:
Anyway, that function doesn’t initialize ‘a’, it assigns 5 to ‘a’.

Technically initializing and assigning are the same thing for primitive types so whether you use the initializer list or assignment, you'll end up with the same thing. Initializing doesn't mean to construct an object with a constructor, it means to give an initial value so I think it's proper use of the word.
Topic archived. No new replies allowed.