Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Friend Functions in C++ & Use Case with Examples

By Pavan Vadapalli

Updated on Nov 28, 2022 | 8 min read

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

    … .. …

}

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

967 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

RecommendedPrograms

SuggestedBlogs