Friend Function In C++ - C++ Programming Tutorial
C++ Course / Functions / Friend Function In C++

Friend Function In C++

BLUF: Mastering Friend Function In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Friend Function In C++

C++ is renowned for its efficiency. Learn how Friend Function In C++ enables low-level control and high-performance computing in the tutorial below.

In C++, a friend function is an external function that has the capability to access private and protected members of a class. The friend function is specified within the class using the friend keyword. By designating a function as a friend, a class can grant it unique access permissions, allowing it to manipulate the class's internal data.

In C++, a friend can be a function, member function, class, class template, or function template. In such scenarios, the entire class and all its members are considered friends.

Syntax of the Friend Function in C++

It has the following syntax:

Example

class class_name    

{    

 friend data_type function_name(arguments);  //Friend Function Declaration

};

The friend function can be declared in any part of the program, just like a typical C++ function. The definition of this function does not make use of either the friend keyword or the scope resolution operator.

C++ Friend Function Example

Let's consider an instance where we utilize a friend function to calculate the dimensions of a box.

Example

Example

#include <iostream>

using namespace std; //using standard namespace

class Box //class 

{

    private:

        int length;

    public:

        Box(): length(0) { }

        friend int printLength(Box); // friend function declaration

};

int printLength(Box b)

{

    b.length += 10;

    return b.length;

}

int main() //Main Function

{

    Box b;

    cout << "Length of the box: " << printLength(b) << endl; //prints the output

    return 0;

}

Output:

Output

Length of the box: 10

Explanation

In this instance, a Box class is showcased with a private integer attribute called length, set to an initial value of 0. Subsequently, a printLength friend function is defined within the class.

In the printLength method, the box's size is incremented by 10 and then the new length is returned. Within the main function, a Box object named b is instantiated and then passed as an argument to the printLength function, which displays the revised length (10) on the console.

Accessing Private and Protected Members

In C++, external access to private and protected members of a class is restricted. To interact with these members, the friend function can be employed. This special function grants direct access to the private and protected members within the class.

Accessing Private and Protected Member Examples

Let's consider an example to demonstrate the differences between private and protected members in C++.

Example

Example

#include <iostream>

using namespace std;

class CppTutorial {

private:

    int private_memb;

protected:

    int protected_memb;

public:

    CppTutorial() : private_memb(25), protected_memb(50) {}

    

    friend void friendFunction(CppTutorial& obj); // Friend function declaration

};

// Friend function definition

void friendFunction(CppTutorial& obj) {

    cout << "Accessing Private: " << obj.private_memb << endl;

    cout << "Accessing Protected: " << obj.protected_memb << endl;

}

int main() {

    CppTutorial cpptutorial_object;

    friendFunction(cpptutorial_object); // Access private and protected members

    return 0;

}

Output:

Output

Accessing Private: 25

Accessing Protected: 50

Explanation

In this instance, we consider the class CppTutorial containing a pair of data attributes, privatememb and protectedmemb, which are set during object construction. Subsequently, a friendFunction is announced within the class but implemented externally. Within the main function, an instance of CppTutorial illustrates how friend functions offer regulated entry to otherwise restricted class components.

Types of Friend Functions

  • External Friend Functions
  • Friend Functions within a Different Class
  • Non-Member Friend Function

In C++, the non-member friend function is defined within the class, yet they are not considered as part of the class. This feature allows them to access the private and protected members of the class. These external functions are frequently employed to provide operations on the class's private data members.

C++ Non-Member Friend Function Example

Let's consider an illustration to showcase the Non-Member Friend Function in C++.

Example

Example

#include <iostream>

using namespace std; //using standard namespace

class CppTutorial {

 private:

  int private_data;  // Private member

 protected:

  int protected_data;  // Protected member

 public:

  CppTutorial() : private_data(0), protected_data(0) {}

  friend void friend_Funct(CppTutorial& obj); //non-member function declared

};

void friend_Funct(CppTutorial& obj) // friend function definition

{

  obj.private_data = 57;    // Access private member

  obj.protected_data = 18;  // Access protected member

  cout << "Private Data: " << obj.private_data << endl;

  cout << "Protected Data: " << obj.protected_data << endl;

}

int main() //Main function

{

  CppTutorial obj;

  friend_Funct(obj);  //Calling the friend function

  return 0;

}

Output:

Output

Private Data: 57

Protected Data: 18

Explanation

In this instance, the friendFunct function alters and showcases the privatedata and protected_data of the CppTutorial class instance, despite these attributes being restricted from external access.

Member Function of another Class

In C++, it is possible to designate member functions from a different class as friend functions. This allows the friend function to have access to the private and protected members of the other class.

It is highly beneficial in situations where two classes need to collaborate closely, like in scenarios involving operator overloading or utility functions that require direct interaction with internal data.

C++ Member Function of Another Class Example

Let's consider a scenario to demonstrate the member function of a different class instance in the C++ programming language.

Example

Example

#include <iostream>

using namespace std; //using standard namespace

class First; // Forward declaration of class First

class Last {

public:

    // Member function of class Last

    void showValue(First obj); // Declaration

};

class First {

private:

    int val;

public:

    First() : val(115) {}

    // Declare member function of class last as a friend

    friend void Last::showValue(First obj);

};

// Definition of member function of class last

void Last::showValue(First obj) {

    cout << "Private value of class First accessed from class Last: " << obj.val << endl;

}

int main() //Main Function

{

    First x;

    Last y;

    y.showValue(x); // Member function of last accessing private data of first

    return 0;

}

Output:

Output

Private value of class First accessed from class Last: 115

Explanation

In this instance, the class First includes a private attribute val, while the class Last incorporates a method showValue(First). Subsequently, this method is specified as a friend in First, granting it permission to access val. Within the main function, the y.showValue(x) operation showcases inter-class private access facilitated by a friend member method.

Usage of Friend Function

Various applications of the Friend Function in C++ are outlined below:

1) Multiple Classes using Friend Function

If there is a need to retrieve confidential information from various classes in C++, the friend function proves to be extremely beneficial.

Friend Function of Multiple Classes Example

Let's consider an example to demonstrate the friend function among several classes.

Example

Example

#include <iostream>

using namespace std; //using standard namespace

class B; // forward declaration

class A

{

    int x;

public:

    void setdata(int i)

    {

        x = i;

    }

    friend void min(A, B); // Friend Function

};

class B

{

    int y;

public:

    void setdata(int i)

    {

        y = i;

    }

    friend void min(A, B); // Friend Function

};

void min(A a, B b)

{

    if (a.x <= b.y)

        std::cout << a.x << std::endl;

    else

        std::cout << b.y << std::endl;

}

int main()  //Main Function

{

    A a;

    B b;

    a.setdata(10);

    b.setdata(20);

    min(a, b);

    return 0;

}

Output:

Explanation

In this illustration, we showcase the implementation of a friend function to retrieve private data members from different classes. Within the min function, the data values of each class are evaluated against each other, and the lesser value is outputted. Subsequently, the main function initializes values for both instances and invokes the friend function to showcase the minimum value.

2) Operator Overloading Using Friend Function

In C++, a friend function is employed to redefine operators for a class in situations where the left-hand operand is not an instance of that class (operators such as +, -, *, and so forth).

Friend functions are external functions that are not part of the class but can access the private and protected members of the class. They are particularly useful for overloading operators when there is a need for direct access to the class's internal data from external sources.

In C++, operator overloading is a technique that allows operators to be redefined for user-defined types. This can be achieved by using friend functions to overload operators. Let's explore an example of C++ operator overloading using friend functions.

Consider the following example where we have a class named ```

class class_name

{

friend datatype functionname(arguments); //Friend Function Declaration

};

Example


include <iostream>

class ```

class class_name

{

friend datatype functionname(arguments); //Friend Function Declaration

};

Example

private:
    int x, y;

public:

class class_name

{

friend datatype functionname(arguments); //Friend Function Declaration

};

Example


    void display() {
        std::cout << "x = " << x << ", y = " << y << std::endl;
    }

    friend ```
class class_name    

{    

 friend data_type function_name(arguments);  //Friend Function Declaration

};

class class_name

{

friend datatype functionname(arguments); //Friend Function Declaration

};

Example

class class_name    

{    

 friend data_type function_name(arguments);  //Friend Function Declaration

};

};

Example

class class_name    

{    

 friend data_type function_name(arguments);  //Friend Function Declaration

};

class class_name

{

friend datatype functionname(arguments); //Friend Function Declaration

};

Example

class class_name    

{    

 friend data_type function_name(arguments);  //Friend Function Declaration

};
Example

class class_name    

{    

 friend data_type function_name(arguments);  //Friend Function Declaration

};

temp.x = obj1.x + obj2.x;

temp.y = obj1.y + obj2.y;

return temp;

}

int main {

Example

class class_name    

{    

 friend data_type function_name(arguments);  //Friend Function Declaration

};
Example

class class_name    

{    

 friend data_type function_name(arguments);  //Friend Function Declaration

};
Example

class class_name    

{    

 friend data_type function_name(arguments);  //Friend Function Declaration

};

obj3.display;

return 0;

}

Example


In this example, the `+` operator is overloaded using a friend function, allowing us to add two objects of the ```
class class_name    

{    

 friend data_type function_name(arguments);  //Friend Function Declaration

};

Let's consider an example to illustrate operator overloading using the friend function in the C++ programming language.

Example

Example

#include <iostream>

using namespace std; //using standard namespace

class Cmplex_num

{

    private: //private class member

        int real_num;

        int img_num;

    public: //public class member

        Cmplex_num (int r = 0, int i = 0)

        {

            real_num = r;

            img_num = i;

        }

        void show ()

        {

            cout << real_num << "+i" << img_num;

        }

        friend Cmplex_num operator + (Cmplex_num c1, Cmplex_num c2);

};

Cmplex_num operator + (Cmplex_num c1, Cmplex_num c2)

{

    Cmplex_num temp;

    temp.real_num = c1.real_num + c2.real_num;

    temp.img_num = c1.img_num + c2.img_num;

    return temp;

}

int main () //Main Function

{

    Cmplex_num C1(8, 5), C2(20, 7), C3;

    cout << "The Result is: ";

    C1.show();

    cout << " + ";

    C2.show();

    cout << " = ";

    C3 = C1 + C2;

    C3.show();

}

Output:

Output

The Result is: 8+i5 + 20+i7 = 28+i12

Explanation

In this instance, we are working with a pair of integer values, referred to as real and imag numbers, encapsulated within the Cmplex_num class. Within the show function, a temporary variable is employed, and the addition operation is executed through operator overloading. Subsequently, the main function utilizes the cout function to display the resultant output.

Features of the Friend function

Several features of the friend function in C++ are as follows:

  • 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 because it is not in the scope of that class.
  • It can be called like a normal function without using the object.
  • It can be declared either in the private or the public section of the class.
  • C++ Friend Class

In C++, a friend class is given permission to access the private and protected members of the class that designates it as a friend. When a class designates another class as a friend within the program, the latter class can then have direct access to the private and protected members of the former class.

When a class is designated as a friend class, all functions within that class are granted friend status, resembling the behavior of individual friend functions.

Syntax

It has the following syntax:

Example

friend class class_name;  // declared in the base class

C++ Friend Class Example

Let's consider a scenario to demonstrate the friend class concept in C++.

Example

Example

#include <iostream>

using namespace std; //using namespace

class First

{

    int i = 10; // private member

    friend class Last; // friend class

};

class Last

{

public:

    void display(First &x)

    {

        cout << "The Value of i is: " << x.i << endl; // accessing private member of A

    }

};

int main() //Main Function

{

    First x;

    Last y;

    y.display(x); // calling display method

    return 0;

}

Output:

Output

The Value of i is: 10

Explanation

In this instance, the class First comprises a private integer attribute i that is set to 10 upon initialization. The class Last is designated as a friend of First through the friend class Last declaration, enabling Last to access First's private members. Within the main function, instances of both classes are instantiated, and the display method is invoked to display the private data stored within the First class.

Advantages and Disadvantages of Friend Function in C++

Several Benefits and drawbacks of Friend Functions in C++ are outlined below.

Advantages of Friend Function

  • Access to Private Members: Friend functions conveniently make it possible to change the protected and private members of a class because they can access them, which provides more flexibility in design.
  • Operator Overloading: They are also frequently utilized in operator overloading because of their ability to access the private data of the pertinent objects.
  • Separation of Concerns: With the help of friend functions, the user interface can be separated from the actual implementation, which improves code organization.
  • Improved Performance: Friend functions enable accessing the private parts of a class that reduces the use of getter/setter functions, which makes it more efficient.
  • Inter-Class Communication: They allow different classes to communicate without needing a direct relationship, which is beneficial in complex designs.
  • Disadvantages of Friend Function

  • Encapsulation Break: Friend functions can access private members, thus violating the encapsulation principle, which makes code maintenance a complex task.
  • Tight Coupling: Friend functions make classes dependent on each other, which makes design modularity difficult.
  • Security Risks: In C++, using the friend function and friend class to allow access to private data can discover the class to potential risk.
  • C++ Friend Function MCQs

1) What is the Friend Function in C++?

  • A function that is not allowed to access any member of the class.
  • A function that can access all the class members, including public, private, and protected.
  • A function that is allowed to access only the public members of the class.
  • A function that is allowed to access the public and protected class members.

b) A method that is capable of accessing all the attributes of the class, including public, private, and protected ones.

2) Is it possible for a friend function to serve as a member of another class in C++?

  • This is permissible only when it is explicitly declared as public.
  • This can only occur if both classes are derived.

3) Which keyword is used to define the friend function in C++?

  • Friend
  • extern
  • friend
  • private

4) What will be the output of the following code?

Example

#include <iostream>

using namespace std;

void CppTutorial();

class funct {

private:

    int var;

public:

    funct()

    {

        var = 20;

    }

    friend void CppTutorial();

};

void CppTutorial()

{

    funct i;

    cout << i.var << endl;

}

int main()

{

    CppTutorial();

    return 0;

}
  • Compilation Error
  • Linker Error

5) Which of the following statements is correct about the friend function in C++?

  • Friend functions are in the scope of the class
  • They can only access public members
  • They can be called using class objects only
  • Friend Functions are not in the scope of the class

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience