Search code examples
c++friend

Not able to understand why friend function is not working


#include<iostream>
using namespace std;

class A;
void test(A &a);
class A
{
    private:
        int x;
        int y;
        friend void test();
};
void test(A &a)
{
    a.x = 1;
    a.y = 2;
    cout << a.x << " " << a.y << endl;
}
int main()
{
    A a;
    test(a);
}

The errors I am getting are as follows-

1.error: ‘int A::x’ is private within this context

2.error: ‘int A::y’ is private within this context

Aren't friend functions supposed to be able to modify private members of a class?


Solution

  • #include <iostream>
    using namespace std;
    
    class A { 
      private: 
        int x; 
        int y; 
    
      public: 
        friend void test(A &); 
    };
    
    void test(A &a) { 
      a.x=1; 
      a.y=2; 
      cout << a.x << " " << a.y << endl; 
    }
    
    int main() { 
      A a; 
      test(a); 
    }