Friend Functions

Friend functions are the functions which can access the private members of the class. We have to write the prototype of friend function inside the class of which it is the friend.

Properties of Friend Functions:

  • Friend functions are declared inside the class.
  • They can access the private and protected data members of class of which they are friends.
  • They can be declared inside the public or private part of the class.
  • They are not the members of the class and we do not need object to call them.
  • Unlike methods/member functions which can access data members directly, friend functions cannot access data members directly. There is a need of dot operator, like obj.dataMemberName

class ClassName {
  private:
    // private data members 
    /* Declare the friend function 
    inside the class. It can be 
    public or private*/
    friend type functionName(type param1, ...);
  };
    
  // Define friend function outside the class 
  type funcName(type paramName1, ...) {
  /* Function definition with access
  to private and protected members 
  of the class*/
}

friendFunc.cpp
#include <iostream>
using namespace std;

class Student {
private:
    int num1;
    int num2;

public:
    
    Student(int value1, int value2) {
    	num1 = value1;
    	num2 = value2;
	}

    // Friend function to calculate the sum
    friend int calcSum(const Student& obj);
};

int calcSum(const Student& obj) {
    return obj.num1 + obj.num2;
}

int main() {
    
    Student std(10, 10);
    int sum = calcSum(std);
    cout << "Sum : " << sum << endl;

    return 0;
}

Friend Classes:

Friend class is also the same concept. Friend class is a class which can access the private member of some other class. But this relationship is not reversible. For example, if class1 is the friend of class2, then class1 can access private and protected members of class2 but class2 can not access private or protected members of class21.

class MyClass
{
    friend class FriendClass;
};

friendFunc.cpp
#include <iostream>
using namespace std;

// Forward declaration of the FriendClass
class FriendClass;

// Class that declares FriendClass as a friend
class MyClass {
private:
    int num;

public:
    MyClass(int num){
    	this->num = num;
	}
    // Declare FriendClass as a friend class
    friend class FriendClass;
    int getnum() {
        return num;
    }
};

class FriendClass {
public:
    void display(const MyClass& obj) {
      cout << "Private data: " << obj.num << endl;
    }
};

int main() {
  MyClass obj(10);

  FriendClass friendObj;
  friendObj.display(obj);

  return 0;
}