Size calculation for C + + classes

Source: Internet
Author: User

CLASS&NBSP;A{};CLASS&NBSP;B{CHAR&NBSP;CH;VIRTUAL&NBSP;VOID&NBSP;FUNC0 ()   {  }};class  C{char ch1;char ch2;virtual void func ()   {  }virtual void  Func1 ()   {  }};class D : public A, public C{int d; Virtual void func ()   {  }virtual void func1 ()   {   }};CLASS&NBSP;E&NBSP;:&NBSP;PUBLIC&NBSP;B,&NBSP;PUBLIC&NBSP;C{PUBLIC:INT&NBSP;E;VIRTUAL&NBSP;VOID&NBSP;FUNC0 () &NBSP;&NBSP;{&NBSP;&NBSP;}VIRTUAL&NBSP;VOID&NBSP;FUNC1 ()   {  }//Subclass (E) does not implement Func (), So in the subclass of E, the vfptr of B points to the Func () and E's func1 () virtual void func123 () of C ()   {  }}int main () {         //result=1, empty class, size 1         cout <<  "A="  << sizeof (A)  << endl;                 //result=8,4 (vfptr,4) +4 (char ch, memory alignment, 4)  = 8        cout <<  "b="  << sizeof (B)  <<  endl;   //result=8 , 4 (vfptr,4) +4 (CHAR&NBSP;CH1,CHAR&NBSP;CH2, memory alignment, 4)  =  8  cout <<  "c="  << sizeof (C)  << endl;     //result=12, 4 (vfptr,4 of Class D) +4 (existence of base class CHAR&NBSP;CH1,CHAR&NBSP;CH2, memory Alignment, 4) +4 (int d)  = 12d obj_d; //the address of the two virtual functions in Class D is saved first in the virtual function table that vptr points to cout <<  "d="  <<  sizeof (Obj_d)  << endl;    //result=20, (multiple inheritance) inherits the number of classes with virtual functions, there are many virtual function pointers, That is, these virtual function pointers make up their own vfptr (the compiler no longer gives its own virtual function plug vfptr)//4 (b's Vfptr) +4 (char ch) +4 (Vfptr of C) +4 (c  char ch1, CHAR&NBSP;CH2) +4 (e  in int d)  = 20//This can be seen from the debug e obj_e;obj_e.e = 123;cout  <<  "E="  <&Lt; sizeof (obj_e)  << endl;             return 0;}


Size calculation for C + + classes

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.