I had a job interview earlier and was asked what the output of the following code is:
struct A {
int data[2];
A(int x, int y) { data[0] = x; data[1] = y; }
virtual void f() {}
};
int main(){
A a(22, 33);
int* data = (int*)&a;
cout << data[2] << endl;
}
I talked through it but couldn't figure it out exactly. He mentioned that the virtual function was a hint. Afterwards I compiled it and got the output:
22
I then thought about the virtual function and removed it:
struct A {
int data[2];
A(int x, int y) { data[0] = x; data[1] = y; }
//virtual void f() {}
};
int main(){
A a(22, 33);
int* data = (int*)&a;
cout << data[2] << endl;
}
Resulting in the ouput:
0
My question is: How does the seemingly inconsequential virtual function call affect the resulting object's memory layout to cause this?