How to provide protection to friend function in C++

305 Views Asked by At

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?

2

There are 2 best solutions below

0
On

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)).

std::ostream& operator<<(std::ostream& s,two const& b)
{
    return s << b.roll;
}
2
On

friend ship is mutual. Unless one declares the function as friend in the class definition a function cannot be friended, so it's a choice. If you make it you have to live with it. It makes no sense to make a function friend and then try to prevent it from accessing the class internals because that is exactly the purpose of keyword friend.

Do not misuse or misinterpret friendship. friendship is used to indicate a intentional strong coupling between two entities. If there exists a special relationship between two entities such that one needs access to others private or protected members but You do not want everyone to have access by using the public access specifier then you should use friendship.