Let’s say I have a few classes
Class Alpha (Base Class)
Class Beta (Subclass Alpha)
Class Delta (Subclass Alpha)
Would it be possible to create a vector<Alpha> and store object instances of types Alpha, Beta, and Delta all within that vector, and have the vector function as normal?
If not, supposing I wanted to have some sort of functionality like that, what would be the best approach?
One approach to this is to have a vector full of pointers, and have the functions that are common to each of them be
virtualin the base class:You have to be careful with this approach however, to make sure and
deleteeverything younewto put into the container. You could use smart pointers and avoid this caveat though:The reason you don’t want to have a vector of
Alphas (instead ofAlpha*s, which are alright) is because STL containers copy the values you give them, and if you copy aBeta(orDelta) as anAlpha, onlyAlpha‘s copy constructor will be called and the resulting information will have to fit into the size of anAlpha(which if you’ve added any information to the subclass it won’t be big enough), and the extra information theBeta(orDelta) had is lost. This is called slicing.