c++ - Is it ok to cast a STL container with Base type to Derived type? -


Is it ok to insert a STL container of a type of derivative type? For example, I have two vectors in the first class of a base class, the second is in the type of derivative class.

  class base {// code}; Class derivative: public base {// code};   

Usage

  vector & lt; Base * & gt; * Vec_base = new vector & lt; Base *> // vec_base vector & derived * & gt; * Vec_derive = (vector & lieutent;> *) * (vec_base) add some derived type data to vec_base; // Using elements such as irreversible pointers works fine   

Is this OK? (It works fine, but I wanted to make some comment about it). Thanks a lot.

Edit: Updating according to the answer

Say if I use that vector carefully, and will not use it with multi-heritage and other than the Deriv type Will not include the objects, so is it okay? (I think it is not so)

Thanks a lot for more answers

< P> This is definitely not right, and one of the examples of C-style is masking errors, "This works for me" in this example is not a sign of well-defined behavior.

If you really want to do this, then I suggest:

  #include & lt; Vector & gt; # Include & lt; Algorithm & gt; #include & lt; Iterator & gt; using namespace std; Class base {// code virtual ~ base (); }; Class Dager: Public Base {// code}; DERVE * Convert (Base * IN) {// Insert Here? Back to dynamic_cast < Derrick * & gt; (In); } Int main () {Vector & lt; Base * & gt; * Vec_base = new vector & lt; Base *> // vec_base vector & lt; Darev * & gt; * Vec_derrive = new vector & lt; Dareiv *> Add some Depress type data to transform (vec_base- & gt; start (), vec_base- & gt; end (), back_interest_itator & lt; vector & lt; darve * & gt; & gt; (* vec_derrive, convert) ; }    

Comments