2012-02-27

C++ Structure and Class size

C++中,同样数据成员的struct和class的大小(sizeof)是相同的。带有成员函数的class并不增加大小,但是带有virtual函数的class会增加4 bytes。

===== Test Pprogram ===

#include <iostream>

using namespace std;

struct S {
        int     a;
        int     b;
};

class C {
public:
        int     a;
        int             b;
};

class CF {
public:
        int             a;
        int             b;

        void f1() {};
        void f2() {};
        void f3() {};
};


class CVF {
public:
        int             a;
        int             b;

        virtual void f1() {};
        virtual void f2() {};
        virtual void f3() {};
};

int main(int argc, char** argv)
{
        cout << "Size of struct S " << sizeof(struct S) << endl;
        cout << "Size of class C " << sizeof(C) << endl;
        cout << "Size of class CF " << sizeof(CF) << endl;
        cout << "Size of class CVF " << sizeof(CVF) << endl;

        return 0;
}

==== Result ====

Size of struct S 8
Size of class C 8
Size of class CF 8
Size of class CVF 12