0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

c++ > HOWTO: Covariant Return Types in C++ > clone()の例

0
Last updated at Posted at 2015-05-11

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.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?