Friend Function in C++

Friend Function in C++

C++ allows us to make the common function friendly with more than one classes, thereby allowing the function to have access to the private data of classes. Such a function need not be a member of any classes. Non-member functions cannot have access to the private data of the class. However, there could be a situation where user would like two classes to share a particular function. At this situation friend function helps user in C++.

The whole concept of friend function is that in real life when we cannot tell some things to our families, but we can definitely tell it to our friend.

Let’s see the syntax of friend function

class class_name
{
      private :
         ......
         ......
         ......
      public :
         ......
         ......
         friend return_data_type function_name(arguments);  //declaration
};

The keyword “friend” declares the function to be friendly with that class. This function is defined as a normal C++ function. The function definition does not use class_name, keyword friend or scope resolution operator. Now let’s talk about the characteristics of the friend function.

Characteristics of friend function :

1. It is not in the scope of the class to which we declare it as friend.
2. We cannot call it using object of a class because it is not in the scope of the class.
3. We can declare it in either public or private part of the class without affecting its meaning.
4. Usually, it has the objects as the arguments.
5. It cannot access the member function directly and has to use an object name and dot operator with each member name.

Let’s see an example related to friend function to get more clear idea.

Q. Write a program in C++ to demonstrate use of friend function.

Program :

//A simple program to demonstrate friend function

#include<iostream>

using namespace std;

class MySelf
{
    private :
        int age = 19;

    public :
        void askfriend(void)
        {
            cout<<"\n\t Hey do you know my secret?";
        }

        friend void BestFriend(MySelf my);  //Declaring friend function
};

void BestFriend(MySelf my)
{
    cout<<"\n\t Yes I do!";
    cout<<" Your age is not 20. It is "<<my.age;  
                             //Friend function accessing private data of MySelf class
}

int main()
{
    MySelf obj;    //Creating object of a class
    cout<<"\n Me to my bestfriend : ";
    obj.askfriend();

    cout<<"\n My bestfriend to me :";
    BestFriend(obj);     //Calling friend function like a normal function
    
    return 0;
}

Output-

friend function in C++

Let’s see one more example in which friend function will access private data of two classes.

Q. Write a program in C++ to access data of two classes using friend function.

Program :

//Friend function to access data of two different classes
#include<iostream>

using namespace std;

class A;   //This is forward declaration

class B
{
    private:
        int val2;
    public:
        void getdata(void)
        {
            cout<<"\n Enter another number :";
            cin>>val2;
        }

        void displaydata(void)
        {
            cout<<"\n\t Second number : "<<val2;
        }

        friend void exchange(A&, B&);    //declaring friend function
};

class A
{
    private:
        int val1;
    public:
        void get(void)
        {
            cout<<"\n Enter a number :";
            cin>>val1;
        }

        void display(void)
        {
            cout<<"\n\t First number : "<<val1;
        }

        friend void exchange(A &x,B &y);   //declaring friend function
};

void exchange(A &x, B &y)    //friend function definition
{
    int temp;
    temp = x.val1;
    x.val1 = y.val2;
    y.val2 = temp;
}

int main()
{
    A obj1;
    B obj2;
    obj1.get();
    obj2.getdata();
    cout<<"\n Before Exchange:-";
    obj1.display();
    obj2.displaydata();

    exchange(obj1, obj2);     //Calling friend function as a normal function

    cout<<"\n\n After Exchange:-";
    obj1.display();
    obj2.displaydata();

    return 0;
}

Output :

friend function in C++

Explanation-

In both the examples we can see we have to pass objects as arguments of respective classes to access the private data of each class. If we try to use object of a class to access data or functions of other class it will give an error. Thus without inheriting also we can access members of any class in C++ using friend function. Important point to remember here is we have to declare friend function in every class whose private data we want to access. We can declare friend function in private or public section also.

Program Parts :

1. #include is a pre-processor directive. It is used to include header files.
2. iostream is header file which has certain commands that c++ supports. E.g. return, main, etc.
3. .h is an extension for header file.
4. class is a keyword to create classes.
5. friend is a keyword to declare any function as a friend function.
6. int is data type. It indicates that the program returns a value.
7. main() is main function that indicates the compiler that the user written programs starts from here.
8. cout is the keyword use to print a message.
9. cin is the keyword use to store values in variables.
10. return statement is use to return a value. If any error occurs the program will return 0.

Conclusion-

So this was the concept of friend function in C++. We hope the concept was clear to you. If you have any doubt regarding any of the concept or friend function do mention it in the comment section or mail us! For daily updates and more such content do follow us on Instagram.

Keep Programming!

ErrorFreeProgram.

1 COMMENT

Leave a Reply

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