[comp.lang.c++] difference between friend and static member function

cok@islsun.Kodak.COM (David Cok) (02/27/91)

One use of friend declarations is to allow members of other classes (or entire
other classes) access to the internals of a given class.  Aside from that use,

	what can one do with friend functions that one cannot do with
		*static* member functions?

1) static member functions will have conversions applied to all arguments,
just like friends.

2) static member functions can be declared private; friends cannot.  This makes
static members better for functions which are not really part of the interface
but are needed for the implementation (and non-static members are not wanted).

3) static members must be accessed using the class::fcn notation (or using
a dummy object); friends can be called directly.

BUT

4) The compiler (Sun C++ 2.0 on a SparcStation) complains about

	static myclass operator+(myclass,myclass)

saying
	error:  myclass::operator +() must take 0 or 1 arguments

This seems to me to be a bug since there is no implied this argument for a 
static member.  Right or wrong?


Except for the problem in 4 (which only applies to operators) and the 
difference in syntax in 3, it seems friends could generally be replaced by
static members.  Any comments?

David R. Cok
Eastman Kodak Company
cok@Kodak.COM

wmm@world.std.com (William M Miller) (02/28/91)

cok@islsun.Kodak.COM (David Cok) writes:
> 4) The compiler (Sun C++ 2.0 on a SparcStation) complains about
>
>         static myclass operator+(myclass,myclass)
>
> saying
>         error:  myclass::operator +() must take 0 or 1 arguments
>
> This seems to me to be a bug since there is no implied this argument for a
> static member.  Right or wrong?

E&S section 13.4.2, page 333, says: "A binary operator may be declared
either by a nonstatic member function (section 9.3) taking one argument or
by a nonmember function taking two arguments."  (A similar passage in 13.4.1
deals with unary prefix operators.)  There's no provision for static member
functions to be used for operator overloading.  The compiler was correct to
reject the declaration.

To understand why, think about the definitions of operator member functions
and static member functions.  An expression "a + b," where "a" is an object
of a class with a member operator+(), is, by definition, equivalent to
"a.operator+(b)."  However, if a static member function is invoked using the
member selection syntax "a.smf()," the expression on the left side of the
"." is not evaluated (E&S section 9.4, page 180).  That's clearly not what
you want to happen with operators.

Obviously the rules could be rewritten to make static operator member
functions behave differently from ordinary static member functions, but it's
not clear, at least to me, whether it's worth changing.

-- William M. Miller, Glockenspiel, Ltd.
   wmm@world.std.com