0

the below is my test code, i think it will output "Der:12", but the result is "Der:11", any one can tell me why output this, and where is the default argument store?

#include <stdio.h>
class Base{
public:
    virtual void show(int i = 11) 
    {   
        printf("Base:%d\n", i); 
    }   
};

class Der : public Base{
public:
    virtual void show(int i = 12) 
    {   
        printf("Der:%d\n", i); 
    }   
};

int main()
{
   Base *p = new Der();
   p->show();

   return 0;
}
good90
  • 41
  • 2
  • 7
  • Also here... [Can virtual functions have default parameters?](http://stackoverflow.com/questions/3533589/can-virtual-functions-have-default-parameters) – godel9 Jan 21 '14 at 05:32

1 Answers1

0

Hmmm, I'm not sure it's actually valid to override a virtual function with a different default parameter, and it's certainly not sensible. But on the other hand, the compiler is doing the right thing, even if it's contrary to your expectations.

Base *p;
p->show();

What happens here is that the compiler looks into Base for a function taking no arguments. There isn't one, but it finds the one-argument function and calls show(int) with the default parameter of 11.

But the function is virtual, and so because p's dynamic type is Der, it's Der::show(int) that actually gets called -- but crucially, still with Base's default argument of 11, but the default argument is looked up statically, not using run-time dispatch.

I haven't tried it, but I'd imagine if you said

Der *p = new Der();
p->show();

you'd get 12 output instead.

Tristan Brindle
  • 16,281
  • 4
  • 39
  • 82