1

In delegate pattern is it good to make the destuctor virtual ?

class MyClass
{
    ...
};

class MyClassDelegate
{
    ...
};

On one hand class MyClassDelegate is an interface and supposed to be inherited from, but on the other hand it's not supposed to delete the subclass via the MyClassDelegate pointer

What do you think ?

Andrew
  • 24,218
  • 13
  • 61
  • 90

3 Answers3

5

You could consider making it protected non-virtual - then you're actually enforcing and documenting the fact that you can't delete an object using that kind of pointer. Some more discussion can be found here

Community
  • 1
  • 1
Michael Anderson
  • 70,661
  • 7
  • 134
  • 187
0

Making destructor virtual if you already have other virtual functions introduces almost no overhead.

yuri kilochek
  • 12,709
  • 2
  • 32
  • 59
0

If you plan to have classes inherit from MyClassDelegate, it's best to give it a virtual destructor.

In your initial design, you may not plan to delete any pointers to MyClassDelegate, but this design will evolve, and your choice will impose a constraint on how this evolves. This particular constraint is easy to forget, and the crashes (or subtle bugs) that result may take a while to diagnose.

sfstewman
  • 5,589
  • 1
  • 19
  • 26