Carlos Hernández
Carlos Hernández

Reputation: 75

std::vector of Base class with Derived objects

I have a deque of std::shared_ptr declared has a deque of a base class (let's call it Polygon) but I'm storing on it pointers to derived objecs (for example Triangle). I'm thinking now about change the data structure to be a std::vector to use the fact that vector ensures adjacent memory but I have a couple of questions here:

1) Is this possible even if the objects have different sizes? Or can happen that due to the derived objects are bigger than the base one they are going to overlap in memory?

2) Storing std::shared_ptr I'm not going to have them literally together in memory just the pointers is it true? Or am I wrong?

Thanks

Upvotes: 1

Views: 149

Answers (1)

NathanOliver
NathanOliver

Reputation: 180510

Is this possible even if the objects have different sizes? Or can happen that due to the derived objects are bigger than the base one they are going to overlap in memory?

This is fine. Even though Derived can be larger than Base you aren't actually storing those in the vector. You are storing a pointer to them and the pointer is always the same size.

Storing std::shared_ptr I'm not going to have them literally together in memory just the pointers is it true? Or am I wrong?

Correct, the pointers will sit next to each other in the vector, but what they point to could be anywhere in memory.

Upvotes: 5

Related Questions