c++ casting base class to derived class mess

alan2here picture alan2here · Jan 8, 2011 · Viewed 15.1k times · Source

If I were to create a base class called base and derived classes called derived_1, derived_2 etc... I use a collection of instances of the base class, then when I retrieved an element and tried to use it I would find that C++ thinks it's type is that of the base class, probably because I retrieved it from a std::vector of base. Which is a problem when I want to use features that only exist for the specific derived class who's type I knew this object was when I put it into the vector.

So I cast the element into the type it is supposed to be and found this wouldn't work.

(derived_3)obj_to_be_fixed;

And remembered that it's a pointer thing. After some tweaking this now worked.

*((derived_3*)&obj_to_be_fixed);

Is this right or is there for example an abc_cast() function that does it with less mess?

edit:

I had to expand this into another question, the full solutions are shown there. stackoverflow.com ... why-the-polymorphic-types-error-and-cleanup-question

Answer

Grizzly picture Grizzly · Jan 8, 2011

If you store your objects in a std::vector<base> there is simply no way to go back to the derived class. This is because the derived part has been sliced of when storing it in an instance of base class (afterall your vector contains copies of your data, so it happily copies only the base part of your objectes), making the stored object a true instance of base class, instead of a derived class used as a base class.

If you want to store polymorphic objects in the vector make it a std::vector<base*> (or some kind of smartpointer to base, but not base itself) and use dynamic_cast<derived_3*> to cast it to the correct type (or static_cast, if its performance sensitive and you are confident enough that you are trying to cast to the correct type (in that case horrible things will happen if you are wrong, so beware)).