devxlogo

A vector<Base> Should Not Store Derived Objects

A vector<Base> Should Not Store Derived Objects

A vector stores its elements contiguously in memory (although this is not a requirement in the Standard, in practice, all implementations use contiguous storage). Consequently, each element in a vector must have the same size. Since a derived object may have additional members, its size may be larger than the size of its base class. Thus, storing a derived objects in a vector should be avoided because it may cause object slicing and memory overruns, with disastrous results at run time.

devx-admin

Share the Post: