Browse by Domains

Friend Function in C++ and classes with Examples -2024

Introduction

In the world of object-oriented programming, encapsulation stands as a beacon of secure and structured code creation. C++ further elevates this principle by introducing a powerful yet judicious feature: the friend function, which adeptly navigates the fine line between maintaining encapsulation and allowing controlled access to class members. This remarkable tool, which can access the private and protected members of a class, offers programmers a higher degree of flexibility and efficiency in code development. In the midst of preserving the sanctity of data encapsulation, it facilitates a seamless interaction between classes, fostering a symbiotic relationship that can enhance the overall functionality of a software system.

In this tutorial, we will learn how to create a friend function in C++ with the help of some examples.

Data hiding is a fundamental concept in object-oriented programming, and it restricts the access of private members from outside the class.

What is a Friend Function in C++?

A friend function in C++ is defined as a function that can access private, protected, and public members of a class.

The friend function is declared using the friend keyword inside the body of the class.

Friend Function Syntax:

class className {
    ... .. ...
    friend returnType functionName(arguments);
    ... .. ...
}

By using the keyword, the ‘friend’ compiler understands that the given function is a friend function.

We declare a friend function inside the body of a class, whose private and protective data needs to be accessed, starting with the keyword friend to access the data. We use them when we need to operate between two different classes at the same time.

What is Friend Function?

Friend functions of the class are granted permission to access private and protected members of the class in C++. They are defined globally outside the class scope. Friend functions are not member functions of the class. So, what exactly is the friend function?

A friend function in C++ is a function that is declared outside a class but is capable of accessing the private and protected members of the class. There could be situations in programming wherein we want two classes to share their members. These members may be data members, class functions or function templates. In such cases, we make the desired function, a friend to both these classes which will allow accessing private and protected data of members of the class.

Generally, non-member functions cannot access the private members of a particular class. Once declared as a friend function, the function is able to access the private and protected members of these classes.

Upskill with other Programming languages

User-defined Function types

Friend functions in C++ have the following types

  • Function with no argument and no return value
  • Function with no argument but with return value
  • Function with argument but no return value
  • Function with argument and return value

Declaration of a friend function in C++

class class_name
{
   friend data_type function_name(arguments/s); //syntax of friend function. 
};

In the above declaration, the keyword friend precedes the function. We can define the friend function anywhere in the program like a normal C++ function. A class’s function definition does not use either the keyword friend or scope resolution operator (: 🙂.

Friend function is called as function_name(class_name) and member function is called as class_name. function_name.

Use of Friend function in C++

As discussed, we require friend functions whenever we have to access the private or protected members of a class. This is only the case when we do not want to use the objects of that class to access these private or protected members.

To understand this better, let us consider two classes: Tokyo and Rio. We might require a function, metro(), to access both these classes without any restrictions. Without the friend function, we will require the object of these classes to access all the members. Friend functions in c++ help us avoid the scenario where the function has to be a member of either of these classes for access.

C++ function overloading

Two functions can have the same name if the number and type of argument passed is different. Functions that have the same name , but have different arguements are called Overloading functions.

Friend functions are also used in operator overloading. The binary operator overloading in c++ using the friend function can be done as explained below.

Binary operator overloading in C++ using Friend function

The operator overloading function precedes a friend keyword in this approach. It also declares a function class scope. The friend operator function takes 2 parameters in a binary operator. It then varies one parameter in a unary operator.

The function will be implemented outside the class scope. But, the working and the implementation are the same as the binary operator function.

If you want to build your knowledge in C++, consider getting certified. This Introduction to C++ Free Course will help you learn the required skills and also a certificate on completion that can be added to your social profiles. You can also check out our Full Stack Program by IIT Roorkee.

Characteristics of Friend Function in C++

  • The function is not in the ‘scope’ of the class to which it has been declared a friend.
  • Friend functionality is not restricted to only one class
  • Friend functions can be a member of a class or a function that is declared outside the scope of class.
  • It cannot be invoked using the object as it is not in the scope of that class.
  • We can invoke it like any normal function of the class.
  • Friend functions have objects as arguments.
  • It cannot access the member names directly and has to use dot membership operator and use an object name with the member name.
  • We can declare it either in the ‘public’ or the ‘private’ part.
  • These are some of the friend functions in C++ characteristics

Implementing Friend Functions

Friend Functions can be implemented in two ways:

A method of another class:

We declare a friend class when we want to access the non-public data members of a particular class.

A Global function:

A ‘global friend function’ allows you to access all the private and protected members of the global class declaration.

A simple example of a C++ friend function used to print the length of the box.

Code:

#include <iostream>
using namespace std;
class Box
{
   private:
        int length;
   public:
         Box (): length (0) {}
   friend int printLength (Box); //friend function
};
int printLength (Box b)
{
    b. length +=10;
    return b. length;
}
int main ()
{
   Box b;
   cout <<” Length of box:” <<printLength (b)<<endl;
    return 0;
}

Output:

           Length of box:10

Simple example when the function is friendly for two classes.

Code:

#include<iostream>
using namespace std;
class B; //forward declaration.
class A
{
    int x;
    public:
         void setdata (int i)
           {
              x=i;
           }
    friend void max (A, B); //friend function.
} ;
class B
{
     int y;
     public:
          void setdata (int i)
            {
               y=i;
            }
     friend void max (A, B);
};
void max (A a, B b)
{
   if (a.x >= b.y)
         std:: cout<< a.x << std::endl;
   else
         std::cout<< b.y << std::endl;
}
  int main ()
{
   A a;
   B b;
    a. setdata (10);
    b. setdata (20);
    max (a, b);
    return 0;
}

Output:

        20                                         

In the above example, max () function is friendly to both class A and B, i.e., the max () function can access the private members of two classes.  

Implementing through a method of another class

A class cannot access the private members of another class. Similarly, a class cannot access its protected members of a class. We need a friend class in this case. 

A friend class is used when we need to access private and protected members of the class in which it has been declared as a friend. It is also possible to declare only one member function of another class to be a friend. 

Declaration of friend class

class class_name
{
      friend class friend_class;// declaring friend class
};
class friend_class
{
};

All functions in friend_class are friend functions of class_name.

A simple example of a friend class:

Code:

#include <iostream>
using namespace std;
class A
{
   int x=4;
   friend class B; //friend class
};
class B
{
   public:
   void display (A &a)
     {
        cout<<”value of x is:” <<a.x;
     }
};
int main ()
{
   A a;
   B b;
   b. display (a);
    return 0;
}

Output:

          value of x is:4     

Implementing a global function

Code:

#include<iostream>
using namespace std;
class space
{
    int x;
    int y;
    int z;
    public:
    void setdata (int a, int b, int c);
    void display(void);
     friend void operator- (space &s);
};
void space ::setdata (int a, int b, int c)
{
    x=a; y=b; z=c;
}
void space::display(void)
{
    cout<<x<<" "<<y<<" "<<z<<"\n";
}
void operator- (space &s)
{
    s.x =- s.x;
    s.y =- s.y;
    s.z =- s.z;
}
int main ()
{
    space s;
    s. setdata (5,2,9);
    cout<<"s:";
    s. display ();
    -s;
    cout<<"-s:";
    s. display ();
    return 0;
}

Output:

            s: 5 2 9                                                  

      -s: -5 -2 -9 

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

Friend Class in C++

What is a Friend class in C++?

Friend Class is a class that can access both private and protected variables of the class in which it is declared as a friend, just like a friend function. Classes declared as friends to any other class will have all the member functions as friend functions to the friend class. Friend functions are used to link both these classes.


Friend Class in C++ Syntax:

class One{
<few lines of code here>
friend class Two;
};
class Two{
<few lines of code>
};

Note : Unless and until we declare, class friendship is neither mutual nor inherited.

To make you understand in detail:

  • If class A is a friend of class B, then class B is not a friend of class A.
  • Also, if class A is a friend of class B, and then class B is a friend of class C, class A is not a friend of class C.
  • If Base class is a friend of class X, subclass Derived is not a friend of class X; and if class X is a friend of class Base, class X is not a friend of subclass Derived. 

Advantages of friend function in C++

  • Friend function in c++ provide a degree of freedom in the interface design option
  • A friend function is used to access all the non-public members of a class.
  • You can use a friend function to bridge two classes by operating objects of two different classes.
  • It increases the versatility of overloading operators.
  • It enhances encapsulation. Only the programmer who has access to the class’s source code can make a function friend to that class.
  • You may declare a member function of a class as a friend of another class.
  • It works symmetrically with all its friends.

Summary of C++ Friend Function

  • Even though the prototypes for friend functions appear in the class definition, friends are not members functions.
  • We can declare friend functions anywhere in a class definition, that is either in public, private or protected sections.
  • We can do friend declarations anywhere in a class definition, i.e. either in public, private or protected sections.
  • Violates the data hiding principle of classes, so we should avoid it as much as possible. You can grant friendship but not take it, i.e., for class B to be a friend of class A, class A must explicitly declare that class B is its friend. The friendship relation is neither symmetric nor transitive. Friend relationship cannot be inherited.

This brings us to the end of the blog on Friend functions in C++. Hope this helps you to up-skill your C++ skills. Also, if you are preparing for Interviews, check out these Interview Questions for C++ to ace it like a pro.

FAQs


What is the friend function in C++?

In C++, a function that has access to a class’s private, protected, and public members is referred to as a friend function. Within the class’s body, the friend keyword is used to declare the friend function.

What is friend function with example?

In C++, a friend function is a unique function that, although not being a member of a class, has the ability to access secret and protected data. Using the term “friend” inside the class, a friend function is a non-member function or regular function of a class that is specified as a friend.

What are the advantages of the friend function in C++?

Some of the advantages of the friend function in c++ are
1. It enables a non-member function to share confidential class information.
2. It makes it simple to access a class’s private members.
3. It is frequently used when two or more classes include members that are connected to other programme elements.
4. It enables the creation of more effective code.
5. It offers extra capabilities that the class does not typically use.
6. It permits a non-member function to share confidential class information.

What are the limitations of friend function?

The major disadvantage of friend functions is that they occupy the maximum size of the memory and can’t do any run-time polymorphism concepts.

Avatar photo
Great Learning Team
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

Your email address will not be published. Required fields are marked *

Great Learning Free Online Courses
Scroll to Top