I was reading about diamond inheritance problem in java . So wanted to know how other languages have solved and found that c++ has solved it . And I found this How does virtual inheritance solve the "diamond" (multiple inheritance) ambiguity? . Then I tried this code in online c++ compiler . I tried
#include <iostream>
using namespace std;
class A { public: void eat(){ cout<<"A";} };
class B: virtual public A { public: void eat(){ cout<<"B";} };
class C: virtual public A { public: void eat(){ cout<<"C";} };
class D: public B,C { public: void eat(){ cout<<"D";} };
int main()
{
A *a = new D();
a->eat();
}
It worked . Then I wanted to invoke B's eat and changed A *a = new D(); to
B *a = new D();
and this too worked .But when I tried
C *a = new D();
It threw and error
error: 'C' is an inaccessible base of 'D' C *a = new D();
Why with C alone this error ? It is even public . Then why its not accessible ?
So what I did was I changed the order of inheritance to
class D: public C,B { public: void eat(){ cout<<"D";} };
And now C *a = new D(); passed but B *a = new D(); failed .
Why is it so ?
Is the order important ?
When I googled I found this stackoverflow link , but found that it is for constructors . I could not understand why this case fails .
Please forgive if my question is stupid , as I am damn new to C++ .I am used to only java where there is no multiple inheritance .
D
inherits publicly from B
, but privately from C
. Use this if you want to inherit publicly from both:
class D: public B, public C { public: void eat(){ cout<<"D";} };
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.