What Is Friend Function in C++ | DataTrained

Sanjukta Deka Avatar

Introduction To Friend Function

Non-member actions of a class will not have accessibility to another class’s secret data. There may be times when we need two classes to share some methods and data members. In such a situation, we may declare the function a buddy of these classes, allowing it to access the classes’ secret and protected data members. In this post, we’ll look at how to add a non-member function to a class as a friend. In this blog, we will help you understand what is friend function.

Friend Functions

Friend FunctionA friend function is a function that has been declared outside of a class but has access to the protected and private data of the class members. A friend can be a member’s function, function template, or function, as well as a class or class template, wherein case the whole class and all of its members, are friends. If you are also confused about what is friend function is, this blog will help you to get familiar with this topic.

In C++, friend functions of the class are allowed access to the class’s private and protected members. They are specified globally, outside of the scope of the class. Friend functions are not class member functions. So, now what is friend function? Data members, class functions, or function templates are examples of these members. In such circumstances, we add the desired function as a buddy to both of these classes, allowing access to the class’s secret and protected data members.

What Is The Purpose of Friend Functions?

We require friend functions in specific instances when a class’s secret data has to be accessed directly without utilizing objects from that class. Consider the following two classes: Director and Doctor. We will want the gross salary function to act on the objects of each of these types. The function does not have to belong to any of the classes.

Because they are more intuitive, they are also utilized in operator overloading. The binary arithmetic operator, which is widely used, maybe overloaded using the buddy function method. For additional details, visit operator overloading using a friend function.

Characteristics Of Friend Function:

  • A friend function does not fall inside the scope of the class for which it was designated as a friend. As a result, functionality is not restricted to a single class.
  • The friend function might be a member of some other class or a function that is not inside the scope of the class.
  • A friend function is defined in either the private or public parts of a class without affecting its meaning.
  • Friend functions are not invoked with class objects since they are not inside the scope of the class.
  • The friend function can be called like any other member function without the use of an object.
  • Friend functions can take objects from the class as arguments.
  • A friend function may not directly access member names. Every member’s name must include the object’s name as well as the dot operator. For instance, Doctor. pay, while pay is the name of the object.

Purpose Of Friend Function In C++

In C++, the Friend function is used.

As previously stated, we need to know what is friend functions whenever we need to access a class’s secret or protected members. This is true only when we do not wish to utilize the objects of that class to access the private or protected members.

To further comprehend this, consider two classes: Tokyo and Rio. We may need a function, metro(), to have unrestricted access to both of these classes. Without the friend method, we’ll need to use the object of these classes to access all of its members. Friend functions allow us to escape the situation in which the function must be a member of either of these classes in order to be accessed. Our blog on what is friend functions, will help you understand what is friend function. 

In C++, a friend function is one that may access private, protected, and public elements of a class. The friend function is declared within the class’s body using the friend keyword.

Friend Function Syntax: 

class className {

    … .. …

    friend returnType functionName(arguments);

    … .. …

}

The ‘friend’ compiler recognizes that the supplied function is a friend function by utilizing the keyword.

In our blog on what is friend function, you need to know that we define the friend function within the body of a class whose private and protected data must be accessible, beginning with the keyword friend to access the data. We utilize them when we need to switch between two classes at the same time.

Advantages Of Friend Function In C++

In our blog on what is friend function. Let’s see some of the major advantages of the friend function:

  • The friend function enables programmers to write more efficient code.
  • It permits a non-member function to share confidential class information.
  • It quickly gains access to a class’s non-public members.
  • It is commonly used when two or more classes include members that are connected to other areas of the program.
  • It enables additional functionality that is not usually utilized by the class.
  • It improves the adaptability of overburdened operators.
  • It improves encapsulation. Only the programmer with access to the source code of the class can add a function friend to it.
  • A class’s member function can be declared as a friend of another class.
  • It collaborates symmetrically with all of its friends.

User-Defined Function Types

User Defined Function types

  • No-argument function with no return value.
  • No-argument function with a return value.
  • There is an argument to the function, but there is no return value.
  • The function has an argument and a return value.

Friend Class

A friend class can access the data members and methods of another class that has defined it as a friend. They are utilized when we want one class to have access to the private and protected members of another class.

When a class declares itself to be a friend of another class, all of its member functions become friend functions to the friend class. Friend functions are used to connect classes. You can learn more about friend class from here. If you are still confused about what is friend function, then let’s take a look at this:

Syntax of friend class:

class S; //forward declaration

class P{

  // Other Declarations

  friend class S;

};

class S{

  // Declarations

};

Class S is a buddy of class P in the graphic above. As a result, class S has access to class P’s secret d
ata members. This does not, however, imply that class P has access to secret data members of class S. A forward declaration notifies the compiler about the existence of an entity before it is officially specified.

We used forward declaration to notify the compiler of the existence of class S, allowing us to utilize class S objects in class P.

Unless we make it so, class friendship is hardly hereditary nor mutual. This indicates that because class S is a friend of class P, it is also a friend of class P’s sub-classes.

An Example of a program to demonstrate the friend class:

#include

using namespace std;

// forward declaration

class ClassY;

class ClassX

{

int digit1;

  // friend class declaration

  friend class ClassY;

  public:

      // constructor to initialize num1 to 10

      ClassX() : digit1(10) {}

};

class ClassY {

    int digit2;

    public:

        // constructor to initialize num2 to 5

        ClassY() : digit2(5) {}

    // member function to multiply num1

    // from ClassX with num2 from ClassY

    int multiply() {

        ClassX m;

        return m.digit1 * digit2;

    }

};

int main() {

    ClassY n;

    cout << “Multiplication: ” << n.multiply();

    return 0;

}

The Output will be: Multiplication: 50

Declaration Of A Friend Function In C++

In our blog on what is friend function let’s understand how to declare a friend function:

class class_name

{

   friend data_type function_name(arguments/s); //syntax of friend function.

};

The keyword friend comes before the function in the following declaration. The friend function, like any other C++ function, can be defined anywhere in the program. The keyword friend or the scope resolution operator are not used in the function declaration of a class. function name(class name) is the name of a friend function, and the function name is the name of a member function. In our blog on what is friend function is, let’s understand the binary operator next in our what is friend function.

Binary Operator Overflowing In C++ Using Friend Function

It also specifies the scope of a function class. In a binary operator, the friend operator function takes two arguments. It then changes one of the parameters of a unary operator. The method will be implemented outside of the scope of the class. However, the operation and implementation are identical to those of the binary operator function.

Implementing Friend Functions 

Implementing Friend Functions

In our blog on what is friend function, we have tried to easily help you understand how to implement friend functions. There are two approaches to building Friend Functions:

A Method From Another Class: 

We declare a Friend class when we wish to access a class’s non-public data elements.

 A Global Function:

 A ‘global friend function’ lets you access all of the global class declaration’s secret and protected members. A basic C++ friend function is used to output the length of the box.

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

Code:

#include

using namespace std;

class Box

{

   private:

        int length;

   public:

         Box (): length (0) {}

friend int printLength (Box); //what is friend function

};

int printLength (Box b)

{

  1. length +=10;

    return b. length;

}

int main ()

{

   Box b;

 cout <<” Length of box:” <

    return 0;

}

Output: Length of box:10

For example when the function is friendly for two classes.

Code:

#include

using namespace std;

class B; //forward declaration.

class A

{

    int x;

  public:

         void setdata (int i)

           {

              x=i;

           }

friend void max (A, B); //what is 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;

  1. setdata (10);
  2. setdata (20);

    max (a, b);

    return 0;

}

Output:   20      

Implementing Through A Method Of Another Class

A class does not have access to the private members of another class. Similarly, a protected member of a class cannot be accessed. In this case, we require a friend class.

When we need to access secret and protected members of a class that has been defined as a friend, we utilize a friend class. It is also feasible to make only one member function of another class a friend. If you are still wondering what is friend function is then try to execute the code in a terminal or other environment.

Declaration Of Friend Class

class class_name

{

friend class friend_class;// declaring friend class

};

class friend_class

{

};

A simple example of a friend class:

Code:

#include

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;

  1. display (a);

    return 0;

}

Output:

value of x is:4   

Conclusion

We learned about what is friend functions and friend classes are in this article, including what they are and how they are used. By making a function and class “friendly,” we limit the number of functions and, as a result, create programs that are manageable and simple to understand. Friends are not members’ functions, even though prototypes for friend functions exist in the class specification. 

What is friend function, it can be declared anywhere in a class definition, whether in the public, private, or protected sections. Friend declarations can be made anywhere in a class definition, i.e. in the public, private, or protected sections. It violates the class’s data concealing concept, thus we should avoid it as much as feasible. You can give but not accept friendship; that is, for class B to be a friend of class A, class A must expressly state that class B is its friend. There is no symmetry or transitivity in the friendship relationship. Friendship cannot be passed down across generations. I hope our blog on what is friend function helps you understand what is friend function.

This takes us to the conclusion of the blog on C++ friend functions. I hope this helps you improve your C++ abilities. If you still have any doubts about our blog of what is friend function then feel free to contact us. Check out Coding Computer Programming’s best guide to ace it. 

Frequently Asked Question’s

1. What is friend function with an example?

A friend function is a function that is defined outside of a class but has access to the class’s private and protected members. There may be moments in programming when we want two classes to share their members.

These individuals might be data members, class functions, or function templates. If you want to learn more about friend function check out our blog on what is friend function.

2. What is friend function and its characteristics?

A friend function is a function that is defined outside of a class but has access to the class’s private and protected members. There may be moments in programming when we want two classes to share their members. These individuals might be data members, class functions, or function templates. In our blog on what is friend function let’s look at the characteristics of LWC: 

Characteristics of what is friend function:

The function does not belong to the class to which it has been added as a friend. It cannot be accessed via the object since it is not within the scope of that class. It may be called like any other function without the use of an object.

Some of the important characteristics are:

  • A friend function does not fall inside the scope of the class for which it was designated as a friend. As a result, functionality is not restricted to a single class.
  • The friend function might be a member of some other class or a function that is not inside the scope of the class.
  • A friend function is defined in either the private or public parts of a class without affecting its meaning.
  • Friend functions are not invoked with class objects since they are not inside the scope of the class.
  • The friend function can be called like any other member function without the use of an object.
  • Friend functions can take objects from the class as arguments.
  • A friend function may not directly access member names. Every member’s name must include the object’s name as well as the dot operator. For instance, Doctor. pay, while pay is the name of the object.

3. What Is friend function in Java?

The friend keyword from C++ does not exist in Java. There is, however, a method to imitate that; a manner that provides far more accurate control. Assume you have classes A and B. A requires B to have access to a secret method or field in A.

4. What is friend function in OOP?

In object-oriented programming, a friend function, often known as a “friend” of a particular class, is a function that has the same access to private and protected data as methods. A friend function is declared by the class that is giving access, hence friend functions, like methods, are part of the class interface.

5. What is a wrapper object in Java?

A Wrapper class is one whose object contains or covers primitive data types. When we construct an object for a wrapper class, it has a field where we may put primitive data types. To put it another way, we can turn a primitive value into a wrapper class object. Wrapper Classes are needed.

6. What is friend function and does it violate encapsulation?

A friend function in a class declaration does not violate encapsulation any more than a public member function does: both have the same power to access the class’s non-public elements. In object-oriented programming, a “friend” function of a particular class is granted access to secret and protected data in that class that it would not ordinarily be able to access if the data were public. Friends should be utilized cautiously. 

Too many methods or external classes defined as friends of a class containing protected or secret data may reduce the efficacy of encapsulation of distinct classes in object-oriented programming and indicate a flaw in the overall architecture design. In general, If you are still confused about what is friend functions are then they are ideal for encapsulation since they allow you to keep a class’s data secret from everyone except those who expressly say that they require it, but this does imply that your classes will become closely connected.

7. Is there any advantage of using the friend function?

A class’s friend function is a ‘non-member function.’ It has access to members of the class who are not publicly visible. A friend function is defined outside of the class declaration. If you are still confused about what is friend function then our blog will help you to get your doubts cleared.

A friend function provides many advantages:

  1. Provides extra functionality that is maintained outside of the class.
  2. Provides methods that need data that the class does not ordinarily utilize.
  3. Allows a non-member function to share confidential class information.

8. What is friend function and what are its limitations?

The main disadvantage of friend functions is that they necessitate an extra line of code when dynamic binding is desired. To simulate the impact of a virtual friend, the friend function should activate a secret (typically protected) virtual member function. This is referred to as the Virtual Friend Function Idiom.

9. What is friend function & what are its privileges with respect to the class?

In C++, If you are confused about what friend functions are, then friend functions of the class are allowed access to the class’s private and protected members. They are specified globally, outside of the scope of the class. Friend functions do not belong to a class.

10. What are the merits and demerits of using the friend function?

A friend function is a function that is defined outside of a class but has access to the class’s private and protected members. There may be moments in programming when we want two classes to share their members. These individuals might be data members, class functions, or function templates. If you are confused about what is friend function is then our blog on what is friend function will help you.

    Syntax:

class class_name{

private:

private variable of class

public:

friend return_type function_name(argument)

};

return_type function_name(argument)

{

Function definitions

}

Merits of friend function are:

  1. It operates as a link between two classes by using their private data.
  2. It can access members without having to inherit the class.
  3. It may be employed to boost the overloaded operator’s adaptability.
  4. It includes methods that need data that the class does not ordinarily utilize.
  5. Allows a non-member function to share confidential class information.

Demerits of friend function are:-

  1. It violates the law of data concealing by giving outside access to secret members of the class.
  2. Inadequate data integrity.
  3. Conceptually jumbled
  4. The member cannot be subjected to runtime polymorphism.
  5. The amount of memory utilized by items will be at its maximum.

If you are still confused about what is friend function then our blog on what is friend function will help you to understand it better.

Tagged in :

More Articles & Posts

UNLOCK THE PATH TO SUCCESS

We will help you achieve your goal. Just fill in your details, and we'll reach out to provide guidance and support.