Search code examples
c++inheritancefactory-patterndelete-operator

Deleting Instances in C++ Factory


I came across this C++ factory pattern, and I like how the ownership lies with the consumer:

class MyClass {
public:
    void Create(MyClass **instance, int some_param);
    void Destroy(MyClass *instance);

    void SomeAction() = 0;
}

// Use it

MyClass *instance;

MyClass::Create(&instance, 5);
instance->SomeAction();
MyClass::Destroy(instance);

But how do you implement Destroy? I imagine Create will look something like:

void MyClass::Create(MyClass **instance, int some_param) {
    // Subtype in some way derived from some_param
    if (some_param == 1) {
        *instance = (MyClass *) new MyClassSubClass();
    }
    // if some_param == 2, use MyDifferentSubClass() etc...
}

I've tried something like the following for Destroy, but can't get it to work:

void MyClass::Destroy(MyClass *instance) {
    delete instance;
}

Maybe delete needs to know the particular subclass (to know its allocation size)? But this doesn't seem to work either:

void MyClass::Destroy(MyClass *instance) {
    if (some_param == 1) {
        delete (MyClassSubClass *)instance
    }
}

Any input or alternative approaches very welcome.


Solution

  • delete(instance); should work. You forgot to add a virtual destructor in MyClass:

    class MyClass {
    public:
        virtual ~MyClass();
    
        void Create(MyClass **instance, int some_param);
        void Destroy(MyClass *instance);
    
        void SomeAction() = 0;
    }