简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM