[help]type casting

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

#include <iostream>

using namespace std;

class A
{
	int a,b;
	public:
		void operate()
		{
			a = a + b;
			b = a + b;
		}
};
int main()
{
	int b[4], i;
	A *p = (A*)b;
	for( i = 0; i < 4; i++ )b[i] = i;
	p->operate();
	for( i = 0; i < 4; i++ ) cout << b[i] << ",";
	return 0;
}


someone can explain about class type casting and what happening in code above?

sorry for my bad english
Maybe someone is better suited to explain, but I'll give it a shot.

Classes, int's, doubles, etc. are just data types: They tell the compiler to interpret a bunch of bytes in a certain way. The line int b[4]; just reserves 16 bytes in the stack and then sets them to the values 0, 1, 2 and 3 in line 20.

Line 19, on the other hand is just "mapping" the data type 'class A' over the 16 bytes occupied by int array b. It so happens that member variable A::a fits exactly in the four bytes that represent the first element of array b, and it so happens that member variable A::b fits exactly in the four bytes that represent the second element of array b.

Therefore, by the time line 21 is called, A::a and A::b have the values 0 and 1 (due to execution of line 20). The function operate() changes A::a to (0 + 1) and A::b to (1 + 1). Since these are "mapped" into positions 0 and 1 of array b, line 22 outputs 1, 2, 2, 3.

Did you see Ironman? The first suit he designed was drawn in pieces in different pieces of paper, and the whole design could only be seen by placing the sheets of paper one on top of the other. Well, line 19 is a sheet of paper with class A drawn on it that is placed over a sheet of paper that has int b[4] drawn on it.
note: It's a fine explanation, except that you shifted line numbers down. Where you wrote line 20, should be 19 and etc.
All bets are off as to what that will do at runtime. I would steer as clear of that snippet as possible!
@moorecm, while I agree that this isn't a good thing to do, I'd like to hear of a scenario where this code does not produce 1 2 2 3.
The code relies on the memory layout of the object, which I do not think is mandated by the standard (parts of it might be?). What if a compiler decided to add padding, change the order of the members, or places a [null] vtable pointer in the first byte of the object?
Last edited on
Technically there's no possibility of a vtable here, since A follows the guidelines for a POD struct/class according to the standard.

However I agree with moorecm that this should not be attempted.
Topic archived. No new replies allowed.