Example of Ambiguous Virtual Functions


/************************************************************************
*

The following example shows a class that inherits from two nonvirtual bases that are derived from a virtual base class.

                                                                        *
************************************************************************/

class V
{
public:
      virtual void f() { /* ... */ };
};
class A : virtual public V
{
      void f() { /* ... */ };
};
class B : virtual public V
{
      void f() { /* ... */ };
};
class D : public B, public A { /* ... */ }; // error
void main ()
{
      D d;
      V* vptr = &d;
      vptr->f();            // which f(), A::f() or B::f()?
}

/************************************************************************
*

In class A, only A::f() will override V::f(). Similarly, in class B, only B::f() will override V::f(). However, in class D , both A::f() and B::f() will try to override V::f(). This attempt is not allowed because it is not possible to decide which function to call if a D object is referenced with a pointer to class V, as shown in the above example. Because only one function can override a virtual function, the compiler flags this situation as an error.

                                                                        *
************************************************************************/