Exposure to C ++: truth about virtual functions (how does the VC compiler implement the "virtual" rule)

Source: Internet
Author: User

Download Full-text http://download.csdn.net/detail/Dreamcode/201005 from csdn download center

(1) virtual functions

 

Let's take a look at a simple piece of code:

Code segment:

Line01: # include <stdio. h>

Line02:

Line03: class base {

Line04: public:

Line05: Virtual void _ stdcall output (){

Line06: printf ("class base \ n ");

Line07 :}

Line08 :};

Line09:

Line10: Class derive: public base {

Line11: public:

Line12: void _ stdcall output (){

Line13: printf ("class derive \ n ");

Line14 :}

Line15 :};

Line16:

Line17: void test (base * P ){

Line18: p-> output ();

Line19 :}

Line20:

Line21: int _ cdecl main (intargc, char * argv []) {

Line22: derive OBJ;

Line23: Test (& OBJ );

Line24: Return 0;

Line25 :}

 

The "output" function of the base class is a virtual function. Obviously, the program running result will be:

 

(2) virtual function table

First, we will analyze the object OBJ of the derive class in our main function to see its memory layout. Since there is no data member, its size is 4 bytes and there is only one vfptr, so the OBJ address is the vfptr address.

For a C ++ class, if it is to present polymorphism (the General compiler will take this class and whether its base class contains the virtual keyword as the class to be polymorphism ), the class will have a virtual function table, and each instance (object) will have a virtual function pointer (vfptr) pointing to the starting address of the virtual function table of this class, the content of the memory unit corresponding to the virtual function table address is the virtual function address (in fact, it is not the real function address, but the address of the JMP Instruction of the function ).

(2) Implement Virtual Functions

 

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.