#include <iostream>
usingnamespace 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?
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.
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?