1

Have a look at these 2 cases:

class A {
    public:
    int a;

    A () { a = 10;}
    void foo () {std::cout << "a = " << a << std::endl;}
};

Here sizeof(A) gives 4 bytes, which makes sense.

class A {
    public:
    int a;

    A () { a = 10;}
    virtual void foo () {std::cout << "a = " << a << std::endl;}
};

Here sizeof(A) gives 16 bytes as opposed to 12 bytes (4 + 8 for pointer).

Is there any explanation in terms of memory alignment for this ?

shrinidhisondur
  • 771
  • 1
  • 8
  • 18

2 Answers2

1

It's up to the compiler how virtual functions are implemented, but what's likely happening here is it wants/needs to align the 8-byte pointer to the virtual dispatch table on a multiple-of-8 memory address. Then there's either { 4 bytes a, 4 padding, 8 vdt pointer } or { 8 vdt pointer, 4 bytes a, 4 padding } - the latter's less obvious, but consider that arrays of A need to be contiguous and spaced per sizeof(A), so 12's rounded up to 16 given the 8-byte alignment.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
0

FIRST in virtual dispatch table, visual functions need a pointer size , in 32 bits computer, the size of pointer is 4 bytes, int 64 bits it's 8 bytes. so I think your computer is 64 bits.

SECOND the sizeof(A) should consider the padding and memory alignment . so 16 bytes is arranged like that: 4 bytes(int a) + 8 bytes(a virtual function pointer int 64 bits) + 4 bytes padding(because the max size of elements in A is the virtual function pointer which is 8 bytes, so the sizeof(A)should be the integral multiples of 8 bytes )