I am wondering if you can store items into a vector, using the emplace_back, a type that is derived from the class that vector expects.
For example:
struct fruit
{
std::string name;
std::string color;
};
struct apple : fruit
{
apple() : fruit("Apple", "Red") { }
};
Somewhere else:
std::vector<fruit> fruits;
I want to store an object of type apple inside the vector. Is this possible?
No. A vector only stores elements of a fixed type. You want a pointer to an object:
#include <memory>
#include <vector>
typedef std::vector<std::unique_ptr<fruit>> fruit_vector;
fruit_vector fruits;
fruits.emplace_back(new apple);
fruits.emplace_back(new lemon);
fruits.emplace_back(new berry);
std::vector<fruit> fruits;
It only stores fruit in fruits not derived types as allocator only allocates sizeof(fruit)
for each element. To keep polymorphism, you need to store pointer in fruits.
std::vector<std::unique_ptr<fruit>> fruits;
fruits.emplace_back(new apple);
apple is dynamically allocated on free store, will be release when element is erased from vector.
fruits.erase(fruits.begin());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With