Error when using data-member of a class inside a friend function defined in another class

37 views Asked by At

So, here I have two classes, one has the friend function definition and the other a private data member. I want to access the private data member with the friend member function but it gives me an error in the part: obj->x inside the friend member function, it says that the 'x' data member is declared after the friend function, and I can't use it, but I already put the forward declaration, so I am lost.

Here the code:

class cl2; // Forward declaration

class cl1 {
   int y;
   public:
   cl1(int num){ y = num; }
   void setx(cl2 *obj, int num) { obj->x = num; } // friend function definition, here is the error.
};

class cl2 {
   int x;
   public:
   cl2(int num){ x = num; }
   friend void cl1::setx(cl2 *obj, int num);
   int getx() { return x; }
};

int main() {

   cl2 objcl2(2);
   cl1 objcl1(1);
   objcl1.setx(&objcl2, 20);

   cout << objcl2.getx() << "\n\n";


   system("pause");
   return 0;
}

I tried to declare cl2 class before cl1. I changed the way of accessing 'x'. I used a reference (&) and a pointer (*).

0

There are 0 answers