vendredi 24 avril 2020

Factory Method C++

I'm a begginer in C++ and I was trying to solve this implementacion of the factory method, where I'm trying to look for the implementation with the funcion make object below is:

  1. Retrive the return type in order to provide access to the created object in the class Object below.
  2. Create two objects(Object2 and Object3) for the given id
  3. Trying to be thread safe.

I'm working on the following code:

enum ObjectType {
    FO_Object2, FO_Object3
};

class Object {
    int ID;
public:
    Object(int id) : ID(id) {}
    Object(const Object&) = delete;

    virtual void printObject() = 0;
    static Object* make_object(int id);
};

class Object2: public Object
{
public:
    void printObject() {
        std::cout << "ID = 2" << std::endl;
    }
};

class Object3 : public Object
{
public:
    void printObject() {
        std::cout << "ID = 3" << std::endl;
    }
};

//Factory Method to create objects
Object* Object::make_object(int id)
{
    switch (id)
    {
        case FO_Object2: return new Object2();
        case FO_Object3: return new Object3();
        default:
            return NULL;
    }
}

class object_factory
{
public:
    object_factory()
    {
        ObjectType id = FO_Object3;
        pObject = Object::make_object(id);
    }
    ~object_factory()
    {
        if (pObject) {
            delete[] pObject;
            pObject = NULL;
        }
    }
    Object* getFactory() {
        return pObject;
    }
private:
    Object* pObject;
};

But unfortunately in my Error list infors me that i have the following Errors:

E1790 --> the default constructor of "Object2" cannot be referenced -- it is a deleted function.

E1790 --> the default constructor of "Object3" cannot be referenced -- it is a deleted function.

C2280 --> 'Object2::Object2(void)': attempting to reference a deleted function

Anyone can help me with this issue, thanks in advance.

Aucun commentaire:

Enregistrer un commentaire