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,828
  • 6
  • 44
  • 80
  • 5
    add virtual destructor in base class – Mr.Anubis Jul 04 '12 at 19:14
  • Virtual destructor, Dude! ;) Great link: http://blogs.msdn.com/b/oldnewthing/archive/2004/05/07/127826.aspx – paulsm4 Jul 04 '12 at 19:17
  • possible duplicate of [Will using delete with a base class pointer cause a memory leak?](http://stackoverflow.com/questions/2100644/will-using-delete-with-a-base-class-pointer-cause-a-memory-leak) – CB Bailey Jul 04 '12 at 19:18
  • 1
    It actually causes undefined behavior, from the language point of view. – GManNickG Jul 04 '12 at 19:36

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,523
  • 4
  • 42
  • 60