mentalmushroom
mentalmushroom

Reputation: 2467

Deletion of a derived class without new members through a pointer to the base class

A common practice for deleting a derived class instance through a pointer to its base class is declaring a virtual destructor in the base class. But I am curious what happens in case the derived class adds no new members to the base class and the base class' destructor is non-virtual.

Imagine, the following design. The base class has a protected constructor, so it can't be created directly. The only purpose of the derived class here is to allow base class creation by some Factory class. The Factory instantiates the derived class and returns a pointer to the base class. Eventually, when the pointed instance gets deleted by a user, the destructor of the derived class won't be called, of course, but I'm not sure if it's necessary since the derived class adds no new data. I'd like to clear up what kind of problems (if any) are possible in this case.

class Base
{
public:
    ~Base() = default;

protected:
    Base(int x, int y): x(x), y(y) {}

private:
    int x, y;
};

class Factory
{
    // privately declared Derived class exposes protected constructor from the Base class
    class Derived : public Base
    {
    public:
        Derived(int x, int y) : Base(x, y) {}
        ~Derived() = default;
    };

public:

    Base* create(int x, int y)
    {
        return new Derived(x, y);
    }
};  // Factory


int main()
{
    Factory factory;
    Base *base = factory.create(3, 4);
    delete base;
}

Upvotes: 2

Views: 62

Answers (1)

eerorika
eerorika

Reputation: 238321

But I am curious what happens in case the derived class adds no new members to the base class and the base class' destructor is non-virtual.

The behaviour of the program will be undefined regardless of the members of the derived class.

Upvotes: 2

Related Questions