c++ casting base class to derived class mess

Posted by alan2here on Stack Overflow See other posts from Stack Overflow or by alan2here
Published on 2011-01-08T00:45:56Z Indexed on 2011/01/08 0:53 UTC
Read the original article Hit count: 333

Filed under:
|
|
|
|

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?

© Stack Overflow or respective owner

Related posts about c++

Related posts about class