friend declarations and scope
Code:
class myClass;
class otherClass {
public:
otherClass(int x): valor(x) {}
inline int sum(myClass &obj);
private:
int valor;
};
class myClass {
public:
myClass(int x): val(x) {}
friend otherClass::sum(myClass&);
private:
int val;
};
inline int otherClass::sum(myClass &obj) {
return obj.val + valor;
}
The code serves only to ilustrate my question.
I believe C++ Primer (Lippman and others) fails miserably when explaining friend function declarations. A small glitch, I'm sure, on an otherwise awsome book. Or maybe I'm not following this rather small section correctly. But while it explains to:
- Define the function only after the class granting friendship is defined.
- Define the friend class before the class granting friendship is defined.
However, it didn't mention that obviously the function declaration in otherClass presents myClass. And that name can't possibly be in scope yet because I'm forced to only declare it later.
Previous chapters taught me well enough and so it wasn't hard for me to understand all I needed to do was to declare myClass (not define it) and thus introduce it to the scope. The code now compiles and executes correctly when tested.
My question is though (since i'm not used to C++ Primer containing flaws), is this the correct way? Or am I missing something here?