I am trying to decipher the following paragraph from chapter 11.5.1 of Bjarne Stroustrup's The C++ Programming Language:
"A friend class must be previously declared in an enclosing scope or defined in the non-class scope immediately enclosing the class that is declaring it a friend. Scopes outside the innermost enclosing namespace scope are not considered."
The following compliles and runs fine with Code::Blocks GCC, so I presume that the word "previously" relates only to "declared" and not to "defined", since the definition of class Y comes after that of class X:
Likewise, the following compliles and runs fine with the same compiler, so I presume the second sentence relates only to definition and not to declaration, since the declaration of class Y is outside the innermost enclosing namespace and yet it is evidently being considered:Code:#include <iostream>
using namespace std;
namespace out
{
class X
{
int i;
public:
X(int j = 0):i(j){}
friend class Y;
};
class Y
{
public:
void f(X x){cout << x.i;}
};
}
int main()
{
out::X x(101);
out::Y y;
y.f(x);
}
To sum up, I would interpret the text to mean the following:Code:#include <iostream>
using namespace std;
class Y;
namespace out
{
class X
{
int i;
public:
X(int j = 0):i(j){}
friend class Y;
};
}
class Y
{
public:
void f(out::X x){cout << x.i;}
};
int main()
{
out::X x(101);
Y y;
y.f(x);
}
A friend class must be declared previously in an enclosing scope or defined somewhere in the non-class scope immediately enclosing the class that is declaring it a friend. In the latter case, scopes outside the innermost namespace scope or not considered.
Is that right?