Oliver
Oliver

Reputation: 111

C++ friend functions

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");
}

Upvotes: 0

Views: 221

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361762

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).

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258648

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

Upvotes: 1

Related Questions