The following code seems to work with the compilers (clang, g++ on both, Linux and Mac OS) I tried, but is it guaranteed to always do what one would expect?
struct A {
virtual void foo() = 0;
};
struct A2 {
virtual void foo() = 0;
};
struct B : public A2 {
void foo() {
printf("test\n");
}
};
int main() {
B* b = new B;
((A*)b)->foo();
}
I realize this is bad practice and one should not do this, but does it work generally?
It’s not bad practice: It doesn’t work. It will do something allright. Not unlikely, crashing. It is all allowed since you are invoking unspecified behaviour. Edit You might consult your compiler technical documentation (refer to ABI) to find compiler-specific extensions that you might rely on.
Try using
What you are doing is effectively
reinterpret_cast<A*>(b)and the results are entirely
your own responsibilityimplementation-defined.Edit To Nawaz: relevant standards passage: § 5.2.10, clause