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.
What is the friend function in C++?
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.
Characteristics of the Friend Function
The friend function in C++ has the following characteristics:
- The friend function is outside the scope of the class to which it has been declared a friend
- A friend function can either be a member of a class or a function declared outside the scope of the class
- The friend functionality is not limited to a single class.
Explore our Popular Software Engineering Courses
- Invoking a friend function is like invoking any normal function of the class without using the object
- We cannot invoke the friend function using the object since it is not in the scope of the class
- Friend functions in C++ have objects as arguments
- We can declare a friend function either in the private or public part
- The member names are not directly accessible to a friend function, and it has to use the dot membership operator and object name with the member name
Check out upGrad’s Advanced Certification in Cyber Security
Syntax of the Friend Function
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);
… .. …
}
In-Demand Software Development Skills
If we break down the syntax, here’s what each term means:
- friend is the keyword denoting that the function is a friend function
- returnType is the return type of the function
- functionName is the function’s name that’s made a friend of the class
- arg list is the arguments we’ll pass
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.
Example of a C++ Friend Function
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;
}
Read our Popular Articles related to Software Development
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.
Implementing a Friend Function
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.
- 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
- 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.
What is friend class in C++?
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.
Syntax of the Friend Class
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.
What is the use of the friend function in C++?
Summing up our discussion, let us look at the two primary uses of the friend function in C++:
- First, we use the friend function when we want to access the private and protected members of a class. To do this, we would generally require the objects of that class to access the private and protected members. However, the friend function eliminates the situation where the function needs to be a class member to gain access.
- Another use of the friend function in C++ is in operator overloading. Functions having the same name but different numbers and arguments are known as overloading functions. Friend functions in C++ find use in operator overloading.
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:
- Hands-on exposure to industry relevant case studies and assignments
- 450+ hours of 360-degree learning
- 10+ top programming tools and languages
- 1:1 Career mentorship Sessions with industry mentors
- 24/7 student support
Sign up today to get the exclusive upGrad benefits today!
What is the friend function in C++?
A friend function in C++ is a function that’s not a member of a class but has access to its private and protected members.
How do you declare a friend function?
A friend function has access to a class's private and protected data. To declare a friend function, we use the friend keyword inside the body of the class.
How do you make a class friend in C++?
We use the friend keyword to declare a class as a friend class in C++. The keyword lets any class access private and protected members of other classes and functions.