View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Friend Functions in C++ & Use Case with Examples

By Pavan Vadapalli

Updated on Nov 28, 2022 | 8 min read | 6.7k views

Share:

Data hiding is a fundamental software development technique widely used in object-oriented programming languages (OOPs). It restricts access to private data members from outside the class. However, a C++ feature known as the friend function goes against the data hiding principle.  

In this article, you will learn what is friend function in C++, what is a friend class and explore some use cases with examples.

Check out our free courses to get an edge over the competition.

What is the friend function in C++?

A friend function in C++ is a function declared outside a class but has access to the private and protected members of the class. Although the private members of a particular class are inaccessible to non-member functions, declaring them as friend functions gives them access to the private and protected members of the classes.

Check out upGrad’s Advanced Certification in DevOps 

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Characteristics of the Friend Function

The friend function in C++ has the following characteristics:

  • The friend function is outside the scope of the class to which it has been declared a friend
  • A friend function can either be a member of a class or a function declared outside the scope of the class
  • The friend functionality is not limited to a single class.
  • Invoking a friend function is like invoking any normal function of the class without using the object
  • We cannot invoke the friend function using the object since it is not in the scope of the class
  • Friend functions in C++ have objects as arguments
  • We can declare a friend function either in the private or public part
  • The member names are not directly accessible to a friend function, and it has to use the dot membership operator and object name with the member name

Check out upGrad’s Advanced Certification in Cyber Security

Syntax of the Friend Function

To declare the friend function, we use the friend keyword inside the body of the class. The syntax of the friend function is:

class className {

    … .. …

    friend returnType functionName(arg list);

    … .. …

}

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

If we break down the syntax, here’s what each term means:

  • friend is the keyword denoting that the function is a friend function
  • returnType is the return type of the function
  • functionName is the function’s name that’s made a friend of the class
  • arg list is the arguments we’ll pass

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Example of a C++ Friend Function

Now, let’s look at some programs to illustrate the friend function.

Example 1: C++ friend function to print the height of a box

#include <iostream>    

using namespace std;    

class Box    

{    

    private:    

        int height;    

    public:    

        Box(): height(0) { }    

        friend int printHeight(Box); //friend function    

};    

int printHeight(Box h)    

{    

   h.height += 40;    

    return h.height;    

}    

int main()    

{    

    Box h;    

    cout<<“Height of box: “<< printHeight(h)<<endl;    

    return 0;    

}

Output:

Height of box:40

Example 2: When the C++ friend function is friendly to two classes

#include <iostream>

using namespace std;

// forward declaration

class ClassQ;

class ClassP {

    public:

        // constructor to initialize numP to 12

        ClassP() : numP(12) {}

    private:

        int numP;

         // friend function declaration

         friend int add(ClassP, ClassQ);

};

class ClassQ {

    public:

        // constructor to initialize numQ to 1

        ClassQ() : numQ(1) {}

    private:

        int numQ;

        // friend function declaration

        friend int add(ClassP, ClassQ);

};

// access members of both classes

int add(ClassP objectP, ClassQ objectQ) {

    return (objectP.numP + objectQ.numQ);

}

int main() {

    ClassP objectP;

    ClassQ objectQ;

    cout << “Sum: ” << add(objectP, objectQ);

    return 0;

}

Output:

Sum:13

In the above example, Class P and Class Q have declared add()as a friend function, giving it access to the private data of both the classes. Moreover, the friend function inside Class P is using Class Q. 

So, we make a forward declaration of Class Q in the program.

Implementing a Friend Function

To get a better idea of the friend function in C++, we will now look at the two ways by which we can implement the friend function.

1. Implementing a friend function in C++ through a method of another class

We declare a friend class in C++ when we need access to the private and protected members of another class in which it has been declared a friend. It is also possible to declare a single member function of another class as a friend.

class class_name

{

      friend class friend_class;// declaring friend class

};

class friend_class

{

};

In the above declaration of friend class, all functions in friend_class are the friend functions of class_name.

Here’s a simple example to illustrate the implementation of friend functions through a method of another class:

#include <iostream>

using namespace std;

class A

{

   int p=4;

   friend class B; //friend class

};

class B

{

   public:

   void display (A &a)

     {

        cout<<”Value of p is:” <<a.p;

     }

};

int main ()

{

   A a;

   B b;

display (a);
    return 0;

}

Output:

Value of p is:4

2.Implementing a global function

Implementing a global friend function lets us access all the protected and private members of the global class declaration. Here’s an example:

#include<iostream>

using namespace std;

class space

{

    int a;

    int b;

    int c;

    public:

    void setdata (int x, int y, int z);

    void display(void);

     friend void operator- (space &s);

};

void space ::setdata (int x, int y, int z)

{

    a=x; b=y; c=z;

}

void space::display(void)

{

    cout<<a<<” “<<b<<” “<<c<<“\n”;

}

void operator- (space &s)

{

    s.a =- s.a;

    s.b =- s.b;

    s.c =- s.c;

}

int main ()

{

    space s;

setdata (9,2,3);
    cout<<“s:”;

display ();
    -s;

    cout<<“-s:”;

display ();
    return 0;

}

Output:

  s: 9 2 3                                                  

      -s: -9 -2 -3

In the above example program, operator- is the friend function that we globally declared at the scope of the class. 

What is friend class in C++?

Although it’s pretty evident by now, a friend class is a class that has access to both the private and protected members of the class in which it is declared a friend. 

In simple terms, a friend class in C++ is used when we want a class to have access to another class’s private and protected members.

The member functions of the class that we declare as a friend to another class are friend functions to the friend class. Thus, the friend functions link both the classes. 

Syntax of the Friend Class

Here’s the syntax of a friend class in C++:

class R; //forward declaration

class P{

  // Other Declarations

  friend class R;

};

class R{

  // Declarations

};

In the above illustration, Class R is a friend of Class P. As a result, Class R can access the private data members of Class P. However, the reverse is not true, and Class P cannot access the private data members of Class R. 

Also, the forward declaration is given to inform the compiler of the existence of an entity before it is categorically defined. Here, we declare the Class R using forward declaration to notify the compiler of its existence. The forward declaration allows us to use the objects of Class R in Class P.

What is the use of the friend function in C++?

Summing up our discussion, let us look at the two primary uses of the friend function in C++:

  • First, we use the friend function when we want to access the private and protected members of a class. To do this, we would generally require the objects of that class to access the private and protected members. However, the friend function eliminates the situation where the function needs to be a class member to gain access. 
  • Another use of the friend function in C++ is in operator overloading. Functions having the same name but different numbers and arguments are known as overloading functions. Friend functions in C++ find use in operator overloading.

In this case, the operator overloading function precedes the friend keyword and declares a function class scope. When overloaded by the friend function, binary operators take two explicit arguments while unary operators take one argument. It works the same way as a binary operator function, except that the friend operator function implementation takes place outside the scope of the class. 

That brings us to the end of our discussion on the friend function in C++ and its uses. Hope this helps you further your knowledge of C++.

Also, if you’re looking to launch your career as a full-stack developer, upGrad offers a fully online Executive Post Graduate Programme in Software Development – Specialisation in Full Stack Development of 13 months in collaboration with IIIT Bangalore.

Program Highlights:

  • Hands-on exposure to industry relevant case studies and assignments
  • 450+ hours of 360-degree learning
  • 10+ top programming tools and languages
  • 1:1 Career mentorship Sessions with industry mentors
  • 24/7 student support

Sign up today to get the exclusive upGrad benefits today!

Frequently Asked Questions (FAQs)

1. What is the friend function in C++?

2. How do you declare a friend function?

3. How do you make a class friend in C++?

Pavan Vadapalli

900 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

upGrad

Microsoft | upGrad KnowledgeHut

Microsoft Azure Data Engineering Certification

Access Digital Learning Library

Certification

45 Hrs Live Expert-Led Training

upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months