C++ Study Note(1): Size matters

cpp

C++ is so versatile that most likely the application runs with design flaws. Before we dive into this wonderful language, let me summarize overlooked tricks and pitfalls for you, all test cases are compiled and run in gcc (GCC) 4.1.1 (Gentoo 4.1.1-r3)

These are rules-of thumb for the object size:

  • The size of the empty object is minimum 1 instead of 0.
  • Static member does not consume space.
  • Objects with virtual function would pay the price for vtable, aka 4 bytes[1], the good news is this is fixed price.
  • Size of derived object is the sum of base objects.

Let’s try an example:

#include <iostream>
using namespace std;

class Base {};

class StaticBase
{
public:
    static int foo;
};

class BaseWithVTable
{
public:
    virtual ~BaseWithVTable() {};
    virtual void bar() {};
};

class Derived : public BaseWithVTable
{
public:
    virtual ~Derived() {};
    void foo() {};
    int bar;
};

class MoreDerived: public Derived , public StaticBase
{
private:
    int hello;
};

int main()
{
    cout << "sizeof(Base) = " << sizeof(Base) << endl;
    cout << "sizeof(StaticBase) = " << sizeof(StaticBase) << endl;
    cout << "sizeof(BaseWithVTable) = " << sizeof(BaseWithVTable) << endl;
    cout << "sizeof(Derived) = " << sizeof(Derived)  << endl;
    cout << "sizeof(MoreDerived) = " << sizeof(MoreDerived)  << endl;
}

The output is:

sizeof(Base) = 1
sizeof(StaticBase) = 1
sizeof(BaseWithVTable) = 4
sizeof(Derived) = 8
sizeof(MoreDerived) = 12