In C++, how can I test if an object is an instance of a Child class in the Parent class' constructor?
<p>I'm trying to assert that a pointer passed into a Parent class' constructor is only <code>NULL</code> if the object is of a <em>specific</em> Child class type using <code>dynamic_cast</code>:</p>

<pre><code>#include &lt;iostream&gt;
class Parent {
public:
    Parent(void *ptr);
    virtual ~Parent(); // to make Parent polymorphic
};

class Child1 : public Parent {
public:
    Child1() : Parent(0) { std::cout &lt;&lt; "Child1 ctor\n";};
};
class Child2 : public Parent {
public:
    Child2() : Parent(0) { std::cout &lt;&lt; "Child2 ctor\n";};
};

Parent::Parent(void *ptr) {
    if (0 == ptr &amp;&amp; 0 == dynamic_cast&lt;Child1*&gt;(this)) {
         std::cerr&lt;&lt;"ERROR\n";
    }
}
Parent::~Parent() {};

int main(void) {
    Child1 *c1 = new Child1();
    Child2 *c2 = new Child2();
}
</code></pre>

<p>This prints:</p>

<pre><code>ERROR
Child1 ctor
ERROR
Child2 ctor
</code></pre>

<p>Whereas, I expect to see <code>ERROR</code> during the <code>Child2</code> construction <em>only</em>.</p>

<p>Why is <code>dynamic_cast</code> returning non-NULL when I'm in <code>Parent</code> constructor for <code>Child1</code> called from <code>Child1</code>'s constructor initialization list?  Also, is there a different way to accomplish this test?</p>
