TheAJ
TheAJ

Reputation: 10875

emplace_back and Inheritance

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?

Upvotes: 8

Views: 4026

Answers (2)

billz
billz

Reputation: 45450

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());

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 477464

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);

Upvotes: 14

Related Questions