In the following example:
class A {
public:
virtual void f() { cout << "a" << endl; }
virtual void h() { cout << "A" << endl; }
};
class s1 : public A {
public:
virtual void f() { cout << "s1" << endl; }
};
class s2 : public A {
public:
virtual void h() { cout << "s2" << endl; }
};
class GS : public s1, public s2 {
public:
};
int main()
{
s1 *q = new GS;
q->h();//no problem
GS a;
a.h();//error
}
Why does a.h(); give an ambiguity error yet q->h(); doesn't?
Doesn't *q have an instance of GS which should cause the same ambiguity problem?
Your use of multiple inheritance causes two instances of A to appear in GS. When you use S1 *q to access the GS instance, it follows the A instance associated with S1. Since S1 does not implement h(), the output of q->h() will be the implementation provided by A itself.
If you want q->h() to use the implementation provided by S2, then you need to create a diamond using virtual inheritance. Doing so will also remove the ambiguity when using a.h(), since virtual inheritance will cause only one instance of A to appear in GS.
class s1 : virtual public A {
public:
virtual void f() { cout << "s1" << endl; }
};
class s2 : virtual public A {
public:
virtual void h() { cout << "s2" << endl; }
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With