user1089867
user1089867

Reputation: 11

Why the size of a class is getting increased by 1 if I inherit more than 2 classes in C++

In the following code snippet, If I inherit the first 2 classes the size of derived class is 1, from omwards if inherit more number of classes to derived the size of derived class is getting incresed by those many number of classes. Why?

// Remove the comment one by one at derived class (//Base1, //Base2//, Base3//, Base5, //Base6) and check.

struct Base {
    Base(){}
};
struct Base1 {
    Base1(){}
};
struct Base2 {
    Base2(){}
};
struct Base3 {
    Base3(){}
};
struct Base5 {
    Base5(){}
};
struct Base6 {
    Base6(){}
};
struct Derived : Base, Base1, Base2//, Base3//, Base5, //Base6
{
public:
    Derived(){}     
};

int main() {
    Derived der;
    cout << "Sizeof der: " << sizeof(der) << endl;
}

Upvotes: 0

Views: 128

Answers (2)

Petr
Petr

Reputation: 1148

Every time you extend a class it becomes a part of the final object and therefore increases its size by the size of the base class object. As already mentioned there may be some compiler optimizations going on that cause the observed effect.

Upvotes: -1

Cubbi
Cubbi

Reputation: 47438

It means your compiler's empty base optimization is not as extensive as on other compilers.

Output of your program with all six Bases uncommented (and with the necessary include and the "void main" error fixed)

gcc 4.6.2: Sizeof der: 1

clang 3.0: Sizeof der: 1

intel 11.1 Sizeof der: 1

Sun C++ 5.8: Sizeof der: 1

Visual Studio 2010 SP1 (release build): Sizeof der: 5

Upvotes: 12

Related Questions