C++ Study Note(1): Size matters

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:

Let’s try an example:

```c++ #include 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 ```