CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Nov 2000
    Posts
    43

    Question Question about deleting base class pointer

    Is it possible to get memory leak when deallocate a derived class object by deleting its base class pointer(if the base class has virtual destructor)? What about the base class doesn't have virtual destructor?

  2. #2
    Join Date
    Mar 2002
    Location
    California
    Posts
    1,582
    If the base class has a virtual destructor, all the derived class destructors will be called. If not, they won't. Hence, every base class should have a virtual destructor.

    Now, it's still possible to have a memory leak if your class does not free dynamic memory correctly. But this is not the result of a destructor not being called.

    Jeff

  3. #3
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470
    Originally posted by jfaust
    Hence, every base class should have a virtual destructor.
    Just to step on Jeff's toes a little bit (sorry, jeff ), note that, by base class he means a class that is specifically designed to be derived from, not that all classes should be given a virtual dtor as a matter of course. It's cause of constant annoyance to me that VC++ insists on adding a virtual destructor if you use the "Add class..." menu option. The first thing that I always find myself doing is deleting the (default) ctor and the dtor that it "helpfully" adds for you.

    Just thought I'd point that out for any of out younger viewers who might be watching.
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


  4. #4
    Join Date
    Mar 2002
    Location
    California
    Posts
    1,582
    Ouch, my toes!

    But right, "designed to be derived from" is more appropriate than "base class". It should be a design decision rather than an implementation decision.

    Jeff

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured