Question

I am learning about virtual functions and virtual tables in C++. But, I could not understand why there is a need for dynamic binding. Doesn't the compiler have all the information to figure out if the function call is for the derived or the base function, for example here:

class Base1 { 
   public : virtual void foo() 
            {  cout << " Base foo \n"; } 
};

class Base2 {
   public : virtual void foo() 
           { cout << " Base2 foo \n"; } 
};

class derived : public base1, base 2 {
     public : virtual void foo() 
       { cout << " derived foo \n"; }
}

int main()
{
  derived d;
  Base2 *p = &d;
  p->foo();       // why can't the compiler figure out that this
                  // is a function call to the derived function
                  // foo at compile time?

  return 0;
}
Was it helpful?

Solution

why cant compile figure that this is a function call to derived function foo during compile runtime itself?

It can. And some compilers will convert that call to static binding.

And there are other scenarios when the compiler must use dynamic binding.

Which foo() should get called in this function?

void function( Base* p )
{
  p->foo();
}

It can't be determined*. Dynamic binding must be used.

*Edit: Based on the information I've given. :)

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