Home > Back-end >  Adding derived class object to vector<unique_ptr> of base class
Adding derived class object to vector<unique_ptr> of base class

Time:10-07

So in my code I'm trying to add unique_ptr to objects from derived class to vector of base class. I get this error:

E0304 no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back [with _Ty=std::unique_ptr<Organism, std::default_delete<Organism>>, _Alloc=std::allocator<std::unique_ptr<Organism, std::default_delete<Organism>>>]" matches the argument list

The code of base class (if you need more let me know, trying to put as little code as possible):

vector<unique_ptr<Organism>>  World::generate_organisms(int act_level)
{
    vector<unique_ptr<Organism>> organism_list = get_vector();
    coordinates sheep_pos(10, 2);
    //getting error in next line
    organism_list.push_back(make_unique<Sheep>(sheep_pos, *this));

    return organism_list;
}

Code of the derived class:

.h file

class Sheep : Organism
{
    Sheep( coordinates organism_pos, World* world);
};

.cpp file

Sheep::Sheep( coordinates organism_pos, World* act_world)
    :
    Organism(organism_pos, act_world)
{
    this->armor = 0;
    this->damage = 2;
    this->health = 10;
    this->vigor = 10;
}

CodePudding user response:

Similar to how the default member visibility of class is private, inheritance is also private unless otherwise specified. You need to inherit from Organism publicly so that std::unique_ptr is able to see and perform the conversions you expect.

class Sheep : public Organism {
public:
    Sheep( coordinates organism_pos, World* world);
}

Your constructor also needs to be public so that std::make_unique can see and use it.

  • Related