Suppose we have such code:
struct Granny {
int g;
};
struct Mom : virtual Granny {
int m;
};
struct Son : Mom {
int s;
};
int main() {
int x;
std::cin >> x;
Mom* mom = (x ? new Son : new Mom);
Granny* granny = static_cast<Granny*>(mom);
}
Classes are not polymorphic, so Granny doesn’t has a vtable. Now, depending on x, there can be different memory layout under mom pointer. So, sub-object Granny will be shifted from the object start by either 16 or 12 bytes.
Question: is static_cast instead of “simply shift pointer” compiled in “dereference vptr(vtable) in mom object, then look at some index to find virtual offset, then, finally, shift pointer by this offset“? So, would static_cast has 2 additional runtime operations? If not, please, explain what happens.
gh_shark is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.