Friend Class In C++ - c++

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.

A public getter or setter permits anybody access. They have some uses, notably for maintaining class invariants when some property is changed, but a getter / setter pair that look like the following code are no better than public member variables for constraining access:
class A {
public:
int getX() const { return x; };
void setX(int x_) { x = x_; };
private:
int x;
};
The getX() and setX() functions do nothing but provide access to x. Everybody can use them, so anybody can change the value of x. There's no point making it private, then.
If, instead, only some classes or functions need to be able to change x, you can make them friends of class A. This restricts the access to only those friends, rather than giving it to everybody.
As such, friend is a tool for encapsulation, permitting the encapsulation to be wider than "just my own class" (private members) or "just my class and classes that derive from it" (protected members). A friend need not be in the same class hierarchy (it need not be a class at all; functions can be friends), but it still permits you to restrict access to only those things that actually need it.
Note that, like getters and setters, it should be used sparingly. Encapsulation is a good thing, and where possible the private members of your class should remain just that – private. friend is a tool that allows you to selectively grant access, but you should always carefully consider whether that access needs to be granted, or whether the function / class that needs it would be better off as a member of your class, instead.

Don't forget about testing and/or copying...
Friend classes / methods can be used quite successfully for checking intermediate states within class functionality.
They can also be useful for some types of copy constructors, where the class to be copied is not a direct ancestor of the target class thus precluding protected members as an option.

Consider the following use-case that I encountered recently: I refactored some code from one class into another class. This new class had to access members from the original class but I did not want to provide this via public getters to avoid other clients messing around with these. In this case, I really welcomed the C++-friendship mechanism.
However, these use cases are very seldom (hopefully, otherwise there is probably something wrong in your SW architecture) and I try to avoid it as much as I can since it is the tightest form of coupling.

Related

Does operator overloading allows the access to private member without friend? [duplicate]

class Person
{
private BankAccount account;
Person(BankAccount account)
{
this.account = account;
}
public Person someMethod(Person person)
{
//Why accessing private field is possible?
BankAccount a = person.account;
}
}
Please forget about the design. I know that OOP specifies that private objects are private to the class. My question is, why was OOP designed such that private fields have class-level access and not object-level access?
I am also a bit curious with the answer.
The most satisfying answer that I find is from Artemix in another post here (I'm renaming the AClass with Person class):
Why have class-level access modifiers instead of object-level?
The private modifier enforces Encapsulation principle.
The idea is that 'outer world' should not make changes to Person internal processes because Person implementation may change over time (and you would have to change the whole outer world to fix the differences in implementation - which is nearly to impossible).
When instance of Person accesses internals of other Person instance - you can be sure that both instances always know the details of implementation of Person. If the logic of internal to Person processes is changed - all you have to do is change the code of Person.
EDIT:
Please vote Artemix' answer. I'm just copy-pasting it.
Good question. It seems that object level access modifier would enforce the Encapsulation principle even further.
But actually it's the other way around. Let's take an example. Suppose you want to deep copy an object in a constructor, if you cannot access the private members of that object. Then the only possible way is to add some public accessors to all of the private members. This will make your objects naked to all other parts of the system.
So encapsulation doesn't mean being closed to all of the rest of the world. It means being selective about whom you want to be open to.
See the Java Language Specification, Section 6.6.1. Determining Accessibility
It states
Otherwise, if the member or constructor is declared private, then
access is permitted if and only if it occurs within the body of the
top level class (§7.6) that encloses the declaration of the member or
constructor.
Click the link above for more details. So the answer is: Because James Gosling and the other authors of Java decided it to be that way.
This works because you are in the class Person - a class is allowed to poke inside it's own type of class. This really helps when you want to write a copy constructor, for example:
class A
{
private:
int x;
int y;
public:
A(int a, int b) x(a), y(b) {}
A(A a) { x = a.x; y = y.x; }
};
Or if we want to write operator+ and operator- for our big number class.
Just my 2 cents on the question of why the semantics of the private visibility in Java is class level rather than object level.
I would say that convenience seems to be the key here. In fact, a private visibility at object level would have forced to expose methods to other classes (e.g. in the same package) in the scenario illustrated by the OP.
In truth I was not able neither to concoct nor to find an example showing that the visibility at class-private level (like offered by Java) creates any issues if compared to visibility at object-private level.
That said, programming languages with a more fine-grained system of visibility policies can afford both object visibility at object level and class level.
For example Eiffel, offers selective export: you can export any class feature to any class of your choice, from {NONE} (object-private) to {ANY} (the equivalent of public, and also the default), to {PERSON} (class-private, see the OP's example), to specific groups of classes {PERSON, BANK}.
It's also interesting to remark that in Eiffel you don't need to make an attribute private and write a getter to prevent other classes from assigning to it. Public attributes in Eiffel are by default accessible in read-only mode, so you don't need a getter just to return their value.
Of course you still need a setter to set an attribute, but you can hide it by defining it as "assigner" for that attribute. This allows you, if you wish, to use the more convenient assignment operator instead of the setter invocation.
Because the private access modifier renders it visible only within the class. This method is still IN the class.
the private field is accessible in the class/object in which the field is declared. It is private to other classes/objects outside of the one it is located in.
First thing here we have to understand is all we have to do is must follow oops principles so encapsulation is say that wrap data within package(i.e. class) and than represent all data as Object and easy to access. so if we make field as non-private than
it's accessed indivisually. and it result into bad paratice.
With reflection concept in Java is possible modify fields and methods privates
Modificando metodos y campos privados con Refleccion en Java

Granting access on a function to another class without exposing it

I have a class let us call it Person:
class Person{
private:
void move(x,y,z);
}
I have another class called PersonController:
class PersonController{
public:
void control(){
while(some_thing){
//do some calculations
controlled_person_->move(some_values); //Wrong Accessing to a private member
}
}
private:
Person* controlled_person_;
}
Both Person and PersonController are part of the public interface of the library I am designing.
I want PersonController to be able to call move from Person. However, I do not want anyone to access this function (move) from the public interface.
The easy way to sovle the problem is add a friendship so PersonController can access private members of Person. However, as far as I read the friend keyword was not introduced to solve these kind of problems and using it here would be a bad practice.
Is this correct? Should I avoid friend here?
Does this mean my design is broken?
Any alternative suggestions?
From what you said in comments, it seems you are interested in only allowing PersonController to touch that one member function. The way to do that and only that, is to make the door public, but add a private key for it:
class Person{
public:
class MovePrivilege {
move_privilege() = default; // private c'tor
friend class PersonController; // only PersonController may construct this
};
void move(MovePrivilege, x,y,z);
};
class PersonController{
public:
void control(){
while(some_thing){
//do some calculations
controlled_person_->move(MovePrivilege{} , some_values);
}
}
private:
Person* controlled_person_;
};
The type MovePrivilege has a private c'tor. So it can only be constructed by its friends. And it is also required for calling move. So while move is public, the only classes that may call it are the friends of MovePrivilege.
This essentially gives you a fine grained control over who may call move. If this is obtrusive and you can't change move itself, a variant of the attorney client idiom may be appropriate instead.
You do have options at your disposal. Direct firend-ship is just the bluntest tool.
That is exactly the sort of problem that friend is meant for. While friendship should be minimized if your design needs it there is no reason not to use it.
I see non-use of friend a lot like the continuing dislike of 'goto', there are simply times where using it will make a design far cleaner.
Yes your design is not correct.
Classes are an expanded concept of data structures: like data structures, they can contain data members, but they can also contain functions as members. You can read more here
So PersonController (If it only control person class) should not be a class because it is not concept of data structures Check if it is possible to merge them or design another way.
There are many ways to do it.If you want to design it like what you do now you can use protected access controller for your function and Create derived class but it's not a good design again.
You can use friend function here too but it isn't an object oriented concept again(But the easiest way).
You should rethink about your design if you want to design it OO.Because you can't access private function from other class in object oriented programming ,It breaks encapsulation so C++ won't let you do that.
However your question depends on opinions too.

Protected get-functions for protected datamembers?

We have two classes(A and B). Class A can only be created by classes who inherit from it(class A)
and class B can be created by a user.
Class A, version 1 has a private data member and has methods to aces the data in class A.
Class A, version 2 has a protected data member and therefore, no methods are needed for classes that will inherit from the class to aces the data in class A
Class A, version 1
class A
{
protected:
A() = default;
void set_data( T d );
T& get_data();
private:
T data;
}
Class A, version 2
class A
{
protected:
A() = default;
T data;
}
Class B
class B : public A {}
Which version of class A is the preferred one?
This is fairly subjective, but I would say 95% of the time neither one. Protected data makes your code just as hard to maintain as public so we rule that version out right away. But then also you almost never need a direct mutator (set) function, so we'll chop that function and then change the signature of the get function to const T& get_data() const;. Then we'll add a real interface to the parent to manipulate its state rather than having something external decide what the new state should be.
Your version one is always preferred. Data members of class should by default be private. Making data members all public is justified only in one case i.e If you just want to bundle-o-data. Only then you would use struct and make all data public. ( Like to capture the essence of what is s single node in linked list)
However, there is no such exception in case of protected. You can always make them private and provide accessors/mutators to those data members.
Downside of public data members is that they breaks the encapsulation. And it's difficult to maintain invariants as data is open to modification from all sides. Case of protected data member is bit restrictive than public in that it opens up ways for modification only through derived class members and friends. But still it's breaking encapsulation.
Conclusion :- All data members of class should always be private except in case it's intended to be used as bundle-o-data.
Along with that you would never want to pass handle to your internals to outside users as you have done in:-
T& get_data();
So, better way would be
const T& get_data();
except in some specific scenarios.
If you follow the common guidelines, data members should be private. Therefore, version 1 is preferred. On the other hand, completely trivial get/set pairs are a minor code smell in my opinion, so you may want to investigate why that member needs to be fully exposed to the derived class in the first place.
Use accessor functions if you need anything other than simple access to the variable: validating the value, maintaining class invariants, signalling changes, logging, etc. Note that get should return either a value or a const reference; your version, returning a non-const reference, can be used to assign arbitrary values to the variable, bypassing the set function.
If you only need simple access then some would suggest exposing the variable for the sake of simplicity; others would suggest using accessor functions for the sake of consistency (with other types that do need such things), or backwards compatibility (if you later decide you need functions after all). There's no compelling reason to prefer either option.

Why define Parent class as friend class?

I am looking at other's code and find one part I can't understand.
class a {
public:
function xxx () {.....}
}
class b : public a {
public:
xxxx
protected:
constructor()....
friend class a ; <= here why it is needed ????
}
As I understand, since b had already inherited from a, it should be able to use the function of a directly. What's the purpose of this "friend" declaration used for?
The friend allows a to use b's methods, not the other way around, which isn't implicit.
The design looks fishy though, a base class shouldn't care about derived classes.
friend class a; grants class a the right to access non-public members of b. So in this small example, an instance of a can call b::constructor(). Without friendship, it wouldn't be possible.
As to why, there is not enough information to answer that, other than there must be a need for instances of a to call b::constructor() (assuming that to be anything other than the syntax error it currently is).
As I understand, since b had already inherited from a, it should be able to use the function of a directly.
Yes. The friend specification though allows access the other way around (instances of a will be able to access private data and functions of b).
What's the purpose of this "friend" declaration used for?
The example above doesn't suggest any. The only situation where it may make sense is with using CRTP in certain situations (i.e. a is a template of b) but even so, if you see such a requirement ("must add friend declaration in b") it is possible that the design you're looking at is flawed.
Can you post a concrete example?
Depending on your projects/requirements, your class designs change. I have no comment on your class hierarchy but true your question is all about theories of friend usage. If you don't use friend, you will not be able to call B members from A. It is there for...cross-mating :D
It almost certainly means that there is a serious design problem. One of the basic rules of thumb for inheritance is that base classes should not need any information about derived classes. Making a a friend of b makes it possible for member functions of a to get at the internals of b objects.

What's the best way to access the internal data structure within a class?

I have a class A consisting of a bunch of internal data structures (e.g. m_data) and a few objects (e.g. ClassB):
class A
{
public:
...
private:
int m_data[255];
ClassB B[5];
}
What's the best way for B to access m_data? I don't want to pass m_data into B's function..
// updated:
Many thanks for the responses. Let me provide more contextual info.
I am working on an AI project, where I got some data (e.g. m_data[i]) at each time step. The class A needs to buffer these information (m_data) and uses a list of B's (example updated) to make inference. Class B itself is actually a base class, where different children derive from it for different purpose so I guess in this context, making B a subclass of A might not be clean (?)..
friend class ClassB;
Put this line anywhere in A's declaration if you want ClassB to access all of A's protected and private members.
One of:
Make ClassB a friend of A
Make A a sub-class of ClassB and make m_data protected rather than private
[In response to Mark B's comment]
If ever you feel the need to resort to a friend relationship, the design should be reconsidered - it may not be appropriate. Sub-classing may or may not make sense; you have to ask yourself "Is class A and kind of class ClassB?" If the question makes no sense intuitively, or the answer is just no, then it may be an inappropriate solution.
Ideally, you don't allow external access the data structure at all. You should rethink your approach, considering more the question "What are the functional requirements / use cases needed for ClassB to access instances of A" rather than offloading the management of the internal members to methods not managed within class A. You will find that restricting management of internal members to the class owning those members will yield cleaner code which is more easily debugged.
However, if for some reason this is not practical for your situation there are a couple possibilities that come to mind:
You can provide simple get/set accessor methods which, depending upon
your requirements, can be used to access either a copy of or a
reference to m_data. This has the disadvantage of allowing everybody
access, but does so only through well defined interfaces (which can
be monitored as needed).
ggPeti mentions use of friend, which may work for you, but it gives ClassB access to all of the internals of A.
A getData() function that returns m_data.
Use setData() to change the value.
So in the function in class B you would create a pointer to the class type A variable that you created. Lets just call this pointer 'p'.
Just do p->getData(), p.getData() may be the answer. I think they do the same thing but c++ uses the '->' and some other languages use the '.'. Don't quote me on that one though.
Good luck, sir. Hope I helped ya.
What's the best way for B to access m_data?
Depends on the use.
This is how would I do it :
class ClassB
{
// ...
void foo( A &a )
{
// use a's data
}
};
class A
{
//...
int m_data[255];
ClassB & B;
};
Depending on the implementation, maybe ClassB is not needed at all. Maybe it's methods can be converted to functions.