0

My question is pretty simple. I'm learning about friend functions, but this does not work for some reason. It only words if i swap the screen class with the Window_Mgr class, and then add a forward declaration of the screen class. Does it not work because screen doesn't know of the existence of "Relocate" at that point in time?

class Window_Mgr;
class screen
{
public:
    typedef string::size_type index;
    friend Window_Mgr& Window_Mgr::relocate(int, int, screen&);
private:
    int width, height;
};

class Window_Mgr
{
public:
    Window_Mgr& relocate(int r, int c, screen& s);
private:

};

Window_Mgr& Window_Mgr::relocate(int r, int c, screen& s)
{
    s.height=10;
    s.width=10;
};

int main(int argc, char* argv[])
{

    system("pause");
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Oliver
  • 111
  • 2
  • 10

2 Answers2

2

You have to define the class Window_Mgr BEFORE screen, because in your code the compiler cannot make sure that Window_Mgr really has a member function with name relocate, OR you are simply lying to it. The compiler parses the file from top to bottom, and on the way down, it's job is to make sure that every declaration is a fact, not lie!

Since relocate() takes a parameter of type screen&, you've to provide the forward declaration of screen instead!

With these fixes, (and along with other minor ones) this code compiles fine now (ignore the silly warnings).

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • Is it worth mentioning that this is distinctly different from non-member functions, in which case the `friend` declaration also serves as a function declaration, which it cannot do for member functions (for obvious reasons)? – JaredC Jan 18 '13 at 16:07
  • @JaredC: That is an interesting question. But it is not entirely different from non-member functions. The rule is more about *scope*, rather than member-ness of a function. I mean a friend from different namespace will have the same problem, e.g `friend void other_namespace::relocate(int, int, screen&);` is NOT a declaration. So if you have to provide the declaration before the class even in this case! – Nawaz Jan 18 '13 at 16:30
  • In the previous comment, I meant, *"[...] is NOT a **function** declaration."* It is a *friend* declaration though! – Nawaz Jan 18 '13 at 17:04
1

Yes, Window_Mgr::relocate is unknown at the time of the friend declaration. You have to define Window_Mgr beforehand.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625