Search code examples
c++friend

How to add class friends on different files headers?


My class Bloque is a friend of my other class user and i want to pass an int y of my user class to a function called void colision() on my Bloque class.

So I tried this:

# user.h #

class user
{
    private:
        int y;
    friend class Bloque;
};

# bloque.h #

class user;
class Bloque
{
    public:
        void mover();
        void colision(user& f);
};

# bloque.cpp # 

#include "user.h"
#include "bloque.h"
#include <iostream>

void Bloque::mover(){ colision(user& f); }

void Bloque::colision(user& f){ cout << f.y; }

When i try to compile it, i get two errors:

In member function 'void Bloque::mover()':
bloque.cpp [Error] expected primary-expression before '&' token
bloque.cpp [Error] 'f' was not declared in this scope
Makefile.win    recipe for target 'bloque.o' failed```

Solution

  • Your forward declaration looks correct.

    The problem is in this line:

    void Bloque::mover() { 
       colision(user& f); 
    }
    

    Your variable f does not exist. I don't understand what you are trying to do exactly. If you are planning to call Bloque::colision with a variable of user type you should first declare it:

    void Bloque::mover() { 
       user us;
       colision(us); 
    }