
Originally Posted by
wysota
Correct me if I'm wrong but virtual destructor is needed only if you have some other methods declared as virtual. Lack of virtual methods doesn't prevent you from adding new methods.
virtual destructor is necessary if the class is intended to be a based class regardless the class itself has virtual methods or not. Otherwise they could be memory leak.
For instance, in the following code, B's dtor will not be called because A's dtor is not virtual. If you make A's dtor virtual, then the memory will be properly freed.
In java, you could add "final" keyword so no one can derive from A, but in C++ there is no such keyword...I guess this is one of C++'s weakness...
#include <iostream>
class A {
public:
~A() {
std::cout << "A::~A called" << std::endl;
}
};
class B : public A {
public:
~B() {
std::cout << "B::~B called" << std::endl;
}
};
int main()
{
A* a = new B;
delete a;
}
#include <iostream>
class A {
public:
~A() {
std::cout << "A::~A called" << std::endl;
}
};
class B : public A {
public:
~B() {
std::cout << "B::~B called" << std::endl;
}
};
int main()
{
A* a = new B;
delete a;
}
To copy to clipboard, switch view to plain text mode
Bookmarks