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

Asked

Viewed 56 times

2

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

1 answer

2


This type of problem is solved through a indirect. When you have a pointer to the object it’s easy to deal with because the vector will only have pointers, so it doesn’t matter if it has the base object or any of the derivatives. The only requirement is that the object pointed out be of the base type or derived from it, only for type safety and not be able to put a loaf in a vector of animals.

If you do not want to use indirect there complicates. Easily and naturally there is no way. I’d have to create a mechanism to handle it manually, and I doubt it’s worth it. You will have to store in each element of the vector the object and of what type it is, and deal with each element according to the type. Without this it runs the risk of taking 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 base type size, if the derived type is larger, the excess will be discarded. Don’t even try.

  • I was in doubt of the exact interpretation of what the slicing in that case. I opened a question on the subject: https://answall.com/q/286437/64969

Browser other questions tagged

You are not signed in. Login or sign up in order to post.