How to save in a single vector, base classes and derivatives?

2

I have a C ++ job, and I need to write to a single vector, a base class, and two derivatives. How to make this vector?

    
asked by anonymous 25.03.2018 / 03:59

1 answer

2

This type of problem is addressed through an indirection . When you have a pointer to the object it is easy to handle this because the vector will only have the pointers, so it does not matter if it has the base object or any of the derivatives. The only requirement is that the object pointed to is of the base type or derived from it, just for the sake of type security and can not put a loaf of bread into an animal vector.

If you do not want to use indirection then it complicates. In an easy and natural way it has no way. I would have to create a mechanism to handle this manually, and I doubt it will compensate. You will have to store in each vector element the object and what type it is, and deal with each element according to the type. Without this you run the risk of catching an object as if it were another with an inadequate structure. This phenomenon is called slicing . For the vector to have fixed size it will adopt the size of the base type, if the derived type is larger, the excess will be discarded. Do not even try.

    
25.03.2018 / 04:11