Virtual destructors

I wrote a program that has a base class & one derived class. Do i need to make my base class destructor virtual even though i used no dynamic memory. Everything is on the stack no heap memory. No base class pointers?
No. A virtual destructor is for if you are using a base class pointer to point to an instance of a derived class, and the derived class has a non-trivial destructor. If you just have an instance of the derived class, or the derived class has a default destructor, then you don't need to have a virtual destructor in the base class.

However; will that always be the case? In lots of cases, yes, but that might not be true. If you think that you might possibly need a virtual destructor in the future, add one now, so you don't get memory leaks without realising it if you forget to add one later.
Alexandrescu and Sutter in 'C++ Coding Standards: 101 Rules, Guidelines, and Best Practices'
Make base class destructors public and virtual, or protected and nonvirtual.

Summary
To delete, or not to delete; that is the question: If deletion through a pointer to a base Base should be allowed, then Base's destructor must be public and virtual. Otherwise, it should be protected and nonvirtual.
...
Corollary: Always write a destructor for a base class, because the implicitly generated one is public and nonvirtual.
...


CppCoreGuidelines:
A base class destructor should be either public and virtual, or protected and nonvirtual

Reason
To prevent undefined behavior. If the destructor is public, then calling code can attempt to destroy a derived class object through a base class pointer, and the result is undefined if the base class's destructor is non-virtual. If the destructor is protected, then calling code cannot destroy through a base class pointer and the destructor does not need to be virtual; it does need to be protected, not private, so that derived destructors can invoke it. In general, the writer of a base class does not know the appropriate action to be done upon destruction.

and
A class with a virtual function should have a virtual or protected destructor

Reason
A class with a virtual function is usually (and in general) used via a pointer to base. Usually, the last user has to call delete on a pointer to base, often via a smart pointer to base, so the destructor should be public and virtual. Less commonly, if deletion through a pointer to base is not intended to be supported, the destructor should be protected and nonvirtual
Topic archived. No new replies allowed.