+ 1
Why can't the D class object access the disp function in class A? (Diamond Problem) (Code inside the post)
#include<iostream> using namespace std; class A { public: void disp() { cout << "Class A"; } }; class B : public A { }; class C : public A { }; class D : public B, public C { }; int main() { D obj; obj.A::disp(); return 0; }
9 Answers
+ 4
first sorry for my english ....
line : obj.A::disp () gives compile time error.
it is becouse compile goes to confuse for what path disp() is inherited .....either by the
1. class A -> classB -> classD or
2 classA-> classC-> classD
......
and if draw the arrows to the flow of inheritance of classes its seems like diamond or rhombus. ...
that's by this problem is known as diamond problem
+ 4
#include<iostream>
using namespace std;
class A
{
public:
void disp()
{
cout << "Class A";
}
};
class B :virtual public A
{
};
class C :virtual public A
{
};
class D : public B, public C
{
};
int main()
{
D obj;
obj.A::disp();
return 0;
}
notice that class B and class C virtually inherit A (additional virtual right before public)
this now able to run on the app compiler
this wikipedia page explains the situation with a nice example:
https://en.m.wikipedia.org/wiki/Virtual_inheritance
+ 2
their is an ambiguity
compile get confuse which path has to follow
1. D-> B ->A::dis ()
2. D-> C-> A::dis ()
+ 1
@james .......during the compilation procces, compiler finds more then one path for the same .... so it is ambitious for the compiler ..... and gives compile time error.
0
I just tried running your code in Visual Studio and it compiled and executed fine. Is it perhaps a problem with the compiler the website uses?
0
I use the CodeBlocks IDE. And it shows the same error. This problem is written in Robert Lafore's book on C++ but unfortunately, it doesn't provide it's solution. But still, thanks for the reply and your time. :) Hope someone here gives a lil explanation regarding it.
0
@Rajkumar, but I do write obj.A::disp( ) i.e., explicitly pointing out the object A here, shouldn't the compiler know what I'm trying to do here? And don't worry, I understood each word of yours perfectly. :)
0
Even though you use .A, your object is still of class D, making it have the ambiguous path that others have mentioned.
0
Thanks a lot everyone. All of your answers were really helpful.