I added a protected member array in the abstract base class that each derived class uses, should the destructor of the base class be virtual or can I do:
**~base(){
delete[] array;
}**
I added a protected member array in the abstract base class that each derived class uses, should the destructor of the base class be virtual or can I do:
**~base(){
delete[] array;
}**
On
I added a protected member array in the abstract base class that each derived class uses, should the destructor of the base class be virtual
Yes.
When you use polymorphism desctructor should be also virtual.
There is official guideline for that:
CppCoreGuidelines/CppCoreGuidelines.md at master · isocpp/CppCoreGuidelines · GitHub
C.127: A class with a virtual function should have a virtual or protected destructor
ReasonA 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 non-virtual; see C.35.
Example, badNotestruct B { virtual int f() = 0; // ... no user-written destructor, defaults to public non-virtual ... }; // bad: derived from a class without a virtual destructor struct D : B { string s {"default"}; }; void use() { unique_ptr<B> p = make_unique<D>(); // ... } // undefined behavior, might call B::~B only and leak the stringThere are people who don't follow this rule because they plan to use a class only through a
Enforcementshared_ptr:std::shared_ptr<B> p = std::make_shared<D>(args);Here, the shared pointer will take care of deletion, so no leak will occur from an inappropriatedeleteof the base. People who do this consistently can get a false positive, but the rule is important -- what if one was allocated usingmake_unique? It's not safe unless the author ofBensures that it can never be misused, such as by making all constructors private and providing a factory function to enforce the allocation withmake_shared.
- A class with any virtual functions should have a destructor that is either public and virtual or else protected and non-virtual.
- Flag
deleteof a class with a virtual function but no virtual destructor.
Both!
You can provide a definition for the base destructor (even if it's pure virtual!) and, if the base is where the resource lives, then the base is where it should be cleaned up.
Alternatively, get yourself a nice
std::vectorso it's all done for you.