Possible Duplicate:
virtual function default arguments behaviour
class Human{ virtual void print(int height =72){ cout << "Human: " << height << endl; }};
class Child:public Human{ void print(int height =48){ cout << "Child: " << height << endl; }};
int main()
{
Human * brother = new Child();
brother->print();
}
Result is this
Child: 72
Why it gets default parameter from base class and function definition from derived class? Expecting an explanation associated with C++ standers.
The parameters passed to a function are decided by the code that calls the function. The behavior of the function, once called, is up to the class. If you need this behavior, create a virtual function that takes no parameters.
Getting the default parameter of the derived function would be impossible because the calling code can’t even necessarily see the prototype for that function.
Consider:
This code may have no idea there exists a class derived from
Humanthat has aprintfunction with a default value of 48. And, in any event, it would have no way to know to actually pass that value.Long after this code is compiled, it might get linked to code like this:
See 8.3.6.10: