Monday, August 14, 2006

Size of class

http://www.mathworks.com/products/demos/image/cross_correlation/imreg.htmlWhat is the size of an empty class? a class has one empty function? a class has virtual function?

1 byte
1 byte
4 bytes and remain 4 bytes if with more virtual functions (there are virtual table defined in the class object)

class T{
private:
float iMem1;
const int iMem2;
static int iMem3;
char iMem4;
};

the size will be 12 = the size of float iMem1 + size of int iMem2 + size of char iMem4. Static members are really not part of the class object. They won't be included in object's layout.

Even though char iMem4 will consume only 1 byte, 4 bytes will be allocated for it, and the remaining 3 bytes will be wasted (holes).

class C {
char c;
int int1;
int int2;
int i;
long l;
short s;
};

size is 24. int-long = 4, short=2, char = 1; padding.

class CT {
int int1;
int int2;
int i;
long l;
short s;
char c;
};

size is 20. the char is in one of the slots in the hole in the extra four bytes.

Class B {
...
int iMem1;
int iMem2;
}

Class D: public B {
...
int iMem;
} ;

size of D is 12, sizeof(D) is will also include the size of B.

The existence of virtual function(s):


Existence of virtual function(s) will add 4 bytes of virtual table pointer in the class, which will be added to size of class.

If the derived class has virtual function(s) from its base class, then this additional virtual function won't add anything to the size of the class. Virtual table pointer will be common across the class hierarchy.

class Base {
public:
...
virtual void Func1(...);
private:
int iAMem
};

class Derived : public Base {
...
virtual void Func2(...);
private:
int iBMem
};

sizeof(Base) = 8 bytes-- sizeof(int iAMem) + sizeof(vptr).

sizeof(Derived) =12 bytes-- sizeof(int iBMem) + sizeof(Derived), the existence of virtual functions in class Derived won't add anything more. Now Derived will set the vptr to its own virtual function table.

virtual inheritance


class ABase{
int iMem;
};

class BBase : public virtual ABase {
int iMem;
};

class CBase : public virtual ABase {
int iMem;
};

class ABCDerived : public BBase, public CBase {
int iMem;
};
Size of ABase : 4
Size of BBase : 12
Size of CBase : 12
Size of ABCDerived : 24

Because BBase and CBase are dervied from ABase virtually, they will also have an virtual base pointer. So, 4 bytes will be added to the size of the class (BBase and CBase). That is sizeof ABase + size of int + sizeof Virtual Base pointer.

Size of ABCDerived will be 24 (not 28 = sizeof (BBase + CBase + int member)) because it will maintain only one Virtual Base pointer (Same way of maintaining virtual table pointer).

No comments:

Post a Comment