Doubt on pointer conversion
Posted
by
Simone
on Stack Overflow
See other posts from Stack Overflow
or by Simone
Published on 2010-12-30T08:46:38Z
Indexed on
2010/12/30
8:54 UTC
Read the original article
Hit count: 160
c++
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.
© Stack Overflow or respective owner