1
votes

I am fairly new to C++ memory management. I read Should every class have a virtual destructor? and found this answer:

Every abstract class should either have a

  • protected destructor or
  • virtual destructor

If you've got a public non-virtual destructor, that's no good, since it allows users to delete through that pointer a derived object. Since as we all know, that's undefined behavior.

For a class not intended to delete through a pointer to it, there is no reason whatsoever to have a virtual destructor. It would not only waste resources, but more importantly it would give users a wrong hint. Just think about what crappy sense it would make to give std::iterator a virtual destructor.

So I have a protected destructor now (I am not deriving from the class).

In another class though I have a pointer to this object. In my constructor I make give the pointer a "new" object of that class, in my destrcutor I would like to destroy it.

How do I do that? If the destructor is not protected I get a seg fault (which I don't entirely understand but I realise is bad programming anyway). If the destructor is protected I don't know how to delete the object.

1

1 Answers

3
votes

You are missing the term "abstract" in the block above. "abstract" means, that you shouldn't /have/ an object of the class. If you have objects from a class, it should almost always have a public destructor.