[00000]-[2015-06-22]-[00]-[c++ virtual function]

Source: Internet
Author: User

The polymorphism of C + + language is related to the virtual function of C + + class

Introduce a problem: Define a pointer to a base class, point to a derived class object, and then invoke the corresponding method based on the pointer, what effect does it have?

Class CBase

{

Public

virtual void Vfun ()

{

cout<< "Vfun from base class" <<endl;

}

void Fun ()

{

cout<< "Fun from base class" <<endl;

}

};

Class Cderive:public CBase

{

Public

virtual void Vfun ()

{

cout<< "Vfun from derive class" <<endl;

}

void Fun ()

{

cout<< "Fun from derive class" <<endl;

}

};

Cbase* pbase;

CBase Base;

Cderive derive;

"1" If PBase = &derive;

Pbase->vfun ();

Pbase->fun ();

Output results

Vfun from derive class

Fun from derive class

Virtual functions are overloaded in derived classes and pointers point to derived class objects

"2" If pbase is only defined, but not initialized;

Pbase->vfun ();

Pbase->fun ();

Outputs the corresponding function in the base class to process the result

To call a base class pointer to a function method of a derived class, either let PBase point to the derived class object, or type display cast (cderive*) pbase for pbase;

(cderive*) Pbase->vfun ();

(cderive*) Pbase->fun ();

For each class that has a virtual function inside it, the compiler generates a virtual function table for it (vtable), and each element in the table points to the address of a virtual function, and the compiler generates a member variable-----the virtual function table pointer (VPTR) to the virtual function table, which is inherited ...

[00000]-[2015-06-22]-[00]-[c++ 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.