Tuesday, November 1, 2011

Size of Class Objects

Some notes about how to determine the size of class objects in C++.

  1. The keyword sizeof can work on both class type names and class objects.
  2. Static member data don't contribute to the size of class (they are classwide available)
  3. Member functions don't really contribute to the size of class (except the vtable for virtual functions).
  4. The this pointer doesn't contribute to the size of class objects.
  5. Friends and pointers to members are not class members at all, and hence they won't contribute to the class size.
  6. It is unspecified whether or not a reference requires storage. It may be compiler specific.
  7. The actual size is most likely greater than the sum of sizes for each non-static member data and virtual pointers. This is because of byte alignment or padding, and depends on the compiler.
  8. Virtual pointer will take some space if there are virtual functions or virtual inheritance in the class.
  9. Empty classes won't be size 0 in order to distinguish the objects of that class type. By most compilers, their size will be 1.
  10. Empty sub-objects will take no space in memory when an empty class is inherited by a non-empty class type.
  11. Regular inheritance will make the size of derived class the sum of all non-static member sizes from its base classes.
  12. The _vptr field is always an alias of the first available _vptr of its base classes, if there are some. Otherwise, the class itself will create a new _vptr if necessary.
  13. The virtual inheritance is kind of complex. It's designed to solve the diamond problem in inheritance, and there will be only 1 copy for the common ancestor members. Simply speaking, the class will first create the non-virtual base class members, and its own members in class body, and finally a unique set of members from virtual base classes (including immediate virtual base and inherited virtual base).

References:
C Programming
C++ FAQ
Wikipedia: Reference
Wikipedia: Virtual Inheritance

No comments:

Post a Comment