Signup/Sign In

C++ Friend Function Program

Hello Everyone!

In this tutorial, we will learn how to demonstrate the concept of Friend Function, in the C++ programming language.

To understand the concept of Friend Function and various other types of Class Member functions in CPP, we will recommend you to visit here: C++ Types of Member Function, where we have explained it from scratch.


#include <iostream>

using namespace std;

//Class Volume to demonstrate the concept of Friend Function in CPP
class Volume {
    //Member variables are declared as private and hence cannot be simply accessed from outside the class
        int liter;

    //Initializing the value of variable liter to 2 using the default constructor
        Volume(): liter(2) {}

    //Declaring the Friend Function for the class Volume
    friend int mulFive(Volume);

// Defining the Friend Function to be used by the Volume Class
int mulFive(Volume v) {
    //Friend function enables accessing private data from non-member function
    v.liter *= 5;
    return v.liter;

//Defining the main method to access the members of the class
int main() {

    cout << "\n\nWelcome to Studytonight :-)\n\n\n";
    cout << " =====  Program to demonstrate the working of a Friend Function in CPP  ===== \n\n";

    //Declaring the Class objects to access the class members
    Volume vol;

    cout << "Volume after calling the Friend Function = " << mulFive(vol);

    cout << "\n\n\n";

    return 0;


C++ friend function

We hope that this post helped you develop a better understanding of the concept of Friend Function in C++. For any query, feel free to reach out to us via the comments section down below.

Keep Learning : )

About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.