0
Passing an object
when making a function friend of a class why we have to pass an object to it and why to pass it by reference?
1 Réponse
+ 4
No, its not necessary to pass an object. You may even declare a friend function which takes no arguments and returns void. But that won't be of much use.
You should see friend functions as normal functions that are just allowed to access the private members of a class they are declared in.
Example :
#include<iostream>
using namespace std;
class Example
{
int var;
public:
friend Example Set(int a)
{
Example s;
s.var = a;
return s;
}
void Print()
{
cout<<var;
}
};
int main()
{
Example s;
s = Set(5);
s.Print();
}
The Set() function accepts an integer and creates an object of type Example from it and returns it, so that it can be used in another object.
Similarly, you need not pass the object by reference. It is simply done to prevent excess memory from being used.
https://stackoverflow.com/questions/17941842/can-we-declare-a-friend-function-with-no-argument