C ++ Polymorphic memory

I have this piece of 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(void) {
      printf("CoolClass size: %ld\n", sizeof(CoolClass));
      printf("PlainOldClass size: %ld\n", sizeof(PlainOldClass));
      return 0;
    }

Am I a little confused because it says CoolClass size is 16? How? What for? Even with a pointer to vtable, the size should not be 8? The size of the old class is 4, as expected.

edit: I am running Linux Mint 64 bit with g ++ 4.6.3.

+5
source share
4 answers

You cannot assume anything about the sizes of anything other than charor unsigned char. If you are building on a 64-bit platform, there intare likely to be 4 more bytes, but the size of the virtual table pointer will probably be 8, and an additional 4 bytes to fill in (so the pointer is aligned to 8 bytes).

64 bit

+----+----+----+----+
| vp | vp | x_ | p  |
+----+----+----+----+

vp - virtual table pointer
x_ - member
p  - padding byte

32 bit

+----+----+
| vp | x_ |
+----+----+

vp - virtual table pointer
x_ - member
p  - padding byte

Padding not required because the pointer is already aligned

As a test, you can try

class PlainOldClass {
private:
  int* x_;
};

and its size will be 8.

+5

, 64- . 8 , , 4 int ( 64- 8 , , sizeof (PlainOldClass) 4, ) 4, 64- , , - 16 .

+4

, :

  • 64- , 8
  • 4 int ( 8 )
  • 4, 64- ,

sum = 16 .

+2

, 64- , - ,

  • 8 vptr.
  • 4 int
  • and an extra 4 bytes to give 64-bit alignment to the pointer.

therefore, the sum becomes 16.

+1
source

All Articles