4

I have the base class and the class that inherits the base class:

class base
{
};

class derived : public base
{ 
    std::string str;
};

I need to manage a derived class using the pointer to the base class, but the following code causes a memory leak:

base* ptr = new derived();
delete ptr;

Have I to cast ptr, or there are better alternatives?

gliderkite
  • 8,688
  • 6
  • 42
  • 76

1 Answers1

7

You need a virtual destructor in the base class so the destructor of the derived class is found and called at runtime. See this question and answer for more detail.

Community
  • 1
  • 1
tmpearce
  • 12,215
  • 3
  • 39
  • 59