In-depth introduction to the C ++ virtual function table

Source: Internet
Author: User
Why do you need to understand the virtual function table?

Understanding the virtual function table provides a better understanding of the mechanism for understanding the C ++ Implementation of polymorphism and the memory layout of objects.

If you want to reprint, please indicate the author and the URL

Verify the existence of the virtual function table

(Struct and class in C ++ are actually the same)

In C ++, if a class contains virtual functions (virtual functions) or its parent class contains virtual functions, then the compiler will generate a virtual table for this class. I will use code to verify this.

First, write a class

Class

{

};

Cout <sizeof (a) <Endl;

Output result 1, that is, this class occupies 1 byte (I am not sure why it occupies 1 byte. I should design it like this. If you have any experts, please tell me why ).

Rewrite this class and add a virtual function to it.

Class

{

Public: Virtual int add (int I );

};

Cout <sizeof (a) <Endl;

Output 4.

We know that the function will not affect the class size. The function address is in another memory area.

These four bytes are pointers to the virtual function table. The Compiler adds a 32-bit pointer to a class with virtual functions, because the addressing range of the 32-bit operating system is 4 GB (the 64-bit processor value should be 64-bit and has not been verified ).

The Pointer Points to the virtual function table, which also has a piece of memory, where the addresses of all the virtual functions are stored. The memory may be as follows:

Virtual function table

Int add (INT I) Address in Class

... Other virtual function addresses

If Class A is defined as follows:

Class

{

Public:

Int I;

Virtual int add (int I );

}

So sizeof (A) = 8. Therefore, the size of the class is equal to the size of the vtable plus the size of the data member. If the class has a parent class, the size of the data member in the parent class needs to be added. For example:

Class B: public

{

Public:

Int K;

}

Cout <sizeof (B );

OUTPUT 12.

B's vtable (4 bytes) + B: K (4 bytes) + A: I (4 bytes) = 12 bytes.

Principle of Polymorphism

How is polymorphism implemented using this virtual function table? See the following code:

Struct super

{

Int data;

Virtual int add (int I) {return I ;};

Virtual string tostring () = 0;

};

Class Sub: Public super

{

Public:

String tostring ()

{

Return string ("sub class ");

}

};

 

Super * s = new sub ();

Cout <s-> tostring () <Endl;

Delete S;

Output "sub class ".

 

 

Super vtable

Super: Add address

Super: tostring address

Sub vtable

Super: Add address

Sub: tostring address

Int data;

The compiler will compile the virtual table into the above style. Pay attention to two things:

First, the virtual function table is at the beginning of all the members of the class.

Second, because sub overwrites tostring, the sub virtual function table records the tostring address of sub.

The above program super * s = new sub ();

S actually points to the memory area of the sub-class object. Therefore, when calling a method, the function address recorded in the memory is called. polymorphism is implemented in this way.

 

Access the virtual function table and manually call the virtual function

Since the virtual function table exists in the memory, there will be a way to find this memory area and then call it. Next we will use the program to illustrate this work.

 

First, let's look at a technology.

Struct s

{

Int K;

Int m;

};

S;

Int I = 5;

A. k = 5;

A. m = 4;

Cout <* (int *) & A <Endl;

Output 5.

To illustrate this program, I think it is not easy to understand the first line of statements. It will be clear to split it.

First, point the int * type to the S type.

Int * Pi = (int *) &;

Then, use the unreferenced method to view the int type data stored in this memory. In combination, * (int *) & A is in this form.

 

So we have a method to access any piece of memory in a class, so first find the address of the virtual function table!

To learn about a data type dword_ptr, which is defined as a 32-bit pointer (64-bit in 64-bit systems), we can use this pointer to find the address of the virtual function table.

Dword_ptr pvtable;

Pvtable = (dword_ptr) & sub ();

Sub () creates a temporary sub object. & sub () indicates getting the address of this object, and then forcibly converts the type to dword_ptr, as mentioned above, the virtual table is at the top of the class, so pvtable points to the virtual function table of this class.

The following code accesses such virtual functions:

(Sub *) pvtable)-> tostring ()

This technology can be used to implement dynamic calling. The specific implementation is not clear. For more information, see <excellent MFC> P19. The basic idea is to implement a structure that matches the called class, then, you can map the data type to the memory at the corresponding location.

Struct compitiblestruct

{

Dword_ptr vtable;

Int data;

};

 

Others

C ++ does not have the interface concept. Generally, pure virtual class (pure virtual class) is used to implement the interface. The following Code provides an example:

Struct iswitch

{

Virtual void on () = 0;

Virtual void off () = 0;

};

Defines an iswitch interface. According to the Java or C # language, an interface cannot be inherited from a class. Therefore, the virtual function table of this interface has no significance, microsoft invented a modifier _ declspec (novtable) for this situation ). Adding this keyword to a pure virtual class can reduce the redundant information compiled. This technology is used on the _ interface keyword, which can be seen in ATL.

 

Summary: This article introduces the virtual function table of C ++ from a simple perspective and its role in C ++. The technology in this article is summarized and tested by some books, the above Code passed the test in vs2005. Due to my limited ability, there may be errors. I hope readers can correct me.

 

References:

<Simple introduction to MFC> <excellent MFC> msdn

Original article: http://blog.csdn.net/smalllixin/article/details/1728464 #

Author: smalllixin

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.