samedi 30 janvier 2021

Why my factory pattern return error while compiling?

I want to implement simle factory pattern but when I try compile code i get error like:

error: undefined reference to `vtable for Interface'

error: undefined reference to `typeinfo for Interface'

class Interface{
public:
    virtual void set(const std::string &data);
    virtual void get(const std::string &data);
    virtual void show();
    virtual ~Interface(){}
};

class InterX : public Interface{
public:
    void set(const std::string &data){x++;}
    void get(const std::string &data){x--;}
    void show(){std::cout << x << std::endl;}
private:
    int x = 1;
};

class InterY : public Interface{
public:
    void set(const std::string &data){y++;}
    void get(const std::string &data){y--;}
    void show(){std::cout << y << std::endl;}
private:
    int y = 2;
};

class Factory{
public:
   static Interface* getInterface(const std::string interface_name){
       if(interface_name == "x") return new InterX();
       if(interface_name == "y") return new InterY();
       return nullptr;
   }
};

int main()
{
    Interface* interface = Factory::getInterface("x");
    return 0;
}

How could I fix that? When I commented line in main, the programs comiles

Interface* interface = Factory::getInterface("x");

Aucun commentaire:

Enregistrer un commentaire