All About C++ Friend Function

All About C++ Friend Function

4 mins read1.6K Views Comment
Updated on Aug 5, 2024 11:10 IST

Friend function in C++ is a non-member function of a class. It is defined outside the class scope, but it does have access to a private data member of that class.

Data hiding is one of the fundamental concepts of object-oriented programming. It explains how private members of a class are restricted from being accessed outside the class. Similarly, protected members of a class can only be accessed by its derived classes and are inaccessible to other classes. 

However, C++ has a concept of friends that allows us to access member functions from outside a given class. Through this article, we will try to learn how this happens. 

Table of Content

Recommended online courses

Best-suited C++ courses for you

Learn C++ with these high-rated online courses

โ€“ / โ€“
4 months
โ‚น4.24 K
6 weeks
โ€“ / โ€“
15 days
โ€“ / โ€“
โ€“ / โ€“
โ€“ / โ€“
70 hours
โ€“ / โ€“
3 months
โ‚น7.14 K
5 weeks
name
SoloLearnCertificateStar Icon4.5
Free
โ€“ / โ€“
โ€“ / โ€“
4 months
โ€“ / โ€“
3 months

What is Friend Function in C++?

A friend function of a class is a function defined outside the scope of the class that can access all of the private and protected members of that class. Friends are not member functions, even though the prototypes for friend functions can be found in the class definition. A friend can either be a function, function template, or member function.

A friend can also be a class or class template, in which case the friend class can access both private and protected members of another class in which it is declared as a friend. 

To declare a function as a friend of a class, the function prototype in the class definition has to be preceded by the keyword friend, as shown below.

class className {
    // ...

    friend returnType functionName(arguments);
    
    // ...
};

Explore C++ courses

Working of a Friend Function in C++

Example 1


 
#include <iostream>
using namespace std;
class Length {
private:
int meters;
// friend function
friend int addFive(Length);
public:
Length() : meters(3) {}
};
// Friend function definition
int addFive(Length l) {
// Accessing the private members using the friend function
l.meters += 5;
return l.meters;
}
int main() {
Length len;
cout << "Length is given as: " << addFive(len) << endl;
return 0;
}
Copy code

Output 1

Length is given as: 8

In the above example, addFive() is a friend function that can access both private and protected data members of the class Length.

Now, letโ€™s see how friend functions are used to operate on objects of two different classes.

Example 2:

In the following program, we will use a friend function to find the sum of members belonging to two different classes.


 
#include <iostream>
using namespace std;
// Forward declaration of ClassB
class ClassB;
class ClassA {
public:
// Constructor to initialize num1 to 35
ClassA() : num1(35) {}
private:
int num1;
// Friend function declaration
friend int add(ClassA, ClassB);
};
class ClassB {
public:
// Constructor to initialize num2 to 15
ClassB() : num2(15) {}
private:
int num2;
// Friend function declaration
friend int add(ClassA, ClassB);
};
// Access members of both classes
int add(ClassA object1, ClassB object2) {
return (object1.num1 + object2.num2);
}
int main() {
ClassA obj1;
ClassB obj2;
cout << "Sum of the objects is: " << add(obj1, obj2) << endl;
return 0;
}
Copy code

Output 2

Sum of the objects is: 50

What have we done here?

In the above example, add() is a friend function that can access both private and protected data members of both the classes โ€“ ClassA and ClassB.

Please note that the friend function inside ClassA is using ClassB. However, the latter has not been defined at this point. This is why we have done a forward declaration of ClassB in our code.

Understanding Break Statement in C++
Introduction to QuickSort Algorithm in C++
Tokens in C Programming

Working of a Friend Class in C++

As discussed above, we can also declare a friend class within another class in C++ using the friend keyword. 

Hereโ€™s the syntax for the same

class ClassTwo;  // Forward declaration of ClassTwo

class ClassOne {
   // Declare ClassTwo as a friend of ClassOne
   friend class ClassTwo;

   // Other members of ClassOne...
};

class ClassTwo {
   // Members of ClassTwo...
};

Here, ClassTwo is a friend class of ClassOne. In such a case, the entire class and all of its data members and functions are also friends. So, we can access all members of ClassOne from inside ClassTwo.

However, the vice versa is not true. That is, the members of ClassTwo cannot be accessed from inside ClassOne. This is because the friendship is not mutual.

Example


 
#include <iostream>
using namespace std;
// Forward declaration of ClassTwo
class ClassTwo;
class ClassOne {
private:
int num1;
// Friend class declaration
friend class ClassTwo;
public:
// Constructor to initialize num1 to 72
ClassOne() : num1(72) {}
};
class ClassTwo {
private:
int num2;
public:
// Constructor to initialize num2 to 8
ClassTwo() : num2(8) {}
// Member function to add num1 from ClassOne and num2 from ClassTwo
int add() {
ClassOne obj1;
return obj1.num1 + num2;
}
};
int main() {
ClassTwo obj2;
cout << "Sum is given as: " << obj2.add() << endl;
return 0;
}
Copy code

Output

Sum is given as: 80

What have we done here?

In the above example, ClassTwo is a friend class of ClassOne. So, ClassTwo can access all data members of ClassOne, and we can create objects of ClassOne inside ClassTwo.

Now, in ClassTwo, we have defined a function add() that returns the sum of num1 and num2. Easy Peasy!

Important points to remember about friend functions:

  • Friendship in C++ is only granted, not taken. So, even if class A is a friend of class B, that does not imply that class B also becomes a friend of class A automatically.
  • Friendship is not inherited. If a base class has a friend function, that does not imply that the function becomes a friend of the derived class(es).
  • Friend functions and classes should be used only for a limited purpose as it lowers the value of encapsulation of separate classes in object-oriented programming.
  • Java programming language does not have a concept of friends.
About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio