Bloomberg LP Interview Question
Software Engineer / DevelopersI completely agree with this statement :" It is a good programming practice to keep the destructor virtual if your base class has any virtual function that is overridden in derived class."
But as far as I know virtual function are implemented using vTable which is late binding. and should be implemented on heap. So there is no question of having virtual function.
Also the last sentence is bit confusing. Could you please clarify it.
If base class or derived class object is not created dynamically then there is no need for virtual destructor......
run following code:
class Base{
public:
~Base(){cout<<"Base::~Base()"<<endl;}
};
class Derived:public Base{
public:
~Derived(){cout<<"Derived::~Derived()"<<endl;}
};
int main(){
Derived d;
Base* p = new Derived;
delete p;
cout<<"======="<<endl;
}
Derived object created on stack, Derived, Base destructor will be called in order
However, Derived object created on heap, the behavior is UNDEFINED! Therefore, even no members that are allocated on heap, and none virtual destructor for Base works fine on your machine and compiler, you cannot guarantee it works correctly on other machine and compiler.
Say there is an static data member "counter" in Derived d, and the destructor of Derived will run "counter--". when you delete the d using Base*, the destructor of d will not be called, so "counter--" is not executed. I believe that's the reason why virtual dctor should be used even if nothing is on heap.
..."members that are allocated on heap" are not the only resources one must free up properly in a destructors. Graphoical resources, n/w (e.g. open sockets), mutexes etc: why do you for get ab. all these?
if we are assured of that there will be no use of heap then we should go for no-virtual destructor because using virtual destructor will cause an extra vtbl pointer in the object which do not have any need in this situation except that it will increase the processor instruction and pollute cahce.
It is a good programming practice to keep the destructor virtual if your base class has any virtual function that is overridden in derived class.
- Harish March 17, 2010Yes I do believe that there is need to keep the destructor virtual in the above when you have not allocated anything on the heap. Bcos objects on heap would clean up on its when when the derived class goes out of scope