+ 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; }

17th Nov 2016, 5:40 PM
james nyle
9 Antworten
+ 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
17th Nov 2016, 6:03 PM
Rajkumar Nagar
Rajkumar Nagar - avatar
+ 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
17th Nov 2016, 9:49 PM
Burey
Burey - avatar
+ 2
their is an ambiguity compile get confuse which path has to follow 1. D-> B ->A::dis () 2. D-> C-> A::dis ()
17th Nov 2016, 6:15 PM
Ajay Nagar
Ajay Nagar - avatar
+ 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.
17th Nov 2016, 6:15 PM
Rajkumar Nagar
Rajkumar Nagar - avatar
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?
17th Nov 2016, 5:55 PM
scott johnson
scott johnson - avatar
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.
17th Nov 2016, 6:03 PM
james nyle
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. :)
17th Nov 2016, 6:06 PM
james nyle
0
Even though you use .A, your object is still of class D, making it have the ambiguous path that others have mentioned.
17th Nov 2016, 6:17 PM
scott johnson
scott johnson - avatar
0
Thanks a lot everyone. All of your answers were really helpful.
18th Nov 2016, 2:53 AM
james nyle