Calling parent virtual destructor from child

Apr 16, 2011 at 9:10pm
Hi,

is it possible to call parent virtual destructor from the child destructor?
I'm used to call parent virtual functions trough Parrent::func(), but this not work for destructors. I have a base class with several subclasses and I would like to delete them trough the Base class pointer (without casting). Now I'm just copy pasting the content of the destructors for each subclass and adding what is necessary, but I don't think that's the correct way to do it.

The only solution that comes to my mind is creating something like virtual Dispose() method and chain them trough each sub class like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Child : public Parent
{
private:
   virtual void Dispose()
   {
    /*...*/
   }
public:   
   virtual ~Child()
   {
       Parent::Dispose()
       this->Dispose();
   }
};


Thanks in advance.
Apr 16, 2011 at 9:45pm
closed account (D80DSL3A)
None of that should be necessary. If the Parent destructor is virtual then a child object will be properly destroyed. The child destructor will automatically invoke the parent destructor. This works fine even if a parent (base) pointer is used to point to a child.
Apr 16, 2011 at 10:16pm
Uhm, thanks. I should've just try it :)
Now I see.

Thanks again.
Apr 16, 2011 at 11:07pm
closed account (D80DSL3A)
You're welcome. It's easy to verify. If you put a cout statement in each destructor then output will appear when they are invoked, enabling you to see exactly what's going on.
Topic archived. No new replies allowed.