Search code examples
c++interfacevirtualdestructorunique-ptr

How to call the destructor of a child of an abstract class?


I have a purely abstract class:

class Abstract{
     void func1(arg1, arg2) = 0;
}

And its implementation with a destructor:

class Concrete : public Abstract{
void func1(arg1,arg2) { /*implementation code..*/ };
~Concrete() {/*code for the destructor..*/}

In main.cpp I create an unique pointer for it:

 int main(){
 std::unique_ptr<Abstract> class = std::make_unique<Concrete>();
 //do operations with it
 class.reset();
 }

After I'm done with class I need it to call the (custom) destructor of its current implementation class, but .reset() doesn't do that. How do I call the destructor of this implementation of Abstract class?


Solution

  • As per your implementation you have not defined your Abstract Class Destructor as virtual.

    So simple fix will be to make the destructor of the Abstract Class as virtual.

    So the Declaration of the Abstract Class will look like below:

    class Abstract{
         public:
         void func1(arg1, arg2) = 0;
         virtual ~Abstract() {/*..Destrctor Body..*/}
    }
    

    Now coming for the reason since in main.cpp , you are pointing to an object of Concrete Class using pointer of the Abstract Class and as you've performed reset() on the pointer of the Abstract class , it will cause the destructor of only Abstract class to be envoked.

    But as soon as you've made the destructor of the Abstract Class as Virtual , it will call the **destructor of the Concrete Class **First**** and then later the destructor of the Abstract Class will be called.

    For further details I am sharing one thread for the reference When Should we Use Virtual keyword ?