galinette
galinette

Reputation: 9292

Prevent deleting an object through an interface

Let's suppose that in C++ I have an interface class Interface, which has only pure virtual functions. Then, other class definitions derive from this interface and provide an implementation for the pure virtual functions.

Now, is there a way to prevent an object to be deleted via an Interface* pointer? I have tried deleting the constructor but then derived classes can't be destroyed either.

The idea being to pass object pointer while being clear on the fact that ownership isn't passed with the pointer. I know there are other ways to achieve this, I'm just curious whether it's doable in C++.

Upvotes: 0

Views: 365

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

You can make the destructor protected:

struct interface {
    protected:
        virtual ~interface(){}
};

struct concrete : interface {};

int main(){
    //interface f; // error

    //interface* f2 = new concrete(); 
    //delete f2;                       // error

    concrete c;

    concrete* c2 = new concrete();
    delete c2;
}

However, note that it is delete f2; that issues the error, so a user might be tempted to new interface and then leak it.

Also note that this is technically possible but wont solve any problem. You would always need to know the concrete type otherwise you cannot delete an object, making the interface basically useless for polymorphism.

Upvotes: 1

Related Questions