sizeof(class) question
-
Hi, i've got this class template class pointer { private: T *p; }; and i get 4 if i do sizeof(pointer). if i add a static member data, it doesn;t count. why is it that? is it because there's only one copy of that atribute for all the instances of the class? then, if i add a virtual function (or 2, or 3), i get 8 if i do sizeof(pointer). why is that? thanks for your help!
-
Hi, i've got this class template class pointer { private: T *p; }; and i get 4 if i do sizeof(pointer). if i add a static member data, it doesn;t count. why is it that? is it because there's only one copy of that atribute for all the instances of the class? then, if i add a virtual function (or 2, or 3), i get 8 if i do sizeof(pointer). why is that? thanks for your help!
Adding a static member does not affect the size because a static member does not exist in an object (instantiation) of the class. The memory for the static member is allocated in ONE place, not for each object. The reason that the size increases when you add a virtual method, is that the object needs a pointer to the VTable. This is a table of pointers, one for each virtual method. This table is specific to your class. Each object of the class will contain a pointer to this VTable. The size of this pointer is 4 bytes.
-
Adding a static member does not affect the size because a static member does not exist in an object (instantiation) of the class. The memory for the static member is allocated in ONE place, not for each object. The reason that the size increases when you add a virtual method, is that the object needs a pointer to the VTable. This is a table of pointers, one for each virtual method. This table is specific to your class. Each object of the class will contain a pointer to this VTable. The size of this pointer is 4 bytes.