friend is a keyword in c++. A friend class can access private and protected data members of the class in which it is declared as a friend. suppose A and B is two different classes. if we declare B as a friend class of A then, member functions of class B can access private data and protected data of class A.

#include<iostream>
using namespace std;

class B; // forward declaration

class A {
private:
	int a;
	friend B; // friend class of A
public:
	A() {
		a = 5;
	}
};

class B {
private:
	int b;
public:
	void add(A a_obj);
	B() {
		b = 6;
	}
};

void B::add(A a_obj) {
	cout << a_obj.a + b << endl;
}
int main() {
	B b_obj;
	A a_obj;
	b_obj.add(a_obj);

	return 0;
}

 

A function declared as a friend function inside a class , can access private and protected data members of that class. A member function of one class can be declared as a friend function of another class. Also a global member function can be declared as a friend function of a class.

Simple example of friend function which is a global and non member function.

#include<iostream>
using namespace std;

class A {
	friend void add(A&);
private:
	int a;
public:
	A() {
		a = 6;
	}
};

void add(A &obj) {
	cout << ++obj.a << endl;
}
int main() {
	A a_obj;
	add(a_obj);
	return 0;
}
Another example where one class member function declared as a friend in another class to access private data member.
#include<iostream>
using namespace std;

class A;

class B {
private:
	int b;
public:
	void init(A& a_obj);
};

class A {
private:
	int a;
public:
	void print();
	friend void B::init(A& a_obj);
};

void A::print() {
	cout << a << endl;
}

void B::init(A& a_obj) {
	a_obj.a = 5;
}

int main() {
	return 0;
}

 

Question on Friend function and classes in cpp ?

Some of the question asked in interview on friend function and friend class is important to practice, those are…

(1) Where to declare friend function or friend class inside another class?

The friend function or friend class can be declared anywhere inside the class i.e either in private or public section.

(2) can you give a case where friend function becomes necessary?

If we want to print object of user defined type by cout the we need to overload operator <<().

(3) How to use friend function to for overloading operator?

Ref:

http://en.cppreference.com/w/cpp/language/friend



Related Contents to follow