Question

If this question has been asked I apologize. I am writing a c++ class which will be interfaced with python. The class implementation so far is:

struct body_data
{
map <int, atom*> atoms;
map <int, bond*> bonds;
map <int, dihedral*> dihedrals;
};

This class is the base class for another class. I have not added in the destructor for this class because I am very confused. In all of the posts I have read about destructors for base classes they suggest the destructor should either be public virtual or protected. Since i am not planning on using the above class polymorphically in either the c++ code or python interface do I really need to make the destructor public virtual or protected? I was thinking of making the class public so programmers would know never to use this class polymorphically. Is my thinking correct?

Was it helpful?

Solution

You only need a public destructor to be declared as virtual when you have virtual functions, indicating you intend your type to be derived from. I emphasize "need" because it's only needed if your base type has non-POD types or you know that types derived from yours will have non POD types. Yes, you could have a base class that has zero virtual members, but such a base would have marginal utility. Unnecessarily adding virtual members adds overhead. i.e. if you have a type that has no virtual members other than a virtual destructor, typically you've increased the size of each instance by one pointer, and destruction of said object will be slightly slower because you have to call the destructor through at least a single memory indirection. Incrementally adding virtual members after the first should have a fixed memory cost, but you'll still encure runtime penalties for unnecessarily virtualizing functions.

In your case, your data types seem to indicate ownership of dynamically allocated memory (maps whose values are raw pointers) and you've indicated this is intended to serve as a base to other types (this is key), in which case you would definitely want to define a destructor that properly deallocates the memory, and since you've stated it's serving as a base to other types, it should be marked as virtual, unless you can absolutely ensure the instances will never be destroyed from anything other than a pointer to the most derived type (making this assumption is very dangerous and failure could lead to hard to diagnose memory leaks).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top