Some ambiguous virtual function calls ~ Part1

In this article I will be discussing one funny virtual function call.Consider the below code snippet:-

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

 

When you try to compile the above code snippet you will get the following error dumps.

error C2250: ‘D’ : ambiguous inheritance of ‘A::A::f’
error C2250: ‘D’ : ambiguous inheritance of ‘B::B::f’

Let’s analyze this scenario a bit deeper. What I have done is I created a derived class (D) that inherits from two non virtual bases (A,B) that are derived from a virtual base class(V).

     V
    / \
  /     \
A        B
   \     /
     \ /
      D

In short its forms a deadly beautiful diamond with Class V at the top which has a Virtual function f() with two branches formed by class A and B. Both of these classes overrides the virtual function f().Do note that in class A and B the over ridden virtual functions are non virtual. Now Class D inherits class A and B. The issue is when f() is called by an object of D will it call the F() implemented by B(D::B::f)or the one implemented by C(D::C::f).Moral of the story - Never try this :D !

Related Reading:-

2 Responses to “Some ambiguous virtual function calls ~ Part1”


  1. 1 Rob Will July 20, 2007 at 4:01 pm

    You exp a lot these days ;)

  1. 1 Virtual Inline functions… « Stream Trackback on July 13, 2007 at 7:10 pm

Leave a Reply




 

July 2007
S M T W T F S
« Jun   Aug »
1234567
891011121314
15161718192021
22232425262728
293031  

Categories

Blog Stats

  • 29,660 hits

Last 100 Visitors

Map IP Address

Map IP Address