Virtual Destructor
-
What is the main advantage of Virtual destructor? Why don't we have virtual constructor when virtual destructor's are present? Please help regarding this 2 questions. Thanking you, Neelesh K J Jain.
-
What is the main advantage of Virtual destructor? Why don't we have virtual constructor when virtual destructor's are present? Please help regarding this 2 questions. Thanking you, Neelesh K J Jain.
-
What is the main advantage of Virtual destructor? Why don't we have virtual constructor when virtual destructor's are present? Please help regarding this 2 questions. Thanking you, Neelesh K J Jain.
Neelesh K J Jain wrote: What is the main advantage of Virtual destructor? Imagine you have one base class (CBase) and one derived class (CChild that inherits from CBase). Now look at this piece of code:
CBase* pPtr = new CChild; .... // Do things with pPtr.. ... delete pPtr;
Now, what would happens if the destructor wasn't virtual ? The only destructor that will be called is the destructor of the base class (pPtr is a pointer of type CBase*) and so your object may be not completelly cleaned. So, if you make your destructor virtual, the destructor of CChild will be called. Neelesh K J Jain wrote: Why don't we have virtual constructor when virtual destructor's are present? Because when you create an instance of an object (like in the piece of code before), you know exactly which kind of class (CChild or CBase) you want to create. In fact this line:CBase* pPtr = new CChild
can be explained as: first create an object of type CChild (the compiler knows exactly that he will need to call the constructor of CChild) and then store this pointer in pPtr. So, here, no need for virtual constructors... Hope this helps