The destructors of Base
and Derived
will not be virtual
. To make a virtual
destructor you need to mark it up explicitly:
struct Base
{
virtual ~Base() {}
};
Actually there's now only one reason to use virtual destructors. That is to shut up the gcc warning: "class 'Base' has virtual functions but non-virtual destructor". As long as you always store your allocated objects in a shared_ptr
, then you really don't need a virtual destructor. Here's how:
#include <iostream> // cout, endl
#include <memory> // shared_ptr
#include <string> // string
struct Base
{
virtual std::string GetName() const = 0;
};
class Concrete : public Base
{
std::string GetName() const
{
return "Concrete";
}
};
int main()
{
std::shared_ptr<Base> b(new Concrete);
std::cout << b->GetName() << std::endl;
}
The shared_ptr
will clean up correctly, without the need for a virtual destructor. Remember, you will need to use the shared_ptr
though!
Good luck!