Object Layout in C + +

Source: Internet
Author: User

When a virtual table is involved in C + +, the layout of the class object is divided into: virtual table and data member, subclass contains derived class layout, assume the following program:

1#include <iostream>2 3 using namespacestd;4 5 classB {6 Private:7     intA;8  Public:9 B () {TenA = One; One     } A  -     Virtual voidFun () { -cout <<"B::fun"<<Endl; the     } - }; -  - classA: PublicB { +  Public: - A () { +cout <<"class A Constructor"<<Endl;  Am =3; atn =2; -     } -  -~A () { -cout <<"~a ()"<<Endl; -     } in     Virtual voidFun () { -cout <<"A::fun"<<Endl; to     } +  - Private: the     intM,n; * }; $ Panax Notoginseng intMainintargcChar*argv[]) - { the A; +     int*p; Atypedefvoid(*pf_t) (void); the      + pf_t PF; -p = static_cast<int*> ((int*) &a); $PF =(pf_t) p; $      -     int*vptr = * (int* *) &A; -     int*vtable = (int*)*vptr; thePF = (pf_t) vtable[2]; - Wuyiprintf"address A::fun%p\n", pf); the  -cout <<"P:"<< *p <<Endl; WuP + + ; -cout <<"P:"<< *p <<Endl; Aboutp++; $cout <<"P:"<< *p <<Endl; -p++; -cout <<"P:"<< *p <<Endl; -          Ap++; +cout <<"P:"<< *p <<Endl; the  -  $     return 0; the}

With the VS 2010 Display Object Layout diagram (cl-d1reportallclasslayout), where meta is the type information for the corresponding object:

Class B:

1 class B    Size (8):  2     +--- 3  0    |  {VFPTR} 4  4    | a 5     +--- 6  7b::[email protected]:  8     | &B_meta  9      |  0 Ten  0    | &b::fun

Class A:

 class  A size (16  ):    +---    | +---(base  class   B)  0  | |  {vfptr}  4  | |  a  | +---8  |  M  12  |  n  +---a::[email protected]:  |  &a_meta  | 0  0  | &a::funa::fun  0  

Object Layout in C + +

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.