Interview Question
SDE-2sTeam: abc
Country: United States
Interview Type: Phone Interview
when you typecasted to void*, all info about D's layout got lost. So now when you are again type casting to C*, it just sets the pointer, but the vtable info is for D, compiler didn't do any adjustment because of the typecast, so when calling the method, it just calls whatever method it found in the offset location, which is undefined because a void* was not supposed to have any info
You have created D form both A and C, and their virtual tables are combined.
so virtual table for D looks like [fun1,fun2,fun3]
When compiler see d->fun3() it is compiled to "call 3rd function in virtual table"
But with that casting through void* you lost the type information.
at this point C* c = (C*)obj compiler doesn't know what obj is, it just assumes that first item is a pointer to virtual table and second one is z.
So c->fun3() is compiled to "call 1st function in virtual table"
First function in virtual table is fun1.
P.S. try to add variable "int w;" to class A then change c->z in "other" then check what d->w is :).
This has to do with the type casting and the fact that your C::fun3 is virtual. Somehow B::fun1 is overriding the virtual C::fun3. If you cast your void* obj to the correct type, or remove the virtual keyword from C::fun3 you will get the expected output. Sorry I cannot provide a better explanation.
- Steve August 28, 2015