Calling virtual functions in member functions (Considerations for polymorphism)------New standard C + + programming

Source: Internet
Author: User

The member functions of the class can be called each other. Statements that call other virtual member functions in addition to member functions (except static member functions, constructors, and destructors) are polymorphic. For example:

#include <iostream>using namespace Std;class cbase{public:void func1 () {Func2 ();} virtual void Func2 () {cout<< "Cbase::func2 ()" <<endl;}}; Class cderived:public cbase{public:virtual void Func2 () {cout<< "Cderiver::func2 ()" <<endl;}}; int main () {cderived d;d.func1 (); return 0;}

Output:

CDERIVER::FUNC2 ()

Line 20th calls the FUNC1 member function. Enter the FUNC1 member function, execute to line 8th, and call the FUNC2 function. It looks like the FUNC2 member function of the CBase class should be called, but the output proves that the FUNC2 member function of the CDerived class is actually being called. This is because, in the FUNC1 function, "Func2 ();" Equivalent to "THIS->FUNC2 ();", and the this pointer is obviously a cbase* type, which is a base class pointer, then "THIS->FUNC2 ();" is to call a virtual function from a base class pointer, so this function call statement is polymorphic. When the program executes to line 8th, the this pointer points to an object of the Cderivrd class, which is D, and is called the FUNC2 member function of the CDerived class.

New standard C + + programming

Calling virtual functions in member functions (Considerations for polymorphism)------New standard C + + programming

Related Article

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.