They do - for example:
class test_interface
{
public:
virtual ~test_interface() {}
};
class A : public test_interface
{
public:
virtual ~A() { std::cout << "Running A's destructor..." << std::endl; }
};
class B : public test_interface
{
public:
virtual ~B() { std::cout << "Running B's destructor..." << std::endl; }
};
int main()
{
test_interface *pA = new A;
test_interface *pB = new B;
delete pA;
delete pB;
}
If you remove the virtual from the base class destructor's declaration the output will stop (although exactly what happens is undefined, should have pointed that out).
Cheers,
Ash
PS in response to the comment below...
Well as Sauro's pointed out to create an object of a class you really need to know what type the object is going to be before you can create it. However... you don't always need to know the type of the object you're creating. For example you might want to be able to polymorphically copy objects without knowing what concrete type they are, e.g:
void A::cache_companion( companion_interface *ci )
{
}
So how can you get around that? Well the first thing is you define a polymorphic copy member of the interface:
class companion_interface
{
public:
virtual companion_interface *polymorphic_copy() const = 0;
};
You can then implement it:
class implemented_interface : public companion_interface
{
public:
virtual implemented_interface *polymorphic_copy() const
{
return new implemented_interface( *this );
}
};
You can then complete the code from earlier:
void A::cache_companion( companion_interface *ci )
{
cached_interface_ = ci->polymorphic_copy();
}
So C++ does support virtual constructors, just not directly and only in the cases where the type of the object being constructed can be decoupled from the thing doing the construction. This technique works because objects always know their own class even if they can't tell anyone else what it is in a meaningful way.