Template overriding base class virtual function?
I'm trying to write something like a clone() method using the curiously
recurring template pattern. What I'm doing is similar to what's
described here:
http://nerdland.net/2009/06/covariant-templatized-virtual-copy-constructors/
but simpler, since I'm not worried about covariance. My clone() method
will always return a Base*. So I have something like
class Base
{
Base(){}
Base(const Base& other){}
virtual Base* clone(){Base b = new Base(); return b;}
};
// This template defines a clone() method with the same signature
// as the one in Base.
template <typename D> class Cloneable
{
public:
virtual Base* clone() {Base b = new D(this); return b;}
};
// I think by inheriting from Cloneable, the clone() method in
// Cloneable() should override the one in Base. But it doesn't.
class Derived : public Base, public Cloneable<Derived>
{
Derived() : Base() {}
Derived(const Derived& other) : Base(other) {}
}
When built with Visual Studio 2008, at least, the debugger shows me that
it's the Base::clone() function that always gets called, instead of the
one derived from Cloneable.
If I make both Base and Cloneable be virtual base classes, this works,
but I don't understand why this is necessary. Why doesn't the template
just override the Base definition of clone()?
Thanks!
-pd
--
----
The Tech Curmudgeon
http://www.techcurmudgeon.com