1

I am assigning a pointer to a pointer inside the constructor of a class. In the destructor I delete the pointer which is a member variable. This mean that the pointer passed in as an argument is also deleted when the destructor is called but i can't understand why. I made a small piece of code to preview my question.

class IWrite {
public:
    virtual void write(string) = 0;
};

class Consolerite : public IWrite
{
public:
    void write(string myString)
    {
        cout << myString;
    }
};

class OutPut
{
public:
    OutPut(IWrite* &writeMethod)
    {
        this->myWriteMethod = writeMethod;
    }
    ~OutPut() { delete this->myWriteMethod; }

    void Run(string Document)
    {
        this->myWriteMethod->write(Document);
    }

private:
    IWrite* myWriteMethod = NULL;
};

int main()
{
    IWrite* writeConsole = new Consolerite;
    OutPut Document(writeConsole);
    Document.Run("Hello world");
    system("pause");
}

When the program exits the IWrite* writeConsole is deleted but i can't understand why. Can someone help me understand that. Thank you.

Wander3r
  • 1,801
  • 17
  • 27
Ari663
  • 25
  • 5

1 Answers1

2

You are not "deleting the pointer" you are deleting the object this pointer points to (that is to object created with new Consolerite). And since the pointer passed and member field pointer point to the same object they will both become invalid once you use delete on any of them.

Also this program has undefined behavior since you are deleting an object using a pointer to base class that does not have a virtual destructor.

user7860670
  • 35,849
  • 4
  • 58
  • 84
  • Ok I think I understand. Thank you – Ari663 Apr 10 '19 at 09:36
  • but i thought it uses the default destructor of the base class. i need to provide destructor? – Ari663 Apr 10 '19 at 09:40
  • @Ari663 *"it uses the default destructor of the base class"* - and that is the problem, destructor of derived class is never called. Though it is not like it really makes any difference in this example since both classes have no fields and no user-defined destuctors. – user7860670 Apr 10 '19 at 09:47
  • @VVT my intention is to make an Interface of IWrite class which contains only pure virtual functions. In that case do I have to provide destructors for the derived classes of that interface? Sorry for the many questions – Ari663 Apr 10 '19 at 09:53
  • @Ari663 See [When to use virtual destructors?](https://stackoverflow.com/questions/461203/when-to-use-virtual-destructors) – user7860670 Apr 10 '19 at 09:59