Friend Functions in C++ & Use Case with Examples
Updated on Nov 28, 2022 | 8 min read | 6.7k views
Share:
For working professionals
For fresh graduates
More
Updated on Nov 28, 2022 | 8 min read | 6.7k views
Share:
Table of Contents
Data hiding is a fundamental software development technique widely used in object-oriented programming languages (OOPs). It restricts access to private data members from outside the class. However, a C++ feature known as the friend function goes against the data hiding principle.
In this article, you will learn what is friend function in C++, what is a friend class and explore some use cases with examples.
Check out our free courses to get an edge over the competition.
A friend function in C++ is a function declared outside a class but has access to the private and protected members of the class. Although the private members of a particular class are inaccessible to non-member functions, declaring them as friend functions gives them access to the private and protected members of the classes.
Check out upGrad’s Advanced Certification in DevOps
Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.
The friend function in C++ has the following characteristics:
Check out upGrad’s Advanced Certification in Cyber Security
To declare the friend function, we use the friend keyword inside the body of the class. The syntax of the friend function is:
class className {
… .. …
friend returnType functionName(arg list);
… .. …
}
If we break down the syntax, here’s what each term means:
Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.
Now, let’s look at some programs to illustrate the friend function.
Example 1: C++ friend function to print the height of a box
#include <iostream>
using namespace std;
class Box
{
private:
int height;
public:
Box(): height(0) { }
friend int printHeight(Box); //friend function
};
int printHeight(Box h)
{
h.height += 40;
return h.height;
}
int main()
{
Box h;
cout<<“Height of box: “<< printHeight(h)<<endl;
return 0;
}
Output:
Height of box:40
Example 2: When the C++ friend function is friendly to two classes
#include <iostream>
using namespace std;
// forward declaration
class ClassQ;
class ClassP {
public:
// constructor to initialize numP to 12
ClassP() : numP(12) {}
private:
int numP;
// friend function declaration
friend int add(ClassP, ClassQ);
};
class ClassQ {
public:
// constructor to initialize numQ to 1
ClassQ() : numQ(1) {}
private:
int numQ;
// friend function declaration
friend int add(ClassP, ClassQ);
};
// access members of both classes
int add(ClassP objectP, ClassQ objectQ) {
return (objectP.numP + objectQ.numQ);
}
int main() {
ClassP objectP;
ClassQ objectQ;
cout << “Sum: ” << add(objectP, objectQ);
return 0;
}
Output:
Sum:13
In the above example, Class P and Class Q have declared add()as a friend function, giving it access to the private data of both the classes. Moreover, the friend function inside Class P is using Class Q.
So, we make a forward declaration of Class Q in the program.
To get a better idea of the friend function in C++, we will now look at the two ways by which we can implement the friend function.
1. Implementing a friend function in C++ through a method of another class
We declare a friend class in C++ when we need access to the private and protected members of another class in which it has been declared a friend. It is also possible to declare a single member function of another class as a friend.
class class_name
{
friend class friend_class;// declaring friend class
};
class friend_class
{
};
In the above declaration of friend class, all functions in friend_class are the friend functions of class_name.
Here’s a simple example to illustrate the implementation of friend functions through a method of another class:
#include <iostream>
using namespace std;
class A
{
int p=4;
friend class B; //friend class
};
class B
{
public:
void display (A &a)
{
cout<<”Value of p is:” <<a.p;
}
};
int main ()
{
A a;
B b;
display (a);
return 0;
}
Output:
Value of p is:4
2.Implementing a global function
Implementing a global friend function lets us access all the protected and private members of the global class declaration. Here’s an example:
#include<iostream>
using namespace std;
class space
{
int a;
int b;
int c;
public:
void setdata (int x, int y, int z);
void display(void);
friend void operator- (space &s);
};
void space ::setdata (int x, int y, int z)
{
a=x; b=y; c=z;
}
void space::display(void)
{
cout<<a<<” “<<b<<” “<<c<<“\n”;
}
void operator- (space &s)
{
s.a =- s.a;
s.b =- s.b;
s.c =- s.c;
}
int main ()
{
space s;
setdata (9,2,3);
cout<<“s:”;
display ();
-s;
cout<<“-s:”;
display ();
return 0;
}
Output:
s: 9 2 3
-s: -9 -2 -3
In the above example program, operator- is the friend function that we globally declared at the scope of the class.
Although it’s pretty evident by now, a friend class is a class that has access to both the private and protected members of the class in which it is declared a friend.
In simple terms, a friend class in C++ is used when we want a class to have access to another class’s private and protected members.
The member functions of the class that we declare as a friend to another class are friend functions to the friend class. Thus, the friend functions link both the classes.
Here’s the syntax of a friend class in C++:
class R; //forward declaration
class P{
// Other Declarations
friend class R;
};
class R{
// Declarations
};
In the above illustration, Class R is a friend of Class P. As a result, Class R can access the private data members of Class P. However, the reverse is not true, and Class P cannot access the private data members of Class R.
Also, the forward declaration is given to inform the compiler of the existence of an entity before it is categorically defined. Here, we declare the Class R using forward declaration to notify the compiler of its existence. The forward declaration allows us to use the objects of Class R in Class P.
Summing up our discussion, let us look at the two primary uses of the friend function in C++:
In this case, the operator overloading function precedes the friend keyword and declares a function class scope. When overloaded by the friend function, binary operators take two explicit arguments while unary operators take one argument. It works the same way as a binary operator function, except that the friend operator function implementation takes place outside the scope of the class.
That brings us to the end of our discussion on the friend function in C++ and its uses. Hope this helps you further your knowledge of C++.
Also, if you’re looking to launch your career as a full-stack developer, upGrad offers a fully online Executive Post Graduate Programme in Software Development – Specialisation in Full Stack Development of 13 months in collaboration with IIIT Bangalore.
Program Highlights:
Sign up today to get the exclusive upGrad benefits today!
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources