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()?
Your
std::vectoris declared asstd::vector<Parent>. It holds only instances ofParent– when you insert theChild1andChild2instances, they get sliced.If you want to use a vector of polymorphic objects with a common base class of
Parent, you need to use a container of pointers (or, for ease of lifetime and memory management, smart pointers).Appropriate container types to consider include
std::vector<Parent*>,std::vector<std::tr1::shared_ptr<Parent> >andboost::ptr_vector<Parent>.I’d recommend against the
std::vector<Parent*>unless you’re very comfortable with manual memory management.Also, you need to use public inheritance instead of private, and the base class must have a virtual destructor. I assume you left these out for brevity though.