• Home
  • Friend class and function in C++

Friend class and function in C++

In C++, a friend class is a class that has been granted access to the private and protected members of another class. The class that is granting access is called the “host” class, and the class that is receiving access is called the “friend” class.

Friend functions are functions that have been granted access to the private and protected members of a class. Like friend classes, the class that is granting access is called the “host” class, and the function that is receiving access is called the “friend” function.

Friend functions and classes are typically used in C++ when two or more classes need to collaborate closely with each other, and sharing data and functions between them would make the code more efficient and easier to read.

Here is an example of how to use a friend function in C++:

#include <iostream>

class HostClass {
private:
int data;

public:
HostClass(int d) : data(d) {}

friend int GetData(const HostClass& hc); // Declare friend function
};

int GetData(const HostClass& hc) { // Define friend function
return hc.data;
}

int main() {
HostClass hc(5);
std::cout << GetData(hc) << std::endl; // Output: 5
return 0;
}


In this example, the GetData function is a friend function of the HostClass, so it has access to the private member data. If GetData were not a friend function, it would not be able to access data, and the code would not compile.