Virtual Destructors
-
Hello Friends, What's is the main advantage of having virutal destructors? Why don't we have virtual constructor? Thanks in advance. Neelesh K J Jain.
-
Hello Friends, What's is the main advantage of having virutal destructors? Why don't we have virtual constructor? Thanks in advance. Neelesh K J Jain.
That's a good question :). In fact if we don't need virtual constructor, it's because when you instanciate your pointer, you ALWAYS know what class you instanciate. So take the example of one base class (CBase) and one child class (CChild). If you have an uninstancied pointer to the base class:
CBase* pPointer;
If you instanciate it into a child class:pPointer = new CChild;
the compiler knows exactly that you want to create a child class (first the compiler creates a child class and then it stores the pointer into the uninstancied pointer). So know you've done a lot of things with this pointer and you want to destroy it:delete pPointer;
The compiler just knows that the pointer is from type CBase (that's how it has been declared) without knowing that it has been instancied as a child class. So, in this case your destructor must be virtual so that the compiler will call the destructor of your child class and not from the base class. Hope this helps -
Hello Friends, What's is the main advantage of having virutal destructors? Why don't we have virtual constructor? Thanks in advance. Neelesh K J Jain.
I like this question. The other posting did a good job of explaining why the virtual destructor is needed. The reason you don't need a virtual constructor is that you are specifically telling the compiler what you want to instantiate. You write int i = 10; CBase* pPointer; pPointer = new CChild(i); The concept of virtual functions is also described as dynamic run time binding. So the idea is that you call a function on the fully instantiated object and the system is smart enough to realize that since a function is virtual, the child class version of the function is called first. Then the child class can execute it's own code and may or may not ivoke the base class version of the function as well. So virtual functions don't make sense during the construction process. The child class has to call the constructor for the base class from within it's own constructor. Once the construction of the class is complete, you can use the base class pointer to call virtual functions. If you tried to call any virtual functions from either of the constructors, I'm not sure what would really happen. I wouldn't recommend trying this as it really makes no sense. Seems like it would be an undefined operation that may or may not cause a crash. Shawn