illuminating use of destructors

I stumbled over CABrouwer's post (http://www.cplusplus.com/forum/general/251463/#msg1107166), and this made me recognize that I have rarely understood how destructors work and when I should add them or don't need them.

AFAIK the purpose of a dtor is, assuring that all allocated memory gets freed, and - perhaps - caring about some side effects.

So what about derived classes? Do I need there a virtual dtor regardless of whether there will some memory to free?
Is a virtual dtor needed if the derived class added further members beside the base class?

Maybe someone could explain how a dtor works at derived objects :)

1
2
Base *foo = new Derived;
delete foo; //¿what destructor is called? 
¿do you understand why you need the Base destructor to be virtual?

> if the derived class added further members
A Base may know nothing about its Derived
Yea, if Derived has a virtual dtor, it would be called. Otherwise Base's dtor.
But, need we here a destructor if no additional memory had to be freed?

All I know is, that a dtor is needed if somewhere inside the ctor memory is allocated:
1
2
3
4
5
struct Base {
    int * val;
    Base() { val = new int[256]; }
    ~Base() { delete[] val; }
};


What is, if we have a:
1
2
3
4
struct Derived : public Base
{
    int foo;
};

Here comes to me the question: Is it needed to have here a virtual destructor, or is it sufficient using the destructor of the Base class? Especially: Would the Derived class properly get destructed without having its own (overriding?) destructor?
Last edited on
When to write a destructor? Rule of three/five/zero: https://en.cppreference.com/w/cpp/language/rule_of_three

That is a cousin of RAII https://en.cppreference.com/w/cpp/language/raii


What does a destructor do?
1. Execute the statements in its body [A]
2. Invoke the destructors of the class members
3. Invoke the destructors of the base class(es) [B]


[A] If the class explicitly manages a resource, this is the point of release
[B] Plural, if multiple inheritance


1
2
3
4
struct Derived : public Base
{
    int foo;
};

Is it the end of the world, if you don't call the "destructor of int"?
That is just an innocent small white lie?

Is it the end of the world, when the next developer sees that you derive from Base and use polymorphism, assumes that Base has virtual destructor, derives an another class, and hell breaks loose?
Last edited on
Sorry for my nagging questions :) It's because of my deficient memory ability. I believe when I understood this stuff entirety, I need not longer rely on rules of thumb.
> Yea, if Derived has a virtual dtor, it would be called.
wrong
if Base destructor is virtual, then it woul call Derived constructor

> 2. Invoke the destructors of the class members
1
2
3
4
struct Derived : public Base
{
    std::vector<int> foo;
};
Topic archived. No new replies allowed.