I basically copied this example from Item 21. Overriding Virtual Functions
in Herb Sutter's book Exceptional C++
.
#include <iostream>
class Base {
public:
virtual void f(int i = 10) { std::cout << i << '\n'; }
};
class Derived : public Base {
public:
void f(int i = 20) { std::cout << i << '\n'; }
};
int main()
{
Base* p = new Derived;
p->f();
}
Surprisingly (for me at least) the code prints 10 (not 20) and the author explains this with the following words in page 122: The thing to remember is that, like overloads, default parameters are taken from the static type (here Base) of the object, hence the default value of 10 is taken. However, the function happens to be virtual, so the function actually called is based on the dynamic type (here Derived) of the object.
Is there any quote in the C++11 Standard supporting this?