Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 668
TheAJ Avatar asked Jan 20 '13 01:01

TheAJ


2 Answers

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);
like image 78
Kerrek SB Avatar answered Sep 29 '22 20:09

Kerrek SB


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());
like image 30
billz Avatar answered Sep 29 '22 19:09

billz