Tuesday, March 30, 2010

virtual destructor purpose

Que: If there is a single virtual function in a class, one of the function of that class shold be virtual. what is that function?
Ans: Destructor

purpose of virtual destructor:

We know that, virtual destructor will help to call correct Version of destructor in dynamic binding.


class Base
{
private:
int x;
public:
virtual int getValue() {return x;}
};

class Derived : public Base
{
private:
int y;
public:
int getValue() {return y;}
};

int main()
{
Base* b = new Der();
delete b;
}


In the above program, do we need a virtual destructor?

No, we don't need a virtual destructor in the above program.
Here, there is no problem in deleting delete b;


suppose the Derived class is some thing like this

class Derived : public Base
{
private:
int y;
int* p;
public:
int getValue() {return y;}
};

then the problem will occur. What is this problem.

The problem is ....

Assume that you have allotted memory for "int *p" and the destructor is not virutal
in the case Base* pb = new Derived( );. The destructor of base class gets called
and there is no way we can free the memory allotted for p inside derived.
So, a memory leak.

Yes, to avoid memory leaks we have to use virtual destructor.

Not only for memory leaks, but also used to releasing Filehandles/resources and unlocking mutexes.

No comments: