Remember before a colleague spit the slot in Java there is no default parameter this thing, want to achieve the purpose of the default parameters can only rely on crappy function overloading. But today we found a pit of default parameters in C + +.
The virtual functions in C + + are dynamically bound, while the default values are statically bound.
For example:
Class shape{
Public
Virturl void Draw (Color c = red) const = 0;
}
Class Circle:public shape{
Public
Virturl void Draw (Color c = green) const;
}
sharp* PS;
sharp* pc = new Circle;
The static type of the PC is sharp, and the dynamic type is circle.
Due to the dynamic binding technology, the PC can find its own virtual function through the virtual table, and C + + for efficiency reasons and let the default value of static binding, so when the PC call draw when the default parameter is red, this must be a very difficult to find a bug
If they all have the same default parameters, then the code repeats, and the better solution is to:
Class shape{
Public
void Draw (Color c = red) const{
OnDraw (c);
}
Private
virtual void Draw (Color c) const;
}
Class Circle:public shape{
Private
virtual void Draw (Color c) const;
};
So the only thing we should overwrite is the virtual function, so we should define the statically bound thing (the default parameter) in the Non-virtual function.
Effective C + + 37 never redefine inherited default parameter values