Doubt on pointer conversion
- by Simone
Suppose we have the following code:
#include <iostream>
struct A
{
virtual void f() {
std::cout << "A::f()" << std::endl;
}
};
struct B: A
{
void f() {
std::cout << "B::f()" << std::endl;
}
};
void to_A(void* voidp) {
A* aptr = static_cast<A*>(voidp);
aptr->f();
}
void to_B(void* voidp) {
B* bptr2 = static_cast<B*>(voidp);
bptr2->f();
}
int main() {
B* bptr = new B;
void* voidp = bptr;
to_A(voidp); // prints B::f()
to_B(voidp); // prints B::f()
}
is this code guaranteed to always work as in the code comments or is it UB? AFAIK it should be ok, but I'd like to be reassured.