C++ Friend Functions

A friend function in C++ is a function that is not a member of a class, but has the ability to access the private and protected members of that class. It is declared inside the class using the keyword friend.

About Friend Functions

1. A friend function is not a member of the class.

2. It can access private and protected members of the class.

3. It is often used when a function needs to operate on multiple classes or interact with private members of a class, but doesn’t belong to the class itself.

Example:


#include <iostream>
using namespace std;

class Employee {
private:
    string name;
    int age;

public:
    // Constructor to initialize values
    Employee(string n, int a) : name(n), age(a) {}

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

// Friend function definition
void displayEmployeeInfo(Employee emp) {
    cout << "Name: " << emp.name << endl;  // Accessing private member 'name'
    cout << "Age: " << emp.age << endl;    // Accessing private member 'age'
}

int main() {
    // Creating a Employee object
    Employee employee("John", 35);

    // Calling the Employee function
    displayEmployeeInfo(employee);  // This can access the private members of 'Employee'

    return 0;
}

Output:

Name: John
Age: 35

Explanation:

1. Employee Class:

  • It has two private data members: name and age.
  • It has a constructor to initialize these members.

2. Friend Function displayEmployeeInfo():

  • This function is declared as a friend of the Employee class, meaning it can access the private members (name and age) of any Employee object.
  • It prints the private information of the Employee object passed to it.

3. In main():

  • A Employee object employee is created.
  • The friend function displayEmployeeInfo() is called, and it can access the private members of the employee object.

C++ Friend Functions – Interview Questions

Q 1: What is a friend function?
Ans: A function that can access private members of a class.
Q 2: How is a friend function declared?
Ans: Using the friend keyword.
Q 3: Is a friend function a class member?
Ans: No.
Q 4: Can a friend function access private data?
Ans: Yes..
Q 5: Can one function be friend of multiple classes?
Ans: Yes.

C++ Friend Functions – Objective Questions (MCQs)

Q1. What is a friend function in C++?






Q2. How do you declare a friend function inside a class?






Q3. Can a friend function be called like a normal function?






Q4. Which of the following is TRUE about friend functions?






Q5. Does a friend function become a member of the class?






Related C++ Friend Functions Topics