Valid C ++ clause 37 and valid clause 37

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.