Why Friend Class is not working? Remove Errors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;

class a{
	friend class b;
public:
	//public members...
private:
	int a_mem;
};

class b{
public:
	int get_member_of_class_a(){
		return a_mem; //Since b is a friend of a so b should have access 
//to private members of a
	}
	void set_member_of_class_a(int value){
		a_mem = value;
	}
private:
	//private members...
};

int main(){
	b obj;
	obj.set_member_of_class_a(5);
	cout << obj.get_member_of_class_a() << endl;
	return 0;
}
Each instance of class a has its own version of a_mem, so you can't access it like you do now in get_member_of_class_a(). You should pass an instance of a to that function, and then return the a_mem of that instance:
1
2
3
4
int get_member_of_class_a( a& instance_of_a )
{
    return ( instance_of_a.a_mem );
}
Last edited on
To expand on what Fransje said - if class b is a friend of class a, then that means that objects of type b can access the private members of objects of type a. But there still needs to be an actual object of type a for it to access - and in the code you've posted, there isn't.
- Lol, he actually didn't instantiate an object of type "a" at all...
Thanks to Fransje, MikeyBoy and thejman.
Topic archived. No new replies allowed.