C / C++ FAQs & Programming Resources - ProkutFAQ : SizeOfEmptyClass

HomePage Recent Changes Recently Commented Login/Register
Quick Links
Categories
Links

Why is size of empty class 1 and not zero?

This is what Bjarne Stroustrup has to say:

Size of an empty class is not zero to ensure that the addresses of two different objects will be different. For the same reason, "new" always returns pointers to distinct objects. Consider:

    class Empty { };

    void f()
    {
        Empty a, b;
        if (&a == &b) cout << "impossible: report error to compiler supplier";

        Empty* p1 = new Empty;
        Empty* p2 = new Empty;
        if (p1 == p2) cout << "impossible: report error to compiler supplier";
    }


There is an interesting rule that says that an empty base class need not be represented by a separate byte:

    struct X : Empty {
        int a;
        // ...
    };

    void f(X* p)
    {
        void* p1 = p;
        void* p2 = &p->a;
        if (p1 == p2) cout << "nice: good optimizer";
    }


This optimization is safe and can be most useful. It allows a programmer to use empty classes to represent very simple concepts without overhead. Some current compilers provide this "empty base class optimization".
 Comments [Hide comments/form]
size of an empty class can not be zero because even an empty class contain 3 functions. these are default cunstructer, default copy constucter and default distucter. if in any class no constucter or distructer is formed by the programmer then these function always ocuppy space by default but any contructer made by programmer can replace default constructer and any copy constructer can alone replace default constructer and default copy constructer.
-- ABTS-MP-dynamic-207.72.168.122.airtelbroadband.in (2007-11-12 10:58:15)
objects are just like the variables of type class theese objects size not equal to zero
-- 61.2.247.132 (2007-11-27 13:19:09)
Page was generated in 0.0635 seconds