Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Confusion between this and *this on website -- possible error

0 views
Skip to first unread message

paulde...@att.net

unread,
Mar 29, 2009, 8:06:41 PM3/29/09
to
Below is pasted from a website:

QUOTE BEGINS HERE

HOWTO: Covariant Return Types in C++
20060406T0140

Covariant return types are a useful feature of the C++ language that
could save you from doing some extra, unnecessary work in a few com
mon situations. They can also make the intended purpose of your
functions more clear. This HOWTO explains what they are, how to use
them, a nd gives some common sample applications.

Consider a simple inheritance hierarchy such as that shown here:

Base
|
v
Derived

Often, the derived class has a polymorphic function which returns a
more specific (i.e. more derived) type than the base class. This is
per fectly legal, since the pointer is automatically downcast to the
base class type.

A common use of this (but by no means the only one) is a clone()
method:

class Base {
public:
virtual Base* clone() const
{
return new Base(this);
}
};

class Derived : public Base {
public:
virtual Base* clone() const
{
return new Derived(this);
}
};

QUOTE ENDS HERE

I would expect to see new Derived(*this) and
new Base(*this)


Is the website in error or am I in error?

Thank you,

Paul Epstein

Alf P. Steinbach

unread,
Mar 29, 2009, 8:53:09 PM3/29/09
to
* paulde...@att.net:

Right.


> Is the website in error or am I in error?

The website.

Also the use of the word "downcast" is incorrect and so harebrained that one
suspects the above of being from Microsoft's documentation.

Checking...

No, not Microsoft. But anyways, the author got the "up" and "down" directions
wrong (in C++ "up" is towards Base, "down" is towards Derived).

However, in the author's defense, even Donald Knuth once got the "up" and "down"
directions wrong for drawing tree structures (but in fairness, the convention of
root up was not firmly established when Knuth first wrote the first tome of
TAOCP), and the 'this' instead of '*this' could be a repeato-typo thing.


Cheers & hth.,

- Alf

--
Due to hosting requirements I need visits to <url: http://alfps.izfree.com/>.
No ads, and there is some C++ stuff! :-) Just going there is good. Linking
to it is even better! Thanks in advance!

red floyd

unread,
Mar 29, 2009, 9:56:30 PM3/29/09
to

On top of that, they're not even showing covariant return types.
They're showing simple virtual overriding.

It should be:

class Derived : public Base {
public:

virtual Derived* clone() const
{
return new Derived(*this);
}
};

0 new messages