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.
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?