here im not understanding the concept very well or i am right.... So lets take this "friend" class example here:
class MyClass{
friend class AnotherClass;
private:
int secret;
}
class AnotherClass{
public:
void getSecret(MyClass mc){
return mc.secret;
}
}
So Yes... in the above code it will actually work if you do it... but in general, why cant you use getters and setters all the time instead of friend class? Is the reason of friend class usage because of "tediousness"?
friend
is for when you don't want to expose getters/setters/internals to everyone, but just to a single class. So it's a tool for encapsulation.
For example, if you provided a public getSecret
in MyClass
, everyone could have access to that private variable even if they shouldn't know about it. This breaks encapsulation. friend
is there to fix this problem, so that only those classes that need to know about secret
have access to it.
As @nicomp said, "it's like giving your physical friend a key to your house but you don't know what they will do with it". So a friend
class has unlimited access to all internals of the class it's friends with. This in unfortunate, but the key (no pun intended) here is to keep classes as small as possible so that this doesn't become a problem, which also would be according to the Single Responsibility Principle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With