Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As far I could test, it is very important to add the virtual destructor. I'm using objects created with <code>new</code> and destroyed with <code>delete</code>.</p> <p>If you do not add the virtual destructor in the interface, then the destructor of the inherited class is not called.</p> <pre><code>class IBase { public: virtual ~IBase() {}; // destructor, use it to call destructor of the inherit classes virtual void Describe() = 0; // pure virtual method }; class Tester : public IBase { public: Tester(std::string name); virtual ~Tester(); virtual void Describe(); private: std::string privatename; }; Tester::Tester(std::string name) { std::cout &lt;&lt; "Tester constructor" &lt;&lt; std::endl; this-&gt;privatename = name; } Tester::~Tester() { std::cout &lt;&lt; "Tester destructor" &lt;&lt; std::endl; } void Tester::Describe() { std::cout &lt;&lt; "I'm Tester [" &lt;&lt; this-&gt;privatename &lt;&lt; "]" &lt;&lt; std::endl; } void descriptor(IBase * obj) { obj-&gt;Describe(); } int main(int argc, char** argv) { std::cout &lt;&lt; std::endl &lt;&lt; "Tester Testing..." &lt;&lt; std::endl; Tester * obj1 = new Tester("Declared with Tester"); descriptor(obj1); delete obj1; std::cout &lt;&lt; std::endl &lt;&lt; "IBase Testing..." &lt;&lt; std::endl; IBase * obj2 = new Tester("Declared with IBase"); descriptor(obj2); delete obj2; // this is a bad usage of the object since it is created with "new" but there are no "delete" std::cout &lt;&lt; std::endl &lt;&lt; "Tester not defined..." &lt;&lt; std::endl; descriptor(new Tester("Not defined")); return 0; } </code></pre> <p>If you run the previous code without <code>virtual ~IBase() {};</code>, you will see that the destructor <code>Tester::~Tester()</code> is never called.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload