简体   繁体   中英

Difference sizeof in C++ Classes with virtual parameter

I have this code:

#include <stdio.h>

class CoolClass
{
   public:
      virtual void set(int x){x_=x;};
      virtual int get(){return x_;};

   private:
      int x_;
};

class PlainOldClass
{
   public:
      void set(int x){x_=x;};
      int get(){return x_;};

   private:
      int x_;
};

int main ()
{
   printf("CoolClass:\t %ld \nPlainOldClass:\t %ld \n",
          sizeof(CoolClass),sizeof(PlainOldClass)); 

   return 0;
}

And the output is:

CoolClass:   16 
PlainOldClass:   4 

and I would like to know why this happen, I tried to find some information about virtual, but I dont understand it.

Thank you very much!

This happens because classes that have virtual functions are usually implemented by the compiler via a virtual table , see also this explanation . And to use such virtual table, they store internally a pointer to the table. In your case, the size of CoolClass is given by the size of the int member (usually 4 bytes), plus the size of the pointer (usually 4 or 8 bytes, depending on the architecture: 32 bit vs 64 bit). You see 16 due to padding.

When you add a virtual member function, the compiler allocates space to hold a pointer to a virtual table. In your case, the size of a pointer looks to be 8. To keep the alignment of the objects at 8 bytes, the compiler adds 4 bytes of padding to the object, which total up to 16 bytes.

Had the compiler not added the padding, sizeof(CoolClass) would have been 12.

For the second class, the size is obvious.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM