Friend Function in C++

By | October 26, 2019

Data Hiding is one of the main properties of Object-Oriented Programming and in C++ with the help of access modifiers such as Private, Public and Protected we can alter the privacy of attributes and methods of a Class.

In a class, if we have used private modifiers for the class attributes so only that specific class methods would be able to access those private attributes and no other member function would be able to use any of those private attributes. But in C++ we have a keyword known as 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 which we only declared 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.

As it is not the member function of the class, but it can access the private and protected properties of that class, that’s how it violates the data protection and privacy concept of the OOP’s.

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
    }

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-ordiantes 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-ordiantes is= 9

Summary:

  • A friend function is not a member function of a class
  • We only declare the friend function inside the class with a friend keyword
  • The friend function should be defined outside the class
  • A friend function can access any member of the class
  • A friend function can not access members of a class directly
  • We pass the class object as a parament to the friend function.

Leave a Reply

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