std::bad_cast from parent to child?

Posted by polyglot on Stack Overflow See other posts from Stack Overflow or by polyglot
Published on 2010-06-08T09:49:10Z Indexed on 2010/06/08 9:52 UTC
Read the original article Hit count: 203

Filed under:
|

For simplicity,

class Parent {}
class Child1 : Parent {}
class Child2 : Parent {}

Elsewhere, I created instances of Child1 and Child2 and store it in same vector under Parent:

// . . . in .h file, for example
vector<Parent> vector_of_parent;

// . . . in one particular method
Child1 c1(); 
Child2 c2(); 
vector_of_parent.push_back(c1);
vector_of_parent.push_back(c2);
// . . .

Then in another method which has access to vector_of_parent, I tried

 void doSomething(Parent& some_child) { 
 // wrapped in a try block somehow...
 Child1& c = dynamic_cast<Child1&> some_child;
 // do something if the cast is successful
 }

 void otherMethod() {
      doSomething(vector_of_parent.at(0)); // vector_of_parent.at(0) is a Child1
 }

Why is there a std:bad_cast when I call otherMethod()?

© Stack Overflow or respective owner

Related posts about c++

Related posts about casting