sizeof array element

In the code below, 'a' and 'r[0]' both refer to the same object (correct me if that is wrong).
sizeof(a) is 12 while sizeof(r[0]) is 1; why are they not the same size?

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
30
#include <iostream>
using namespace std;

class Base
{
};

class A: public Base
{
	int x;
	int y;
	int z;
};

class B: public Base
{
};

int main()
{
	A a;
	B b;
					// output:
	cout << sizeof(a) << endl;	// 12
	cout << sizeof(b) << endl;	// 1

	Base r[] = {a, b};
	cout << sizeof(r[0]) << endl;	// 1
	cout << sizeof(r[1]) << endl;	// 1
}
a is a polymorphic, i.e. it has more that one type. In this case, Base and A.

The size of the Base part, can't be zero, so it's one.
The size of the A part appears to be 12 on your system.

You're seeing object slicing, where the A part is sliced off, only the Base part is copied into r[0].
http://en.wikipedia.org/wiki/Object_slicing
Last edited on
closed account (jyU4izwU)
Just a fast comment...
Do: int x,y,z;
It compiles faster.
Last edited on
Just a fast comment...
Do: int x,y,z;
It compiles faster.

What? it absolutely shouldn't matter, but thats a bad coding style.
No, don't change your code in that way.
+1 @ not doing that.

The 1 nanosecond you might save in compile time is not worth the style tradeoff.
Last edited on
+2 for not doing that
the "thats a bad coding style" was referring to int x,y,z;, which is bad bad
closed account (jyU4izwU)
I never said it was good, i said it was faster.
in 100 lines of code the speed gain doesn't matter, in 100, 000 lines of code the clarity matters much more than the speed gain.
Thank you kbw; it's good to be aware of object slicing.
Topic archived. No new replies allowed.