Effective C + + 37 never redefine inherited default parameter values

Source: Internet
Author: User

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

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.