C++ friend functions and friend classes


Introduction

In C++, friend functions and friend classes are used to give specific functions or classes access to the private and protected members of another class. Although C++ provides access control using public, private, and protected access specifiers, sometimes it is necessary to allow certain functions or other classes to access private data. This is where friend functions and friend classes come in.

A friend function is not a member of a class but can access its private and protected members. A friend class is a class whose methods can access the private and protected members of another class.


1. What is a Friend Function in C++?

A friend function in C++ is a function that is not a member of a class but is given access to the class’s private and protected members. The friend function can be a regular function or a member function of another class.

Key Points about Friend Functions:

  • They are not members of the class but are allowed to access its private and protected members.
  • A friend function is declared using the friend keyword inside the class whose members it will access.
  • Friend functions can be used for operations that require access to the internal state of an object but do not necessarily belong to the object as a member.

2. Syntax of a Friend Function

To declare a function as a friend of a class, the friend keyword is used in the class definition.

class ClassName {
    friend returnType functionName(parameters);
};

Example of a Friend Function:

#include <iostream>
using namespace std;

class Box {
private:
    double length;
    double width;

public:
    Box(double l, double w) : length(l), width(w) {}  // Constructor to initialize the dimensions

    // Declaring the function `calculateArea` as a friend function
    friend double calculateArea(Box b);
};

// Friend function definition
double calculateArea(Box b) {
    return b.length * b.width;  // Accessing private members of Box
}

int main() {
    Box box1(5.0, 3.0);
    cout << "Area of the box: " << calculateArea(box1) << endl;  // Output: Area of the box: 15
    return 0;
}

Explanation:

  • The Box class has private members length and width, and we want to calculate the area of the box using a function that is not a member of the Box class.
  • We declare calculateArea() as a friend function, giving it access to the private members of Box.
  • The calculateArea function can access the private members directly, even though it's not a member of the Box class.

3. What is a Friend Class in C++?

A friend class in C++ is a class that is allowed to access the private and protected members of another class. When one class is declared as a friend of another, all the member functions of the friend class can access the private and protected members of the class.

Key Points about Friend Classes:

  • A friend class is declared inside the class it will access, using the friend keyword.
  • All member functions of the friend class can access the private and protected members of the class, making it a special case of access control.

4. Syntax of a Friend Class

To declare a class as a friend, the friend keyword is used followed by the class name.

class ClassName {
    friend class FriendClassName;
};

Example of a Friend Class:

#include <iostream>
using namespace std;

class Box {
private:
    double length;
    double width;

public:
    Box(double l, double w) : length(l), width(w) {}

    // Declaring the `Helper` class as a friend class
    friend class Helper;
};

class Helper {
public:
    double calculateArea(Box b) {
        return b.length * b.width;  // Accessing private members of Box
    }

    void displayDimensions(Box b) {
        cout << "Length: " << b.length << ", Width: " << b.width << endl;  // Accessing private members of Box
    }
};

int main() {
    Box box1(5.0, 3.0);
    Helper helper;

    // Using a friend class method to calculate area and display dimensions
    cout << "Area of the box: " << helper.calculateArea(box1) << endl;  // Output: Area of the box: 15
    helper.displayDimensions(box1);  // Output: Length: 5, Width: 3

    return 0;
}

Explanation:

  • The Box class has private members length and width.
  • The Helper class is declared as a friend class of Box, which allows all the methods in the Helper class to access the private members of Box.
  • The Helper class methods can access and manipulate the Box class’s private data directly.

5. When to Use Friend Functions and Friend Classes?

Friend functions and friend classes are useful in the following scenarios:

1. Tightly Coupled Classes

When two or more classes are tightly coupled and need to access each other’s private or protected data, you can declare them as friend classes. This allows them to interact closely without exposing sensitive data to the outside world.

2. Utility or Helper Functions

Friend functions can be used when you have a utility function that operates on multiple objects of different classes and needs access to their private data. Rather than making the function a member of each class, you can declare it as a friend.

3. Performance Optimization

Sometimes, friend functions may be used to avoid unnecessary getters and setters when performance is critical, particularly when multiple functions need to access internal data directly.

4. Operator Overloading

In cases where operator overloading is needed, friend functions are often used to provide direct access to the private data of a class. This is particularly common with binary operators.


6. Friend Function and Friend Class Limitations

While friend functions and friend classes provide powerful capabilities, they come with some limitations:

  • Breaking Encapsulation: Overusing friend functions and friend classes can break the principle of encapsulation, as it gives external functions or classes direct access to private data.
  • Overuse: If too many classes or functions are declared as friends, it can make the code difficult to maintain and understand.
  • Limited Scope: Friend functions and classes are only allowed to access the private and protected members of the class they are declared as friends in. They do not have unrestricted access to all data in the program.