Class 1 Class 2 Class 3 Class 4 Class 5 Class 6 Class 7 Class 8

Friend Function in C++

Share Now

A Friend Function in C++ is a function that is not a member of a class but still has permission to access its private and protected data.

Friend Function in C++

In C++, a friend function is a special type of function declared inside the class, and it is not a member of a class but has permission to access its private and protected members. The friend function can be declared using the ‘friend’ keyword, and it can be defined outside the class like a normal function, but it can access hidden data. The normal functions are not allowed to access any private or protected data from the class.

Syntax:

#include <iostream>
using namespace std;

class Employee {
private:
    int salary;
public:
    Employee(int s) { salary = s; }

    // Friend function declaration
    friend void displaySalary(Employee emp);
};

// Friend function definition
void displaySalary(Employee emp) {
    cout << "Salary: " << emp.salary << endl;
}

int main() {
    Employee e1(50000);
    displaySalary(e1);  // Can access private member
    return 0;
}

Features of friend functions

  • It can be declared with the ‘friend’ keyword.
  • It is not a member function of the class, but it can access the private and protected members.
  • It can be defined inside or outside the class.
  • A friend function is not mutual.

Advantages of the friend function

  • It allows the external function to access the private data when it is required.
  • It is useful for operator overloading.
  • It works closely between two classes.

Disadvantage of friend functions

  • It breaks the encapsulation, meaning that if a friend function is declared, then it can access the hidden data.
  • Can lead to tight coupling between classes
  • If you use a friend function, then it reduces clarity and security.

When the friend function is used

  • The friend function is used in operator overloading.
  • When you want to access internal data, the function should not be the class members.
  • When two classes need to share private data, then you can use a friend function.

Disclaimer: We have provide you with the accurate handout of “Friend Function in C++“. If you feel that there is any error or mistake, please contact me at anuraganand2017@gmail.com. The above study material present on our websites is for education purpose, not our copyrights.

Images and content shown above are the property of individual organisations and are used here for reference purposes only. To make it easy to understand, some of the content and images are generated by AI and cross-checked by the teachers.

cbseskilleducation.com

Leave a Comment