Question

In the next code, I get ambiguous error when calling D::f in _tmain(..) since B::f overrides A::f, the pointer to f in A::vtable points to B::f.

1) Why the compiler then gives ambiguous error? could someone please clear that?

2) I tried to overload A::f(int) by changing B::f(int) to be B::f(char) but the error didn't disappear! why is that?

The inheritance diagram:

............A......
........../.|.\....
........A1..B..C...
..........\.|./....
............D......

The code:

struct A { 

 virtual void f(int x) {cout << "A::f";}; 
 virtual void g(int x) {cout << "A::g";}; 
 private: int n; 
}; 
struct A1: A { 
 virtual void h(int x) {f(x);}; 
}; 
struct B : virtual A { 
 void f(int x) {cout << "B::f";}; 
}; 
struct C : virtual A { 
 void g(int x) {cout << "C::g";}; 
}; 
struct D : A1, B , C { 

};
int _tmain(int argc, _TCHAR* argv[])
{
    D* d = new D();
    d->f(1);
    return 0;
}
Was it helpful?

Solution

You need to change your inheritance definition for struct A1:

struct A1: virtual A {

The reason, diamond inheritance ambiguity. struct D is getting the method f() from both A1 and B. To inherit it only once, all qualifying classes must inherit the method virtually.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top