#include <iostream>
usingnamespace std;
class base{
public:
int i;
};
class derived1 : virtualpublic base{
public:
int j;
};
class derived2: virtualpublic base{
public:
int k;
};
class derived: public derived1, public derived2{
public:
int sum;
};
int main()
{
derived ob;
cout<<sizeof ob;
return 0;
}
How come the output is 24???In Visual Studio 2010
Explain in detail please
It is entirely compiler- and platform-specific. I get:
with XLC on AIX: 32 bytes in 32-bit mode, 56 bytes in 64-bit mode
with GCC on Linux: 24 bytes in 32-bit mode, 40 bytes in 64-bit mode
with Sun Studio on Solaris: 24 bytes in 32-bit mode, 48 bytes in 64-bit mode
Looking at the 24 bytes of 32-bit gcc's ans sun's layout, which happens to be identical, I see (each line is 4 bytes)
#include <iostream>
usingnamespace std;
class base{
public:
int i;
};
class derived1 : public base{
public:
int j;
};
class derived2: virtualpublic base{
public:
int k;
};
int main()
{
cout<<sizeof derived1<<endl;
cout << sizeof derived2;
return 0;
}
In addition to Cubbi's reply, the size of an unpacked structure is influenced by the size of each member, the VTP (virtual table pointer), and any possible alignment padding the compiler added between the members. Since a compiler may re-arrange a classes data members in any way it wants, it may affect the the result of the "sizeof( )" operator.
SameerThigale wrote:
"why is the output different?"
Because "derived2 has a VTP, and "derived1" does not.
Ah, that's not the best book in the world. In fact, it's a terrible book. As it does not cover virtual inheritance, it's not a complete reference. Bin it -- literally.