Vptr, vtable, virtual base class table

Source: Internet
Author: User

 
# Include <iostream> using namespace STD; Class X {int x, y, z ;}; class Y: Public Virtual X {}; Class Z: public Virtual X {virtual void F () {}}; Class A: Public y, public Z {}; int main () {A * P; cout <"pointer: "<sizeof (p) <Endl; cout <" int: "<sizeof (INT) <Endl; cout <" X: "<sizeof (x) <Endl; cout <" Y: "<sizeof (y) <Endl; cout <" Z: "<sizeof (z) <Endl; cout <" A: "<sizeof (a) <Endl ;}

The output of the above Code on 64-bit Linux is as follows: (G ++)

The output on 32-bit windows is: (vs2013)

The parsing in Linux is as follows:

The output of X is 3*4 = 12. No problem.

If 'y' is inherited from 'x', 'y' will have a vptr, where the pointer occupies 8 bytes. In addition, because Y is a null class, the compiler automatically adds a byte. Add three bytes with the upper boundary alignment. Therefore, 8 + 3*4 + 1 + 3 = 24.

Z is the same as Y.

A inherits multiple values from Y and Z. There are two vptr. In addition, A is an empty class, so the compiler automatically adds a byte. Add three bytes with the upper boundary alignment. Therefore, 8 + 8 + 3*4 + 1 + 3 = 32.

 

 

The parsing in Windows is as follows:

The key is Y, Z, and.

Y is similar to Y in Linux. However, vs does not generate a byte for the empty class. Therefore, 3*4 + 4 = 16.

In the Z, vs compiler, virtual base class table and virtual function table are separated, because there are both virtual base classes and virtual functions, therefore, virtual function table pointers and virtual base class Table pointers are required. Therefore, 3*4 + 4 + 4 = 20.

A multiple inheritance, 3*4 + 4 + (4 + 4) = 24.

Vptr, vtable, virtual base class table

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.