dimanche 30 avril 2017

How to correct match the object type and return it using factory pattern?

I'm trying to solve this error :

No suitable user-defined conversion from
"std::unique_ptr<< error_type >>, std::default_delete<< error_type >>" to
"std::unique_ptr< NPC, std::default_delete< NPC >>" exists.

This is my base class

NPC.h

class NPC
{

public:
    virtual void Talk() = 0;
    virtual void Act() = 0;
};

Then I have the current NPC objects

GoldenNpc.h

class GoldenNpc : public NPC
{
public:
    GoldenNpc(int npcIndex) { this->npcIndex = npcIndex };

    void Talk() override;

private:
    void Act() override;

private:
    int npcIndex;
};

SilverNpc.h

class SilverNPC : public NPC
{
public:
    SilverNPC(int npcIndex) { this->npcIndex = npcIndex };

    void Talk() override;

private:
    void Act() override;

private:
    int npcIndex;
};

The compiler error happens here:

NPCFactory npcFactory = NPCFactory();
std::unique_ptr<NPC> npc = npcFactory.MakeNpc(npcIndex, NPC_CONSTANT);
//npc.talk();

My Factory is defined as follow :

NPCFactory.h

class NPCFactory
{

public:
    std::unique_ptr<NPC> MakeNpc(int npcIndex, int npc_code) const;
};

NPCFactory.cpp

std::unique_ptr<NPC> NPCFactory::MakeNpc(int npcIndex, int npc_code) const
{
    switch (npc_code)
    {
    case GOLD:
        return std::make_unique<GoldNpc>(npcIndex);
    case Silver:
        return std::make_unique<SilverNpc>(npcIndex);
    default:
        return nullptr;
    }
}

I did not understand the reason for this compiler error.

Could someone explain to me? Thanks!

Aucun commentaire:

Enregistrer un commentaire