Multiple classes as friends by default - why?

Hi,

I'm writing a Connect4 program that uses a large number of board objects called SuperBoard, and learned while writing the copy constructor that each SuperBoard is implicitly friends with all other SuperBoards by default. This made it a lot easier to write a lot of functions, but why is this? It seems rather insecure from a security standpoint.

Thanks
I don't understand? One class can always access its private and protected members, no matter the circumstance...
As in, different SuperBoard objects are able to access each others private members?
writing the copy constructor that each SuperBoard is implicitly friends with all other SuperBoards by default


Are you saying based on the argument passed in the copy constructor you can access their private members?

e.g
class SuperBoard {
public:
SuperBoard(const SuperBoard& obj) {
//here you can access obj.private_members ?
}
}
You can always do this, it's the same class, and in fact it is required for copying the state of some objects. It isn't a friend with itself, it IS itself, and it can always access its own stuff.
One instance of a class cannot directly access private members of another instance. If you want the private members to be the same for ALL instances you could make them static. Then they will belong to the class (all instances).

The best thing to do here is to make get and set methods that will allow you to use the public interface as a means to change the object.

You can make a class a friend of another class but it's really not the best way to do things unless you are creating a handle class for an inheritance hierarchy. In that case, your handle class could be a friend of the hierarchies base class.
Last edited on
IceThatJaw wrote:
One instance of a class cannot directly access private members of another instance.
False. Instances of the same class can always access each other's private and protected members. Derived classes can only access protected base class members.
Last edited on
I meant to say another class, not instance. I thought he was trying to access private members of other classes inside of a class. Of course you can access private members within a class.

Honestly, I still don't understand what TS is asking. I still think he should make his interface and hierarchy robust so he wouldn't have to consider using friend functions.

Topic archived. No new replies allowed.