Topic: Friend Functions
Author: Ross Dargahi <rossd@bcm.tmc.edu>
Date: 30 Sep 1994 21:54:11 GMT Raw View
Consider the following:
File1.h
------
class A
{
static friend void foo(A&);
int x;
}
File1.cpp
--------
#include <file1.h>
void publicMethod1(A&);
void publicMethod2(A&);
main()
{
A a;
publicMethod1(a);
publicMethod2(a);
return 0;
}
FIle2.cpp
--------
#include <file1.h>
#include <iostream.h>
static void foo(A& a)
{
a.x = 99;
cout << a.x << endl;
}
void publicMethod1(A& a)
{
foo(a);
}
FIle3.cpp
--------
#include <file1.h>
#include <iostream.h>
static void foo(A& a)
{
a.x = 11;
cout << a.x << endl;
}
void publicMethod2(A& a)
{
foo(a);
}
I discovered that the Sparc C++ compiler (v4) permits this code and
results
in the following output:
99
11
The Borland C++ compiler complains about the the static friend foo
declaration
saying that storage class static is not allowed with a friend declaration.
Looking at the grammar in the ARM it seems that the code is syntactically
correct (p. 395, assuming dec-specifiers[opt] for member-declarations
is included in the language :-)
Unfortunately p. 251 of the ARM has an example on the lower
half of the page which seems to imply that static friend should
be illegal (At least that is how it appears to me)
An interesting side effect with the Sun compiler is that a static friend
foo declaration
permits multiply defined foo's within different file scopes, thus
allowing one to
effectively write foo's that tamper with class A.
Finally when using the Sparc compiler, if one were to have static foo's
and
one were to remove the static from the friend declaration, then the
compiler
complains that foo was perviously declared as extern (which seems
reasonable to me)
My question is which compiler is right - what does the proposed standard
have to say
about this, or is it one of those implementation dependent items?
Cheers
Ross