How come size of this class is 24b

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;

class base{
public:
	int i;
};

class derived1 : virtual public base{
public:
	int j;
};

class derived2: virtual public 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)

derived1::_vptr
derived1::j
derived2::_vptr
derived2::k
derived::sum
base::i

but other compilers, obviously, do other things.
Last edited on
What about this code? why is the output different?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;

class base{
public:
	int i;
};

class derived1 : public base{
public:
	int j;
};

class derived2: virtual public base{
public:
	int k;
};

int main()
{
	cout<<sizeof derived1<<endl;
	cout << sizeof derived2;
	return 0;
}


Visual Studio 2010
closed account (zb0S216C)
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.

Wazzak
I'm a newbie to this "Virtual Classes" topic..
I'm using C++ Complete Reference by Herb Schildt and it doesn't include any such topic in detail
closed account (zb0S216C)
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.

Wazzak
Topic archived. No new replies allowed.