All Courses
OOP: ACCESS SPECIFIERS

Friend Functions

A friend function is not a member function, but it is allowed to access private and protected members of a class.

Friendship is granted by the class.

Syntax

friend void functionName(ClassName object);

Example

#include <iostream>

class Box {
private:
    double width = 0.0;

public:
    explicit Box(double boxWidth) : width(boxWidth) {}

    friend void printWidth(const Box& box);
};

void printWidth(const Box& box) {
    std::cout << "Width: " << box.width << '\n';
}

int main() {
    Box box(10.5);
    printWidth(box);
}

Important Rules

A friend function:

  • is not a member of the class
  • has no this pointer
  • is called like a normal function
  • can access private/protected members through an object
  • can be declared in public or private section with the same meaning

Why Use Friend Functions?

Common uses:

  • operator overloading such as operator<<
  • functions needing private data from more than one class
  • tightly related helper functions

Friend Function Warning

Friend functions weaken encapsulation if overused.

Use them only when they make the interface cleaner or are required by operator syntax.

Viva Answer

A friend function is a non-member function that is granted access to a class's private and protected members. It is useful for some operator overloads and tightly related helper functions, but it should be used carefully because it weakens encapsulation.

Quick Check

  • Is a friend function a member function?
  • Does a friend function have this?
  • How is a friend function called?
  • Why should friend functions be used carefully?