开发者

What the C++ rules in regard to covariant return types?

Like in the example below, what is allowed, how and why?

class Shape {
      public:
        //...
        virtual Shape *clone() const = 0; // Prototype
        //...
    开发者_C百科};
    class Circle : public Shape {
      public:
        Circle *clone() const;
        //...
    };


C++ Standard 2003. 10.3.5

The return type of an overriding function shall be either identical to the return type of the overridden function or covariant with the classes of the functions. If a function D::f overrides a function B::f, the return types of the functions are covariant if they satisfy the following criteria:

— both are pointers to classes or references to classes

— the class in the return type of B::f is the same class as the class in the return type of D::f, or is an unambiguous and accessible direct or indirect base class of the class in the return type of D::f

— both pointers or references have the same cv-qualification and the class type in the return type of D::f has the same cv-qualification as or less cv-qualification than the class type in the return type of B::f.

If the return type of D::f differs from the return type of B::f, the class type in the return type of D::f shall be complete at the point of declaration of D::f or shall be the class type D. When the overriding function is called as the final overrider of the overridden function, its result is converted to the type returned by the (statically chosen) overridden function (5.2.2).

Example:

class B {};
class D : private B { friend class Derived; };
struct Base {
  virtual B*  vf4();
  virtual B*  vf5();
};
class A;
struct Derived : public Base {
  D* vf4();  // OK: returns pointer to derived class
  A* vf5();  // error: returns pointer to incomplete class
};


Pff, too long standard quoting.

You can use another type as covariant if (a) it is a pointer/reference (b) it can be casted to the prior return type by mere addition of a constant known at compilation time (c) it is compliant to all constant-volatile qualifiers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜