Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Friend Function in C++

Last Updated on November 28, 2023 by Ankit Kochar

*

In C++, a friend function stands as a distinct category of function that, although not part of a class, enjoys privileged access to the private and protected members of that class. This special permission enables the friend function to operate on the internal aspects of the class as if it were an integral member function. Declarations for friend functions are typically made within the class to which they extend their friendship, and they are commonly employed to carefully expose controlled external access to the attributes of the class. While friend functions provide a means to interact with private members, their utilization should be deliberate and confined to situations where preserving encapsulation is of utmost importance. Let’s delve deeper into the intricacies of friend functions in C++.

What is a Friend Function in C++?

A friend function in C++ is a special function which can access private and protected members of a class even though it is not a member function of the class.

It is declared as a friend using the ‘friend’ keyword inside the class. By declaring the function as a friend friend in C++ all the permission can be granted to the function. ‘friend’ keyword is placed only inside the class when the function is declared as a friend function, not in the function definition.

We don’t have to use the name of the object or dot operator during the calling of the function, a friend function in C++ can accept the object of the class where the function is declared as a friend function in C++ as an argument. Friend function in C++ can be declared in any section of the class i.e. public or private or protected.

Syntax of friend function in C++:

class     
{    
    friend    (argument/s_type);  
};

Characteristics of Friend Function in C++:

  • The function is not in the scope of the class to which it has been declared as a friend.
  • It cannot be called using the object as it is not in the scope of that class.
  • It can be invoked like a normal function without using the object.
  • It cannot access the member names directly and has to use an object name and dot membership operator with the member name.
  • It can be declared either in the private or the public part of the class.

Types of Friend Function

A friend function in C++ can be of two types:

Global function as friend function in C++

Global Functions in C++ are the functions that are declared outside of any class, function or namespace. Global Functions are also called free functions.
Examples of Global Function in C++ as a friend function in C++ :

  1. Global functions as a friend function in C++ example to only one class to find the product of two numbers.

    #include<iostream>
    using namespace std;
    class Multiplication
    {
        int a,b;
        public:
       	 void set_data()
    {
        cout<<"Enter the First No:";
        cin>>a;
        cout<<"Enter the Second No:";
        cin>>b;
    }
    // declaration of Global function as a friend function in C++
       	 friend void multiply(Multiplication);    
    };
    // defining Global function (friend function for Multiplication class)
    void multiply(Multiplication t)
    {
        int c=t.a * t.b;
        cout<<”Product ”<<c<<endl;
    }
    int main()
    {
    //instantiation of Multiplication class
        Multiplication l;
        l.set_data();
    // calling of friend function in C++
        multiply(l);
        return 0;
    }
    

    OUTPUT

     Enter the First No:5
     Enter the Second No:2
     Product 10
  2. Global functions as a friend function in C++ to more than one class used to print the full name.

    #include<bits/stdc++.h>
    using namespace std;
    // forward declaration of LastName class
    class LastName;
    class FirstName
    {
        string  first_name;
        public:
    	//Constructor
       	FirstName(string first){
    	        first_name=first;
    }
       	 //declaring friend function in C++
       	 friend void fullName(FirstName,LastName);
    };
    
    class LastName
    {
       string last_name;
        public:
    	// Constructor
       	 LastName(string last){
    	     last_name=last;
    }   
        // declaring friend function in C++
        friend void fullName(FirstName,LastName);
    };
    
    //defining friend function in C++
    void fullName (FirstName first,LastName last)
    {
        string full=first.first_name + “  “ + last.last_name;
       cout<<full<<endl;
    }
    
    main()
    {
    //instantiation of FirstName class
        FirstName a(“Aditya”);
    //instantiation of LastName class
        LastName b(“Rastogi”);
     //calling of friend function in C++
        fullName(a,b);
        return 0;
    }
    

    OUTPUT

    Aditya Rastogi

Member function of another class

Member functions are the functions declared as a member of class. These functions can access private and protected member of the class in which these are declared as member. These functions do not include functions declared with friend specifiers.

Examples of Member Function in C++ as a friend function in C++ used to print the full name.

#include <bits/stdc++.h>
using namespace std;
class Last;
class First {
string a="Aditya";
public:
	void full(Last);
};

class Last {
private:
	string b="Rastogi";
Public:
//declaring a Member Function as a Friend Function in C++
	friend void First::full(Last x); // Friend function
};
//calling of friend function in C++
void First::full(Last y){
	cout<<this->a<<" "<<y.b;
}

int main()
{
	First x;
	Last y;
	x.full(y);
	return 0;
}

OUTPUT

Aditya Rastogi

Important points related friend functions in C++:

  1. A class should not have many functions or classes as friend, as it will reduce the encapsulation value of that class.
  2. Friend classes are not mutual, meaning if class A is declared friend class of class B then B will not be the friend of class A.
  3. Friendship is not inherited, meaning if a base class has a friend function, then the function doesn’t become a friend of the derived class(es).

Advantages and Disadvantages of friend functions in C++:

Advantages of friend function in C++:

  • A friend function is able to access members without the need of inheriting the class.
  • Friend function acts as a bridge between two classes by accessing their private data.
  • It can be used to increase the versatility of an overloaded operator.
  • It can be declared either in the public or private or protected part of class.

Disadvantages:

  • Friend functions have access to private members of a class from outside the class which violates the law of the data hiding.
  • Friend functions cannot do any run time polymorphism in its members.

Summary
A friend function in C++ are the function which can access private and protected members of a class without being the member function of that class.
Friend Function in C++ can be declared anywhere in the class i.e. public, private or protected sections.

Friend Function in C++ are of two types:

  1. Global Functions as a Friend Functions
  2. Member function of another class

Conclusion
In the realm of C++, the friend function emerges as a potent tool, granting external functions the ability to reach into the private and protected realms of a class. It selectively dismantles encapsulation, providing a method for deliberate and controlled interactions with the inner workings of a class. While bestowing advantages such as streamlining interactions between classes and augmenting operator flexibility, the deployment of friend functions requires careful consideration to uphold data hiding and overall design integrity. By judiciously harnessing these capabilities, developers can strike a harmonious balance between controlled access and the preservation of fundamental class design principles in C++.

Frequently Asked Questions (FAQs) related to Friend Function in C++

Here are some of the frequently asked questions about friend function in C++.

Q1. What is a friend function in C++?
A friend function in C++ is a special function that is not a member of a class but is granted access to the private and protected members of that class. It can manipulate the class’s internal data as if it were a member function.

Q2. How is a friend function declared in a class?
A friend function is declared using the friend keyword within the class that it is meant to be a friend of. This grants the function access to the private and protected members of the class.

Q3: When should I use friend functions in C++?
Friend functions should be used judiciously. They are beneficial when controlled access to private or protected members is required, such as for streamlining operations between classes or when operator overloading is desired. However, their usage should be limited to situations where maintaining encapsulation is essential.

Q4: Can a friend function be a member of another class?
Yes, a friend function can belong to another class or be a standalone function. The key characteristic is that it is granted friendship with a specific class, allowing it to access that class’s private and protected members.

Q5: Do friend functions violate encapsulation in C++?
Yes, friend functions break encapsulation selectively by accessing private and protected members of a class. While this can be useful in certain scenarios, it should be done judiciously to avoid compromising the principles of data hiding and design integrity.

Q6: Can a friend function be inherited by derived classes?
Friendships are not inherited in C++. A friend function of a class does not automatically become a friend of its derived classes. Friendship is a one-way relationship that must be explicitly declared in each class where access is desired.

Leave a Reply

Your email address will not be published. Required fields are marked *