WAP to demonstrate the characteristics of friend function?

The characteristics of Friend Function is

  • The function is not in the scope of the class to which it has been declared as a friend.
  • It cannot be called using the object as it is not in the scope of that class.
  • It can be invoked like a regular function without using the object.
  • It cannot access the member names directly and has to use an object name and dot membership operator with the member name.
  • It can be declared either in the private or the public part.

Now, we are taking the example of the friend function:

#include <iostream>
using namespace std;

class Box
{
    private:
        int length;

    public:
        Box() : length(0) {}
        friend int printLength(Box);
};

int printLength(Box b)
{
    b.length += 10;
    return b.length;
}

int main()
{
    Box b;
    cout << "Length of box :" << printLength(b) << endl;
    return 0;
}

The output of the above program is

Length of box :10
If you found any type of error on the answer then please mention on the comment or report an answer or submit your new answer.
Leave your Answer:

Click here to submit your answer.

s
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments