Ambiguous Virtual Function Calls

It is an error to override one virtual function with two or more ambiguous virtual functions. This can happen in a derived class that inherits from two nonvirtual bases that are derived from a virtual base class.

A special case occurs when the ambiguous overriding virtual functions come from separate instances of the same class type. In the following example, there are two objects (instances) of class L. There are two data members L::count, one in class A and one in class B. If the declaration of class D is allowed, incrementing L:: count in a call to L::f() with a pointer to class V is ambiguous.

class V
{
public:
      virtual void f();
};
class L : virtual public V
{
      int count;
      void f();
};
void L::f() {++count;}
class A : public L
{ /* ... */ };
class B : public L
{ /* ... */ };
class D : public A, public B { /* ... */ }; // error
void main ()
{
      D d;
      V* vptr = &d;
      vptr->f();
}

In the above example, the function L::f() is expecting a pointer to an L object; that is, the this pointer for class L, as its first implicit argument. Because there are two objects of class L in a D object, there are two this pointers that could be passed to L::f(). Because the compiler cannot decide which this pointer to pass to L::f(), the declaration of class D is flagged as an error.



Example of Ambiguous Virtual Functions


Virtual Functions
Virtual Function Access
Multiple Access
Scope Resolution Operator
Member Functions
The This Pointer