Are these pointer conversions using static_cast ok?
<p>Suppose we have the following code:</p>

<pre><code>#include &lt;iostream&gt;

struct A
{
    virtual void f() { 
        std::cout &lt;&lt; "A::f()" &lt;&lt; std::endl;
    }
};

struct B: A
{
    void f() { 
        std::cout &lt;&lt; "B::f()" &lt;&lt; std::endl;
    }
};

void to_A(void* voidp) {
    A* aptr = static_cast&lt;A*&gt;(voidp);
    aptr-&gt;f();
}

void to_B(void* voidp) {
    B* bptr2 = static_cast&lt;B*&gt;(voidp);
    bptr2-&gt;f();
}

int main() {
    B* bptr = new B;
    void* voidp = bptr; 
    to_A(voidp); // prints B::f()
    to_B(voidp); // prints B::f()
}
</code></pre>

<p>is this code guaranteed to <em>always</em> work as in the code comments or is it UB? AFAIK it should be ok, but I'd like to be reassured.</p>

<p><strong>EDIT</strong><br>
Ok, so it seems there's a consensus that this code is UB, as one can only cast to the exact type. So, what if the <code>main()</code> changes to:</p>

<pre><code>int main() {
    B* bptr = new B;
    to_A(static_cast&lt;A*&gt;(bptr)); // still prints B::f()
    to_B(bptr); // still prints B::f()
}
</code></pre>

<p>is it still UB?</p>
