Search code examples
c++friend

How to make non-member function from one file friend with class in other file?


Lets say I have one file

// X.h (first file)

#include <iostream>
class X{
    int x;
public:
    X(int i);
    void print_me();
};

// X.cpp (second file)

#include "X.h"
X::X(int i){x = i}

void X::print_me(){std::cout<< x << endl;}

// main.cpp (third file)

#include "X.h"

void swap(int lhs, int rhs){
  // do the swap
}

class Y{
   X x_obj;
public: 
    friend void swap(Y& lhs, Y& rhs){
        swap(lhs.x_obj.x, rhs.x_obj.x);
    }

};
int main(){return 0;}

My question is: How can I make class Y in main.cpp a friend of X?

I was thinking of breaking class Y into .h and .cpp file and including Y.h file into X.h and go from there. Is there any way other then that. I mean in the current condition of the code to make Y a friend of X:

The error I am getting in current condition is :

> In file included from main.cpp:1:0: X.h: In function 'void swap(Y&,
> Y&)': X.h:3:9: error: 'int X::x' is private
>      int x;
>          ^ main.cpp:12:24: error: within this context
>          swap(lhs.x_obj.x, rhs.x_obj.x);
>                         ^ In file included from main.cpp:1:0: X.h:3:9: error: 'int X::x' is private
>      int x;
>          ^ main.cpp:12:37: error: within this context
>          swap(lhs.x_obj.x, rhs.x_obj.x);

Solution

  • My question is: How can I make class Y in main.cpp a friend of X?

    Making Y the friend of X won't solve this issue. You need to make the function swap() friend of class X since it's trying to access the private members of X.

    class Y; // forward declaration to avoid circular dependencies
    class X{
        friend void swap(Y& lhs, Y& rhs);
        ...
    };
    

    Note you should use forward declaration to avoid including Y.h into X.h, which leads to circular dependency issue.