Reputation: 57
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!
Upvotes: 0
Views: 57
Reputation: 206717
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.
Upvotes: 2
Reputation: 56577
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.
Upvotes: 3