Default real parameters of C ++ virtual functions

Source: Internet
Author: User

One question:

 

 
# Include <iostream> using namespace STD; Class A1 {public: Virtual int F (INT n = 5) {return 2 * n ;}}; Class B: Public A1 {public: int F (INT n = 10) {return 3 * n ;}}; int main () {A1 * P = new B (); cout <p-> F () <Endl; return 0 ;}

 

The output result is 15.

Result Analysis:

1,BFunctions inInt F (INT)It is also a virtual function.(Similar to the function prototype of the base class)So the pointer call is dynamic binding, that is, what is actually called here isBInF (INT).

2The default real parameters of the virtual function are determined by the type of the function called, and are not related to the dynamic type. The base class pointer is called here, so the real parameter is the default real parameter in the base class.5.

 

 

About dynamic binding:

1. It must be called by pointer or reference;

2. It must be a virtual function.

Both conditions must be met at the same time.

 

The function in the derived class must be exactly the same as the prototype of the virtual function of the base class: The function name, the parameter list is exactly the same, and the keyword virtual can be dispensable.

If the function prototype is not exactly the same, it will be a new function. At this time, the new function will overwrite the inherited virtual function.

 

 

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.