Need a project done?

C++ Programming Developer

Search This Blog

Friend Class C++


#include <iostream>
using namespace std;

class a{
friend class b;//a has granted friendship to b.
public:
//public members...
private:
int a_mem;
};

class b{
public:
int get_member_of_class_a(a &instance_of_a){
return instance_of_a.a_mem; //Since b is a friend of a so b should have access
//to all members of class a's objects.
//Without using friend statement in class a, we cannot access private member of class 'a' in class 'b' using object.private_member.
}
void set_member_of_class_a(a& instance_of_a,int value){
instance_of_a.a_mem = value;
}
private:
//private members...
};

int main(){
b obj_b;
a obj_a;
cout << "We access class a's private member through class b << endl:
obj_b.set_member_of_class_a(obj_a,5);
cout << obj_b.get_member_of_class_a(obj_a) << endl;
return 0;
}
"Don't let anyone ever make you feel like you don't deserve what you want."