I have these classes:
class Base
{
public:
virtual void foo(int x = 0)
{
printf("X = %d", x);
}
};
class Derived : public Base
{
public:
virtual void foo(int x = 1)
{
printf("X = %d", x);
}
};
When I have:
Base* bar = new Derived();
bar->foo();
My output is “X = 0”, even if foo is called from Derived, but when I have:
Derived* bar = new Derived();
bar->foo();
My output is “X = 1”. Is this behavior correct? (To select default parameter value from the declaration type, instead of selecting it from actual object type). Does this break C++ polymorphism?
It can cause many problems if somebody uses virtual functions without specifying the actual function parameter and uses the function’s default parameter.
Default arguments are retained even if you override a function! And this behaviour is correct. Let me search the reference from the C++ Standard.
§8.3.6/10 [Default arguments] from the C++ Standard says,
The example from the Standard itself
Also, not only it’s retained, it is evaluated everytime the function is called:
§8.3.6/9 says,