http://www.lwithers.me.uk/articles/covariant.html
から抜粋
Derived* d = new Derived;
Base* b = d->clone();
Derived* d2 = dynamic_cast<Derived*>(b);
if(!d2) {
delete b;
throw SomeCrazyException();
}
As you can see, this is pretty long-winded given that we know d2 should be a Derived instance.
If, instead, the clone() method could tell the compiler "actually, I always return a Derived*" (i.e. it became virtual Derived* Derived::clone() we could do away with the upcast and the check, moving all this away from run-time and into compile-time:
Derived* d = new Derived;
Derived* d2 = d->clone();
This is the ideal solution; there is no run-time cost associated with it, and it's completely safe: the compiler will check all our types for us. If somebody changes Derived::clone() to return a Base*, the compiler will complain;
続きがある
Fortunately, a language feature does exist to do this: covariant return types.