Friend Function in C++
Friend Function in C++
Similarly, protected members can only be accessed by derived classes and are
inaccessible from outside. For example,
class MyClass
{
private:
int member1;
}
int main()
{
MyClass obj;
// Error! Cannot access private members from here.
obj.member1 = 5;
}
However, there is a feature in C++ called friend functions that break this rule and
allow us to access member functions from outside the class.
A friend function can access the private and protected data of a class. We declare
a friend function using the friend keyword inside the body of the class.
class className
... .. ...
... .. ...
#include <iostream>
class Distance {
private:
int meter;
// friend function
public:
Distance() : meter(0) {}
};
int addFive(Distance d) {
d.meter += 5;
return d.meter;
int main() {
Distance D;
return 0;
Output
Distance: 5
Here, addFive() is a friend function that can access both private and public data
members.
Though this example gives us an idea about the concept of a friend function, it
doesn't show any meaningful use.
#include <iostream>
using namespace std;
// forward declaration
class ClassB;
class ClassA {
public:
// constructor to initialize numA to 12
ClassA() : numA(12) {}
private:
int numA;
class ClassB {
public:
// constructor to initialize numB to 1
ClassB() : numB(1) {}
private:
int numB;
int main() {
ClassA objectA;
ClassB objectB;
cout << "Sum: " << add(objectA, objectB);
return 0;
}
Output
Sum: 13
In this program, ClassA and ClassB have declared add() as a friend function.
Thus, this function can access private data of both classes.
One thing to notice here is the friend function inside ClassA is using the ClassB.
However, we haven't defined ClassB at this point.
// inside classA
friend int add(ClassA, ClassB);
Since ClassB is a friend class, we can access all members of ClassA from inside
ClassB.
#include <iostream>
using namespace std;
// forward declaration
class ClassB;
class ClassA {
private:
int numA;
public:
// constructor to initialize numA to 12
ClassA() : numA(12) {}
};
class ClassB {
private:
int numB;
public:
// constructor to initialize numB to 1
ClassB() : numB(1) {}
int main() {
ClassB objectB;
cout << "Sum: " << objectB.add();
return 0;
}
Output
Sum: 13
Here, ClassB is a friend class of ClassA. So, ClassB has access to the members
of classA.
In ClassB, we have created a function add() that returns the sum of numA and
numB.
Since ClassB is a friend class, we can create objects of ClassA inside of ClassB.