3 ms·
If you don't write a destructor, and the class needs one, the compiler will write one for you. Same with some of the other special functions. The rule might be
by kazinator 11y ago
If you don't write a destructor, and the class needs one, the compiler will write one for you. Same with some of the other special functions.
The rule might be expressed as "try to write classes that are adequately served by the compiler-generated special functions" (which the compiler will write consistently).
If all your member objects have destructors, there should be nothing left to do. The generated destructor recurses over these and that is that. So writing a custom destructor is for cases when something additional needs to be done because some members don't clean themselves up, or there is some other issue even if they all do. The Rule of Zero seems to be saying that these cases tend to be code smell.
Anyway, of course you have to write (or at least declare) a destructor if you need a virtual one, at the bottom of a class hierarchy.
~MyAbstractBase() = 0;
The language-supplied destructor will not be virtual, and certainly not pure virtual.
- pbsd 11y agoYou cannot just declare the destructor of a base class, since it will get called by the derived class destructors and linking will then fail. But you can write out an implementation for a pure virtual function, which will still keep the base class uninstantiable: virtual ~AbstractBaseClass() = 0; ... AbstractBaseClass::~AbstractBaseClass() { }
- anon4 11y agoHuh. Does that mean I can write class A { public: virtual void foo() = 0; }; void A::foo() {} class B: public class A {}; B b; b.foo(); and that will work?
- pbsd 11y agoNo, it will complain that A::foo is pure virtual, and that B must implement `foo`. However, if you define in B the method `void foo() { A::foo(); }`, it will work. In destructors this happens implicitly. There was an old Herb Sutter GotW about this: http://www.gotw.ca/gotw/031.htm http://www.gotw.ca/gotw/031.htm