I have just started learning friend functions in C++.This is the program which I am using for the concept exploration.
#include<iostream>
using namespace std;
class one
{
private:
int age;
public:
one()
{
age=1;
}
void setData(int num)
{
age=num;
}
friend int returnOne(one a);
};
int returnOne(one a)
{
return a.age;
}
class two
{
private:
int roll;
public:
two()
{
roll=0;
}
void setData(int num)
{
roll=num;
}
friend int returnTwo(two b);
};
int returnTwo(two b)
{
return b.roll;
}
int main()
{
one a;
two b;
a.setData(10);
b.setData(12);
cout<<returnOne(a)<<endl<<returnTwo(b)<<endl;
}
Now I am worried that the security of class one
and two
has been compromised as now anyone can use those globally defined friend functions to access class one
's and class two
's private members.
How can I provide protection to these friend functions or restrict their usage?
Declaring a friend function in a class extends the classes
public
interface. You are basically extending the class with more functions (at the cost of tightly coupling those functions).So you can not stop people using those functions just like you can not stop people using public member methods on your class (they are all part of the public interface).
But you could re-design your friend functions so they do not expose implementation details.
Why not define
operator<<
for your class instead of a functions that access particular members (this is assuming you are providing these functions simply for streaming (if not then the point is mute)).