This question may sound too stupid, but I can’t find a specific answer anywhere.
With a little knowledge of how late binding works and the virtual keyword used in inheritance.
As in the code example, when in the case of inheritance, when the base class pointer is used to free memory, it points to the object of the derived class created during the heap and delete operation, the derivative and base destructor will be called in the order when the base destructor is declared as a virtual function.
Now my question is:
1) When the base destructor is not virtual, why the problem of not invoking dtor derivatives occurs only when, in the case of using the delete operator, why not in the case indicated below:
derived drvd;
base *bPtr;
bPtr = &drvd; //DTOR called in proper order when goes out of scope.
2) When "delete" operator is used, who is reponsible to call the destructor of the class? The operator delete will have an implementation to call the DTOR ? or complier writes some extra stuff ? If the operator has the implementation then how does it looks like , [I need sample code how this would have been implemented].
3) If virtual keyword is used in this example, how does operator delete now know which DTOR to call?
Fundamentaly i want to know who calls the dtor of the class when delete is used.
<h1> Sample Code </h1>
class base
{
public:
base(){
cout<<"Base CTOR called"<<endl;
}
virtual ~base(){
cout<<"Base DTOR called"<<endl;
}
};
class derived:public base
{
public:
derived(){
cout<<"Derived CTOR called"<<endl;
}
~derived(){
cout<<"Derived DTOR called"<<endl;
}
};
, , .
int main()
{ base * bPtr = new ();
delete bPtr;// only when you explicitly try to delete an object
return 0;
} Code>