Sitemap

friend function in C++

8 min readJan 4, 2025

--

Press enter or click to view image in full size
Friend function

In class the object are private and we cannot access them outside of the class directly. For this we require member function to access the private variables in the class.

Unlike, member function, a function which is not defined in the class can also have access to the private variable of the class. This kind of function is called the friend function of that class.

The way to define the friend function is by putting the keyword friend as the prefix at the time of function declaration and we have to declare the function inside the class, and the function is defined outside the class without using the friend keyword.

Syntax of friend function

class ClassName {
friend ReturnType FriendFunctionName(Arguments);
// Other class members...
};

Example

Let’s say we want to declare a class Cuboid with variable length, width and height and have to declare the friend function to calculate the volume of the cuboid.

#include <iostream>
using namespace std;

class Cuboid {
private:
double length;
double width;
double height;

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

// Declare the friend function
friend double calculateVolume(const Cuboid& c);
};

// Friend function definition
double calculateVolume(const Cuboid& c) {
// Can access private members of Box because it's a friend
return c.length * c.width * c.height;
}

int main() {
Cuboid cuboid(5.0, 4.0, 3.0); // Create an object of Box
cout << "Volume: " << calculateVolume(cuboid) << endl; // Call the friend function
return 0;
}

Practice Questions

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

2. Can a friend function be called without creating an object of the class? Why or why not?

3. What makes a friend function different from a normal non-member function in terms of accessing private/protected data?

4. Can a single function be a friend to multiple classes?

(Answer to this questions can be found at the bottom of the page)

Friend Class

Similar to friend function we can make an entire class friend of another class. For example, if there are two classes, class A and class B and in class A we had declare class B as friend then class B can access all the private and proctected members of the class whereas class A cannot access B’s private and protected members.

class ClassA {
private:
int privateData;

protected:
int protectedData;

public:
ClassA() : privateData(10), protectedData(20) {}

friend class ClassB; // Declaring ClassB as a friend
};

class ClassB {
public:
void accessClassA(ClassA &obj) {
// Accessing private and protected members of ClassA
cout << "Private Data: " << obj.privateData << endl;
cout << "Protected Data: " << obj.protectedData << endl;
}
};

Explanation of the Example

  1. ClassA declares ClassB as a friend using friend class ClassB;.
  2. Because of this declaration, ClassB can directly access ClassA's private and protected members.
  3. In the function accessClassA, ClassB accesses ClassA's private and protected members without using setters or getters.

Practice Questions

5. Can a friend class access both private and protected members of another class?

6. If ClassA declares ClassB as a friend, does ClassB automatically allow ClassA the same access?

Operator overloading using friend and member function and what is the difference between them

Press enter or click to view image in full size

Let’s first discuss overloading the ‘+’ operator using the member function. For doing so, we need to pass only one parameter, note will be passing two parameter for doing the same operator overloading while doing it with the friend function.

class Complex {
private:
int a, b;
public:
Complex operator+(const Complex &C2) {
Complex temp;
temp.a = this->a + C2.a; // 'this' refers to the implicit first operand
temp.b = this->b + C2.b;
return temp;
}
};

In this case:

  • this->a and this->b refer to the private members of the left-hand operand.
  • C2.a and C2.b refer to the second operand explicitly passed as a parameter.

Usage

Complex C1, C2, C3;
C1.setData(1, 2);
C2.setData(3, 4);
C3 = C1 + C2; // Here, C1 is the implicit first operand, and C2 is the explicit second operand.

C1 is calling the + operator function, and C2 is passed to it as an argument.

So, in case of member function the compiler rewrites C1 and C2

C3 = C1.operator+(C2);

Doing operator overloading using the friend function

As Friend function, all object is passed as an arguement unlike the member function. It is not the member of the class so we cannot use the this pointer, so it cannot implicitly refer to any object.

class Complex {
private:
int a, b;
public:
friend Complex operator+(const Complex &C1, const Complex &C2);
};
Complex operator+(const Complex &C1, const Complex &C2) {
Complex temp;
temp.a = C1.a + C2.a; // Access both operands explicitly
temp.b = C1.b + C2.b;
return temp;
}

In this case:

  • Both operands (C1 and C2) are passed explicitly to the friend function.

Usage:

Complex C1, C2, C3;
C1.setData(1, 2);
C2.setData(3, 4);
C3 = C1 + C2; // Both C1 and C2 are passed explicitly to the friend function.

In this case,

  1. C1 and C2 are both explicitly passed to the + operator function:

Unlike a member function, the friend function is not called on an object. Instead, both operands (C1 and C2) are explicitly passed as arguments to the operator+ function.

2. The + operator function accesses the private members of both C1 and C2 directly:

Get Shubham Dubey’s stories in your inbox

Join Medium for free to get updates from this writer.

Since operator+ is declared as a friend of the Complex class, it can directly access the private members of the class (a and b) for both operands.

+ operator function is called, and C1 and C2 are passed as an argument .

or

C1 and C2 are passed as explicit arguments to the + operator function, which is a friend of the Complex class.

So, in case of friend function the compiler, rewrites C1 and C2 as

C3 = operator+(C1, C2);

Why the Difference?

  • A member function has access to the this pointer, representing the object on the left-hand side of the operator. Hence, it only needs one parameter for the right-hand side operand.
  • A friend function is external to the class, so it requires all operands to be passed explicitly.

Key Considerations:

  • Symmetry: Friend functions treat both operands equally, which is useful when you want to allow implicit conversions for either operand.
  • Member access: Member functions can only be used for operators where the left-hand operand is an object of the class, whereas friend functions can be more flexible. For example:
  • obj + 5 works fine with both member and friend functions.
  • 5 + obj works only with friend functions unless you explicitly define a separate member function or operator.

Practice Questions

7. Can a member function be used for operator overloading?

8. What’s a better alternative to using friend functions when you only need to access specific private members of a class?

9. Why might a friend function be a better choice for overloading a binary operator involving two different classes?

10. Why should friend functions and their definitions be kept in the same file?

It’s all about the friend function.

Thanks for reading.

Enjoy learning 😊

Answers

  1. A friend function is declared inside a class using the friend keyword. For example:
friend double calculateVolume(const Cuboid& b);

2. A friend function cannot be called without creating an object of the class because it requires objects to work with. What Happens Without an Object? If a friend function tries to access private members without being given an object, it will result in a compilation error because there is no instance whose members it can refer to.

class Complex {
private:
int real, imag;
public:
void setData(int r, int i) {
real = r;
imag = i;
}
friend void showComplex(const Complex &C); // Friend function
};

void showComplex(const Complex &C) {
cout << "Real: " << C.real << ", Imaginary: " << C.imag << endl;
}

int main() {
Complex C1;
C1.setData(3, 4);

showComplex(C1); // C1 is explicitly passed to access its data
return 0;
}

// if we don't pass any object it will give compilation error

void showComplex() {
cout << real << " " << imag; // Error: real and imag are undefined
}

3. Friend functions can directly access the private and protected members of the class they’re friends with. This makes them distinct from normal non-member functions, which cannot access private/protected data unless granted access explicitly.

4. Yes, it’s possible that a single function can be a friend to multiple class but only prequisite is that the function should be declare in each of the class with the keyword “friend”.

5. A friend class has full access to both private and protected members of the class that declares it as a friend. This is true for friend functions as well.

6. Friendship is not mutual in C++. If ClassA declares ClassB as a friend, ClassA grants ClassB access to its private/protected members. However, ClassB does not automatically grant the same access to ClassA. Friendship must be explicitly declared in both classes if mutual access is needed.

7. Yes, a member function can be used for operator overloading, but with certain conditions.

  • The left operand is an object of the class itself (i.e., an instance of the class).
  • The operator needs to modify or access the internal state of the object (i.e., it’s a member of that class).

8. Use public getter and setter methods. These methods allow controlled access to private members, maintaining encapsulation while providing the necessary functionality.

9. A friend function is better when:

  • Neither class should be responsible for the operator.
  • The left-hand operand is not an object of the class, and a member function wouldn’t work.
  • Both classes’ private/protected members need to be accessed.

Example:

In the operator+ overload between ClassA and ClassB, neither class is responsible for the operation. The friend function can independently access private data from both.

int operator+(const ClassA& a, const ClassB& b) {
return a.valueA + b.valueB; // Direct access to private members
}

If this were a member function, it would only have access to the private data of the class it belongs to.

10. To maintain clarity and cohesion:

  • It signals that the friend function is closely related to the class and not a general-purpose function.
  • This makes it easier for other developers to understand the relationship between the function and the class.

Example:

class Box {
friend double calculateVolume(const Box& b); // Declaration here
};

double calculateVolume(const Box& b) {
return b.length * b.width * b.height; // Implementation nearby
}

Keeping the declaration and implementation in the same file ensures the function’s intent and context are clear.

--

--

Written by Shubham Dubey

I write to better understand what I had learned.