polymorphism - C++ Polymorphic memory cost -


i have chunk 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;     } 

i'm getting little bit confused because says size of coolclass 16? how? why? pointer vtable, shouldn't size 8? size of oldclass 4 expected.

edit: i'm running linux mint 64 bit g++ 4.6.3.

you can't assume sizes of other char or unsigned char. if you're building on 64 bit platform, int still 4 bytes, size of virtual table pointer 8, , 4 bytes padding (so pointer aligned 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 pointer aligned 

as test, can try

class plainoldclass { private:   int* x_; }; 

and size 8.


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -