Virtual destructor confusion

Hi,

Consider the following snippet:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Base{
//some code here
};

class Derived: public Base{
//some code here
};

int main(){
Derived cDerived;
Base *rBase = cDerived;
delete rBase;
return 0;
}


My question is: Will it be okay if we did NOT declare Base's destructor virtual?
Since cDerived is not dynamically created there is no resource to be de-allocated. But, if the destructor of Base is not virtual then only 'Base part' of cDerived will be destroyed by the call "delete rBase". But when cDerived goes out of scope destructor of Derived is called to take care of 'Derived part' of cDerived. Is my understanding correct?
I guess you forgot the dereference operator on line 11: Base *rBase = &cDerived;

delete rBase; This will invoke undefined behaviour for two reasons.
1. the object pointed to has automatic storage duration.
2. the base class destructor is not virtual.
Last edited on
Okay. So consider this snippet now:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Base{
//The destructor here is NOT virtual
};

class Derived: public Base{
//some code here
};

int main(){
Derived cDerived;
Base *rBase = &cDerived;
return 0;
}

Is anything wrong with this? What is the sequence of events that occurs w.r.t. calls to desrtuctors?
Last edited on
No nothing wrong. cDerived will be destructed at the end of the function. ~Derived() is called first followed by ~Base().
Thanks Peter87.
Topic archived. No new replies allowed.