Friend Function in C++

Posted in /  

Friend Function in C++
vinaykhatri

Vinay Khatri
Last updated on December 21, 2024

    In this article, we will discuss the concept of the friend function in C++. Data hiding is one of the main properties of object-oriented programming, and in C++, with the help of access modifiers , namely Private, Public and Protected, we can alter the privacy of attributes and methods of a class. In a class, if  we have used the Private modifier for the class attributes, then the methods of that specific class would be able to access those private attributes, and no other member function would be able to use any of those private attributes. Nonetheless, in C++, we have a keyword, friend, which helps a function to access the properties of the class, even the Private ones.

    Friend Function in C++

    A friend function is a special function that we only declare inside a class using the friend keyword but do not define it, and it is also not considered as the member function of that class. Although it is not a member function of the class, it can access the private and protected properties of that class. That’s how the friend function in C++ violates the data protection concept of object-oriented programming .

    Syntax to write a friend function:

    class class_name
       {
         //class properties
         friend return_type function_name(class_name);
         // no definition for friend function
       };
        // friend function definition should be outside the class
    
    return_type function_name(class_name object_name)
        {
        // friend function defination
        }

    Code Example:

    #include<stdio.h>
    #include <conio.h>
    #include<iostream.h>
    class Coordinates
        {
           private:
             int x,y,z;
           public:
             void set(int a, int b, int c)
                {
                    x=a;
                    y=b;
                    z=c;
                }
              friend void co_sum(Coordinates); //Only function declaration
          };
    void co_sum(Coordinates c)
         {
          cout<<"The sum of Co-ordinates is= "<<c.x + c.y+c.z;
         }
    
    void main()
        {
          clrscr();
          Coordinates c1;
          c1.set(2,3,4);
          co_sum(c1);
          getch();
         }

    Output:

    The sum of Co-ordinates is= 9

    Summary

    A friend function is not a member function of a class. Moreover, we only declare the friend function inside the class with the friend keyword. The friend function should be defined outside the class, and it can access any member of the class. However, the friend function can not access members of a class directly. We have to pass the class object as a parameter to the friend function.

    People are also reading:

    Leave a Comment on this Post

    0 Comments