Apologies if the variant from the question was already requested - but allows say I'm writing a software application class within an application by which they might be future derivations. I do not have any virtual functions (the overall guideline for implementing virtual dtors), and thus given my memory limitations I not possess a virtual destructor within this utility class.

A couple of developers later - someone contributes to my utility class by drawing from this. If, any place in the code my new class in new'd and erased the right dtor won't be known as because the base class dtor wasn't made virtual (see example code).

Apart from returning and altering the bottom class - what solutions exist within this situation?

#include <iostream>
using namespace std;

class utility {
  int i, j;

  public:
    utility () { cout << "utility ctor\n";};
   ~utility () { cout << "utility dtor\n";};
    void dosomething () { cout << "haha\n";};
};

class addtoutility: public utility  {
  char *ch;

  public:
   addtoutility () { ch= new char(); cout << "added ctor\n";};
  ~addtoutility () { delete ch; cout << "added dtor\n";};
   void andnowaddsomefunctionality () {};
};

int main () {
  utility *u  = new addtoutility();
  //lots of interesthing code
  delete u;
}

Your base class isn't polymorphic so there's little value to getting a pointer-to-base regardless. Your base class documents the truth that it's not polymorphic by not while using virtual keyword anywhere.

If a person wants for doing things because the base class to some polymorhpic hierarchy they can also add a virtual destructor towards the top class they be a consequence of it and, where necessary, hold pointers to that particular base class type.

You cannot prevent developers who come later from digging their very own traps but there's no problem having a non-polymorhphic class and you don't have to do anything whatsoever into it to "allow it to be safe".

As evidence this is typical and acceptable practice, you'll need only have a look in the standard library. You will find many classes (strictly, most of them are class templates) without any virtual functions with no virtual destructor.

  • Remove it via a pointer from the correct type. Since no other techniques are virtual there actually is no indicate dealing with it polymorphically.

Works:

addtoutility *u  = new addtoutility();

delete u;
  • Allow it to be virtual. If you are concerned about the overhead then it is likely minimal.
  • Use static inheritance using CRTP. The only issue is this fact might take up more memory than the usual vtable.

If you cannot customize the code from the base class whatsoever, you can include a function towards the derived class like Destroy(). Type of annoying but we do all of it time should you think about Win32 objects like Brush.