Valid C ++ clause 37 and valid clause 37
Do not repeatedly define the default values of parameters in the virtual function. If the default values are repeated, the Program Calling process may exceed common sense.
You can see the following code:
# Include <iostream> using namespace std; class Shape {public: enum ShapeColor {Red, Green, Blue}; virtual void Drew (ShapeColor color = Red) {if (color = Red) cout <"Red" <endl; else if (color = Blue) cout <"Blue" <endl; else cout <"Green" <endl ;}}; class Rectangle: public Shape {public: virtual void Drew (ShapeColor = Green) {if (color = Red) cout <"Red" <endl; else if (color = Blue) Cout <"Blue" <endl; else cout <"Green" <endl ;}; int main () {Shape * s = new Rectangle (); s-> Drew (); // call the result to print Red instead of Green. Return 0 ;}
We must be troubled by unexpected results, and cannot figure out why this phenomenon occurs. Here I will give a simple explanation. First, you must understand the differences between static binding and dynamic binding.
Our virtual function is a dynamic binding call process, and its call decision makers are actually directed to objects. The default value in our function is static binding, and its decision maker is the currently called object type.
Let's take a look at the example above. The s pointer is of the shape class and actually points to the Rectangle Class Object. When the Drew function is called, The Drew function in the Rectangle class is called because the Drew function is a virtual function, however, the default value of the selected function parameter is the Shape class.