Virtual destructors?
Whats teh difference between a Virtual Destructor and a normal one?
Tomoso
#include <iostream>class CBase{public: virtual ~CBase() { std::cout << "base class" << std::endl; }};class CSub: public CBase{public: ~CSub() { std::cout << "Dying now" << std::endl; }};int main(){ CBase* x = new CSub; delete x; return 0;}
versus
#include <iostream>class CBase{public: ~CBase() { std::cout << "base class" << std::endl; }};class CSub: public CBase{public: ~CSub() { std::cout << "Never shown" << std::endl; }};int main(){ CBase* x = new CSub; delete x; return 0;};
The first one will correctly kill the sub-class because the destructor is virtual, so it can be polymorphic. The second one won't resulting in possible memory leaks (only the CBase destructor will be called - there's no polymorphism, so it sees x as a CBase rather than a CSub class, since that's what it's a pointer to initially).
If you expect the base class to be derived from then use a virtual destructor. The virtual destructor will behave polymorphically when required, which is rather handy.
[edited by - Alimonster on January 4, 2003 6:47:47 PM]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement