Using virtual function in child after casting operation in C++
<p>I have the following code:</p>

<pre><code>class A
{
};

class B : public A
{
    public:
        virtual void f() {}
};

int main()
{
    A* a = new A();
    B* b = static_cast&lt;B*&gt;(a);
    b-&gt;f();
}
</code></pre>

<p>This program fails with a segmentation fault. There are two solutions to make this program work:</p>

<ol>
<li>declare f non-virtual</li>
<li>do not call b->f() (i.e. it fails not because of the cast)</li>
</ol>

<p>However, both are not an option. I assume that this does not work because of a lookup in the vtable.</p>

<p>(In the real program, A does also have virtual functions. Also, the virtual function is not called in the constructor.)</p>

<p>Is there a way to make this program work?</p>
