TITLE: covariant return types (Source: comp.lang.c++.moderated, 25 Sep 2000) [ Sample code added for illustration... class B { public: virtual B* clone (); }; class D : public B { public: virtual D* clone (); // Note return type is a D*, not a B* }; ] BERRY: "Hiram Berry" [snip] > I have to conclude then that covariance provides nothing > more than a shorthand mechanism for avoiding a dynamic_cast, > ie. it provides no new functionality. HYSLOP: Absolutely correct. BERRY: > > > In this case, is the covariant return pointer equivalent to a > > > Derived * in all ways? HUNSINGER: Ron Hunsinger [ Base *d = new Derived; Derived *e = d->clone(); ] > > No. In the code you've written above, the covariant return pointer > > has the wrong static type. BERRY: > Right. What confused me was the assertion by several posters in this > thread > and its mirror in c.l.c++ that covariance was essentially returning a > derived class pointer or reference in an overridden function. As it > turns > out that isn't really a good way of thinking of it because of the > issue of > the static type of the caller that you raised. Thanks for your > explanation. HYSLOP: Jim Hyslop Well, actually that's what it is. Here's how the standard defines it: "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 direct or indirect base class of the class in the return type of D::f and is accessible in D - 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." So the assertion is correct - covariant return types means that a derived class returns a pointer/reference to a class derived from the base class's return type. Note, by the way, that covariant return types can apply to parallel heirarchies, as in: class X { }; class A // NOTE: NOT derived from X { public: X * f(); }; //////////////////////////// class Y : public X { }; class B : public A { public: Y * f(); // OK, Y is derived from X }; _______________________________________________ cpptips mailing list http://cpptips.hyperformix.com