Friend Function in C++ Explained With Example

Friend Function in C++ Explained With Example
Friend Function in C++ Explained With Example

Introduction 

C++ is a powerful language that offers various functions to offer its users more power over the language and mould it in accordance with their needs. To help work with classes efficiently, C++ has introduced friend functions that help in handling the class objects properly and seamlessly.

Some programmers find it difficult to understand the concept behind the friend functions but in this blog, everything is explained in detail which will help you to strengthen your understanding even more. 

In this blog, we will look at the power and advantages that a friend function offers in C++. We will also look at an example that will explain how one can use the friend function in their code.

Advantages of using Friend Function in C++

We are well aware that the private members of a class cannot be accessed by any members outside the ones of that particular class. No non-member of a class can use a function declared in a class. Let us consider a situation where we have two classes – professors and visiting_faculty have been defined in our program.

The ‘professors’ class contains data about the current working professors in the university and the ‘visiting_faculty’ class contains data about the faculty who are not working full time and rather are here in the university for a certain period of time. 

Let us assume there is a function salary(). This function is applicable to both professors and visiting_faculty classes. So how do we use one particular function in two classes without explicitly defining it as a function of both classes? This is where the friend function comes in. 

The importance of the friend function in C++ is that it makes the function ‘friendly’ to both the professors and visiting_faculty classes and makes sure both of these classes are able to use the salary() function, irrespective of its place of declaration and/or its visibility scope. The moment a function is declared friendly to a class, it gains access to the private members of the class it has been declared friendly for. 

Code Example of Friend Function in C++

To declare a function as a friend function, you have to use the friend keyword before the function definition. The definition of the function is the same as that of any function in C++. A global function can be declared anywhere outside the class in C++ which can then be declared as a friend function of the class. 

#include <iostream>
using namespace std;

class visiting_faculty{
    string name;
    int visiting_faculty_id; 
    float base_sal; 
    float sal;
    public:
    visiting_faculty(){
        name = "none";
        visiting_faculty_id = 0;
        base_sal = 50000;
        sal = 500000;
    }
    friend float calculate_sal(visiting_faculty objX);
};

float calculate_sal(visiting_faculty objX){
    return (objX.base_sal+100000)*2.5;
}

int main()
{
    visiting_faculty obj_sample; 
    cout<<"Salary = "<<calculate_sal(obj_sample)<<"\n";
    return 0;
}

Output: Salary = 375000

Characteristics of Friend Function in C++

Below are some characteristics and rules of friend function in C++ which one needs to keep in mind while working with friend functions in C++.

blog banner 1
  • A friend function does not necessarily have to be a function of a particular class, it can be any global function in general as well. 
  • Classes and Objects are used to enforce the object-oriented programming paradigm of encapsulation and abstraction. Over-use of the friend keyword will result in the loss of the properties that a class stands for. 
  • The friendship characteristic doesn’t exist in a vice-versa mode. This means if visiting_faculty is a friend of the professors class then it doesn’t mean that the professors class will be a friend of the visiting_faculty class. 
  • Friendship of classes is not an inheritable characteristic.
  • The friend function is out of the scope of the class for which it has been declared a friend. 
  • The friend function being out of the scope of the class cannot be called by any object declared for that particular class. 
  • The friend function can also be invoked and called like a normal C++ function, it does not require a class object to be invoked or called. 
  • While member functions can access the data members directly, friend functions need to utilise the dot operator to gain access to the data members of the class. Example – To access the name data member of the visiting_faculty class through the object obj1, the friend function has to use visiting_faculty_obj1.name. 
  • The friend function when declared inside a class can be declared in any visibility scope (private/public). It does not affect the working of the friend function. 
  • Usually, objects of a class are passed as arguments to the friend function.

Frequently Asked Questions

What is a friend function in C ++?

A friend function in C++ is used to make a function get access to the private and protected members of the class without being a member of the class.

What is the friend function in C++? Explain with example

A friend function in C++ is a function that lets several classes put forward their data members irrespective of their visibility scope and utilise the full power of the function. Two examples of a friend function which is a member of a class and a friend function which is a global function is given in the article above.

How do you write a friend function in C++?

To write a friend function in C++, you have to use the keyword friend along with the function declaration.

What are the advantages of the friend function in C++?

Friend function does away with the need of explicitly defining separate functions having the same functionality for separate classes.

What is the purpose of a friend function?

The purpose of the friend function is to provide its functionality to different classes and access their private and protected data members without actually being a member function of the class.

What is the friend function? Explain with example

The friend function in C++ is a special function that is used with classes and objects to gain access to the private and protected members of the classes and perform operations on them. Overuse of friend functions is not recommended. Two examples with different use cases of the friend functions are mentioned above.

Key Takeaways

Friend functions are extremely handy when you are utilising the concepts of object-oriented programming. They make your life easier and reduce redundancy by making you write fewer lines of code. As a good programmer, you should be aware of good programming practices which makes your code more readable and easy to understand.

In addition to utilising these advanced concepts, make sure your code is full of comments which enable anyone who is reading your code to quickly understand what is going under the hood. 

To learn more about C++ and learn C++ programming, it is recommended you take a mentor-led course such as the one by Coding Ninjas which is considered to be one of the nation’s best programming courses if you are looking to strengthen your concepts. Here is the link to learn C++ with data structures and algorithms.

Happy Learning!

By Pooja Gera