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.