I have a simple question. As far as I know, if the variable scope ends, the variable is destroyed. But in the below situation, even if Derived is destroyed, the base pointer still calls the virtual function of the derived. Is it plain luck, or the Derived object will actually not be destroyed until all references/ pointers to Derived are not destroyed?
int main(int argc, char **argv) {
Base *base_ptr;
std::string value = "hello";
if ( value == "hello")
{
Derived der1;
base_ptr = &der1;
}
else {
DerivedNew der_new;
base_ptr = &der_new;
}
base_ptr->printDerived();
// this prints the virtual function of the derived object. I was hoping it to print the base object.
}