[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[lmi] Forward declaration preceding friend declaration

From: Greg Chicares
Subject: [lmi] Forward declaration preceding friend declaration
Date: Sat, 10 Mar 2007 14:26:27 +0000
User-agent: Thunderbird (Windows/20060516)

A friend declaration can be written for a class that has not
yet been declared. Existing code does this:
  grep 'friend class .*_*[Tt]est' *.?pp
and so do the examples in C++03 11.4/2 . This is allowed by for the form 'friend class-key ::opt identifier ;'.
See also 11.4/9: "For a friend class declaration, if there is no
prior declaration,..."; see 'rtti_lmi.hpp' for an example that
requires a forward declaration because of the part I elided
(and note that g++ would diagnose its absence).

On 20070310T1254Z I removed a forward declaration to conform to
that existing practice. I wouldn't expect anyone else to have
noticed that, and I don't think I've ever seen a guideline about
this in any coding standard. I'm not even sure which way is
better; I mostly want uniformity because that helps me read the
code. But...which way is better?

(1) Always declare a class before befriending it, adding a
forward declaration if its full declaration isn't otherwise

(2) Never forward declare a class just to befriend it unless
a really good compiler (g++ or EDG) requires you to.

John Potter, in article <address@hidden>,
suggested (1). I think he was saying, though, that (in 1999)
we couldn't rely on a compiler like g++ to diagnose erroneous
usage, so we needed to inculcate a habit like this in order to
avoid writing incorrect code. These days, however, I haven't
seen EDG require a forward declaration where g++ didn't.

Martin Fabian, in article <address@hidden>,
presents this counterpoint:
| >Put the function
| >declaration ahead of the class that makes it a friend.
| But think about whether you really want to do that. In some cases the
| friend is just there as a helper, and then you may not want to make
| (pointers/refs) to this class available to the user, nor do you want to
| nest it within its friend.

In this day and age, I tend to think (2) is better. Less is more:
a forward declaration that isn't written doesn't need to be read
or maintained; if deleting a line doesn't change the meaning of
the program or make it less clear, then delete that line. We have
tools (g++, e.g.) that will tell us whenever we need to add a
forward declaration. But no tool will warn us when we fail to
write a redundant forward declaration as (1) would require.

Feel free, of course, to present any different point of view.

reply via email to

[Prev in Thread] Current Thread [Next in Thread]