Back to C++
2026-03-176 min read

C++ Friend Functions

Learn C++ Friend Functions step by step with clear examples and exercises.

Why This Matters

In this full guide on C++ Friend Functions, we'll delve into their importance, prerequisites, core concept, worked examples, common mistakes, practice questions, and frequently asked questions. This lesson aims to provide you with an in-depth understanding of friend functions, setting it apart from other tutorials.

Why This Matters

Friend functions are essential in C++ programming as they offer an alternative to public/private access specifiers for controlling access to member functions and variables within classes. They allow access to a function or variable defined outside the class without making it a member of that class, promoting efficient, modular, and maintainable code.

Prerequisites

Before diving into friend functions, ensure you have a solid understanding of the following concepts:

  1. Basic C++ syntax and semantics
  2. Classes and objects
  3. Access specifiers (public, private, protected)
  4. Function overloading and templates
  5. Inheritance and polymorphism
  6. Understanding of member functions, data members, and the this pointer

Core Concept

Friend functions are non-member functions that have access to the private and protected members of a class, just like member functions do. To declare a function as a friend, you use the friend keyword followed by the function prototype within the class declaration. Here's an example:

class MyClass {
private:
int myPrivateVar;

friend void printMyPrivate(MyClass &obj); // declare printMyPrivate as a friend
};

void printMyPrivate(MyClass &obj) {
std::cout << obj.myPrivateVar; // access MyClass's private member variable
}

In this example, printMyPrivate is granted access to the private member myPrivateVar of MyClass. Note that friend functions are not members of the class and do not have a this pointer.

Friend Classes

Friend classes grant all of their member functions access to the private and protected members of the class they are friends with, without the need to list each function individually. To declare a class as a friend, use the friend keyword followed by the class name within the class declaration.

class MyClass {
private:
int myPrivateVar;

friend class MyFriendClass; // declare MyFriendClass as a friend
};

class MyFriendClass {
public:
void printMyPrivate(MyClass &obj) {
std::cout << obj.myPrivateVar; // access MyClass's private member variable
}
};

Worked Example

Let's consider a simple example where we have a SavingsAccount class with a private data member balance, and we want to create a function outside of the class to deposit money into the account:

class SavingsAccount {
private:
double balance;

friend void deposit(SavingsAccount &account, double amount); // declare deposit as a friend
public:
SavingsAccount(double initialBalance) : balance(initialBalance) {}
};

void deposit(SavingsAccount &account, double amount) {
if (amount > 0) {
account.balance += amount; // access SavingsAccount's private member variable
} else {
std::cout << "Invalid deposit amount.\n";
}
}

In this example, we have declared the deposit function as a friend of the SavingsAccount class. Now, we can deposit money into an account without making the deposit function a member of the SavingsAccount class:

int main() {
SavingsAccount myAccount(100); // create a savings account with initial balance 100
deposit(myAccount, 50); // deposit 50 into the account
return 0;
}

Common Mistakes

  1. Forgetting to declare a friend function within the class declaration: Friend functions must be declared as friends before they are defined outside of the class.
  2. Misusing friend functions for public member access: Friend functions should not be used as a workaround for public member access when it is appropriate to use public members instead.
  3. Using friend functions without proper naming conventions: Adhere to consistent naming conventions for friend functions, such as prefixing the function name with the class name followed by an underscore.
  4. Ignoring the lack of a this pointer in friend functions: Remember that friend functions do not have access to the this pointer and must receive their object arguments explicitly.
  5. Overusing friend functions: Friend functions should be used judiciously, as they can lead to code that is difficult to maintain and understand if misused.
  6. Not defining a friend function before its first use: If a friend function is not defined within the class declaration, it must be defined before its first use outside of the class. Failing to do so will result in a compile error.
  7. Friend functions cannot access static members: Friend functions do not have access to static members of a class. To access static members from a friend function, you can make them friends as well or use member functions to interact with static members.

Practice Questions

  1. Write a class Circle with a private data member radius. Declare a function getArea outside of the class as a friend function to calculate the area of the circle.
  2. Modify the SavingsAccount example to include a constructor that initializes the account balance and a deposit function that checks if the deposit amount is valid before updating the balance.
  3. Given the following class declaration, what does the friend function swap do?
class MyClass {
private:
int data;

friend void swap(MyClass &a, MyClass &b);
};

void swap(MyClass &a, MyClass &b) {
std::swap(a.data, b.data);
}
  1. Write a class Rectangle with private data members length and width. Declare friend functions to calculate the area and perimeter of the rectangle.
  2. Create a class Student with private data members name, age, and grade. Declare friend functions to print the student's details and compare two students based on their grades.

FAQ

  1. Can a friend function access private members of the class it is not a member of? Yes, friend functions can access private and protected members of a class they are declared as friends of, even if they are not members of that class.
  2. Can a friend function be a member function of another class? No, friend functions cannot be member functions of another class. They must be defined outside of the class they are friends with.
  3. Can I declare multiple friend functions for the same class? Yes, you can declare multiple friend functions for the same class by listing them in the class declaration.
  4. What happens if a friend function is not defined within the class declaration? If a friend function is not defined within the class declaration, it must be defined before its first use outside of the class. Failing to do so will result in a compile error.
  5. Can I make a constructor a friend function? No, constructors cannot be declared as friend functions because they are special member functions and do not have return types. However, you can declare other member functions as friends within the constructor initialization list or class body.
  6. Can I make a static member function a friend of another class? Yes, you can make a static member function a friend of another class by declaring it as a friend within the class declaration. Since static members are not associated with any particular object, they do not have access to the this pointer and cannot call non-static member functions directly.
  7. Can I make a template function a friend of a class? Yes, you can make a template function a friend of a class by declaring it as a friend within the class declaration. However, when instantiating the template function for specific types, ensure that the appropriate access level is granted to the instantiation.
  8. Can I make a lambda function a friend of a class? Yes, you can make a lambda function a friend of a class by declaring it as a friend within the class declaration. However, when capturing variables by reference or copy inside the lambda function, be aware that they may not have the expected behavior if the lambda function is called from outside the class.
C++ Friend Functions | C++ | XQA Learn