Question

The answer to the below output of main is "derived class display with i=10", but I do not understand why? Surely the function was invoked on the base type?

What is the thought-process in determining the answer here?

class base
{
  public:
         virtual void display(int i = 10)
         {
           cout<<"Base class display with i = "<<i<<endl;
         }

};

class derived : public base
{
  public:
          void display(int i = 20)
         {
           cout<<"Derived class display with i = "<< i <<endl;
         }

};

int main(int argc, char *argv[])
{
     base *bptr = new derived;
     bptr->display();

      return 0;
}
Was it helpful?

Solution

Have a look at Can virtual functions have default parameters?:

A virtual function call (10.3) uses the default arguments in the declaration of the virtual function determined by the static type of the pointer or reference denoting the object. An overriding function in a derived class does not acquire default arguments from the function it overrides.

Therefore, bptr->display(); calls the derived version of display, but uses the argument from base, the static type of the pointer bptr.

This is because the default value of an argument has to be determined at compile time while dynamic binding is deferred to the runtime. Using different default arguments in the base and derived versions of the same virtual is almost guaranteed to cause trouble. Problems are likely to arise when the virtual is called through a reference or pointer to base, but the version that is executed is the one defined by the derived. In such cases, the default argument defined for the base version of the virtual will be passed to the derived version, which was defined using a different default argument.

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