When I have a class that requires a virtual destructor is it enough to declare it virtual (and let the compiler generate the definition) or do I have to define it explicitly?
Is it enough to declare destructor virtual?
129 views Asked by NPS AtThere are 2 answers
If the compiler generates a destructor for you:
§12.4/4 If a class has no user-declared destructor, a destructor is implicitly declared as defaulted (8.4). An implicitly-declared destructor is an inline public member of its class.
Note that you can do:
virtual ~Struct() = default;
6 Otherwise, the destructor is non-trivial. A destructor that is defaulted and not defined as deleted is implicitly defined when it is odr-used (3.2) to destroy an object of its class type (3.7) or when it is explicitly defaulted after its first declaration.
Or:
virtual ~Struct() { }
Admittedly, the distinction between "user-declared" and "user-provided" is pretty confusing, so here's the relevant section:
§8.4.3/4 Explicitly-defaulted functions and implicitly-declared functions are collectively called defaulted functions, and the implementation shall provide implicit definitions for them (12.1 12.4, 12.8), which might mean defining them as deleted. A special member function is user-provided if it is user-declared and not explicitly defaulted or deleted on its first declaration. A user-provided explicitly-defaulted function (i.e., explicitly defaulted after its first declaration) is defined at the point where it is explicitly defaulted; if such a function is implicitly defined as deleted, the program is ill-formed.
You have to explicitly say
virtual ~destructorName()
. Just because you have a derived class does not make the bass class's destructor virtual by default.