1

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.

Community
  • 1
  • 1
jcuenod
  • 55,835
  • 14
  • 65
  • 102

1 Answers1

3

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.

filmor
  • 30,840
  • 6
  • 50
  • 48
  • Okay, but if I make the destructor public I get a segfault when I try to delete that object – jcuenod Jan 08 '12 at 14:15
  • I am realising that my problem lies somewhere in the class to be deleted. At this point I'm thinking the constructor. – jcuenod Jan 08 '12 at 15:17
  • 1
    You have to show some code. The segfault is most likely not from built-in structures but from your own programming :) – filmor Jan 08 '12 at 15:18
  • Thanks, I'll mess around a bit and do some googling and maybe ask another question... Shot for the help - must say I did completely miss "abstract". – jcuenod Jan 08 '12 at 19:54