Goldman Sachs Interview Question
Software Engineer / Developersclass base
{
...
~base()
}
class derived:public base
{
int *p;
public:
~derived()
{
delete p;
}
};
main()
{
base *b = new derived;
delete b;
}
here b being a base pointer delete b calls base class destructor directly and gets itself deleted thereby never deleting the pointer p. for which memory is alloted during creation. to avoid this if base destructor is virtual. it acalls derived destructor and deletes p.
When you call delete BasePtr();, the destructor of the class which is pointed by BasePtr needs to be called. To acheive this, we need the destructor to be virtual.
- Ganesh December 01, 2008Without Virtual, the delete BasePtr() will call the class of type BasePtr.