Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconFriend Functions in C++ & Use Case with Examples

Friend Functions in C++ & Use Case with Examples

Last updated:
21st Oct, 2022
Views
Read Time
8 Mins
share image icon
In this article
Chevron in toc
View All
Friend Functions in C++ & Use Case with Examples

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.

Ads of upGrad blog

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.

Explore our Popular Software Engineering Courses

  • 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);

    … .. …

}

In-Demand Software Development Skills

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;    

}    

Read our Popular Articles related to Software Development

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;

  1. display (a);

    return 0;

}

Output:

Value of p is:4

  1. 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;

  1. setdata (9,2,3);

    cout<<“s:”;

  1. display ();

    -s;

    cout<<“-s:”;

  1. 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++. 

Ads of upGrad blog

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!

Profile

Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.

Frequently Asked Questions (FAQs)

1What is the friend function in C++?

A friend function in C++ is a function that’s not a member of a class but has access to its private and protected members.

2How do you declare a friend function?

A friend function has access to a class's private and protected data. To declare a friend function, we use the friend keyword inside the body of the class.

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

We use the friend keyword to declare a class as a friend class in C++. The keyword lets any class access private and protected members of other classes and functions.

Explore Free Courses

Suggested Blogs

What is Composition in Java With Examples
64744
Java is a versatile language that supports object-oriented programming and code reusability with building relationships between two classes. There are
Read More

by Arjun Mathur

19 Feb 2024

Software Engineer / Developer Salary in India in 2024 [For Freshers &#038; Experienced]
906831
Summary: In this article, you will learn about Software Engineer Salary in India based on Location, Skills, Experience, country and more. Today softw
Read More

by Rohan Vats

Top 40 Most Common CSS Interview Questions and Answers [For Freshers &#038; Experienced]
15166
Every industry has started the use of websites and applications to catch up with the pace of the rapidly transforming world. CSS is one of the most cr
Read More

by Rohan Vats

19 Feb 2024

Top 10 Highest Paying Programming Languages In India [2024]
94688
Programmers and Developers are among the highest-paid professionals in the world. They earn six-figure annual salary packages in countries like the US
Read More

by Rohan Vats

19 Feb 2024

Top 12 Highest Paying Online Software Courses in India [2024]
34061
The demand for innovative software products and solutions is at an all-time high, and rest assured, it will only peak higher in the coming years. One
Read More

by Rohan Vats

19 Feb 2024

23 Exciting Software Development Project Ideas &#038; Topics for Beginners [updated 2024]
914957
Summary: In this article, you will learn the 23 Exciting Software Development Project Ideas & Topics for 2023. Take a glimpse below. Android tas
Read More

by Rohan Vats

19 Feb 2024

Must Read 50 OOPs Interview Questions &#038; Answers For Freshers &#038; Experienced [2024]
122194
Attending a programming interview and wondering what are all the OOP interview questions and discussions you will go through? Before attending an inte
Read More

by Rohan Vats

18 Feb 2024

25 Exciting Best Django Project Ideas &#038; Topics For Beginners [2023]
135693
What is a Django Project? Django projects with source code are a collection of configurations and files that help with the development of website app
Read More

by Kechit Goyal

18 Feb 2024

44 Must Know Agile Methodology Interview Questions &#038; Answers: Ultimate Guide 2024
162709
Attending an agile interview and wondering what are all the questions and discussions you will go through? Before attending an agile testing interview
Read More

by Arjun Mathur

18 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon