friend
is a keyword in C++ that is used to share the information of a class that was previously hidden. For example, the private
members of a class are hidden from every other class and cannot be modified except through getters or setters. Similarly, the protected
members are hidden from all classes other than its children classes.
Although information hiding is encouraged because it prevents unwanted bugs in a program, there are cases where two classes need to frequently interact with each other. In such a scenario, one of the classes declares another to be its friend. The class declaring the friendship can now make all of its data available to its friend.
A class may make its data available for one specific function by using the friend
keyword. The function becomes a friend of that class.
Friendship is not bi-directional unless each class declares that the other is a friend.
#include <iostream>using namespace std;class A{private:int x;public:A(){cout << "New object created" << endl;x = 0;cout << "Value of x: " << x << endl;}// Class B can now access all of class A's data// but Class A cannot access class B's datafriend class B;};class B{private:A var;void dec(){cout << "Value decreased!" << endl;var.x--; // Modify private member of class Acout << "Value of x: " << var.x << endl;}public:void increase(){cout << "Value increased!" << endl;var.x++; // Modify private member of class Acout << "Value of x: " << var.x << endl;}// decrease() method can now access class B's datafriend void decrease();};void decrease(){cout << endl;B temp;// Access private function of class B:temp.dec();}int main() {// Use a friend class:B obj;obj.increase();obj.increase();// Use a friend function:decrease();return 0;}
Free Resources