Reputation: 1258
I'm using some kind of "manager" to store a "Context" class, in some cases I want to pass this "Context" to other functions to read data from it.
Actually, when the manager pass this "Context" to a function, it pass a "const& Context", and I the Context have some functions declared as const (for reading) and others that aren't const (becouse the manager have to change the data inside the context)
now, I ask myself, is there any difference if I just do private mutators and give friendship to manager?
I think it must be some difference. I know, it's a particular case, but for me C++ still have a lot of magic around there.
Upvotes: 1
Views: 74
Reputation: 56
In my experience with C++, the main difference between having private mutators and giving friendship and having public mutators not giving friendship is that the second option allows you to not give anything and everything access to the information but only certain. Let's say you create a class called Student which has 2 child classes. Regular Student and Teachers Assistant. A lot of times there's so many students that it's hard for the teacher to take care of everything so he takes the best students as TA's. When the program is looking at these students, they should probably have more access to the Student's information than the regular student. With private mutators and giving friendship, you are saying some information (like a grade on a test) is private but can be changed by a TA possibly. On the other hand, if you have public mutators and no friendship, it is possible that a regular student can access the information and change the grades.
Hope this was helpful.
Upvotes: 1
Reputation: 171117
I'll start with two general statements:
const
-correctness is a very good thing
firendship forms extremely close coupling between the two classes, which is generally a bad thing
Is your Context
so tied in to the manager that only the manager would ever want to modify it (both now and as your program evolves through the years)? And is Context
happy to have the manager modify it as it pleases (accessing all its private data)? If any of the answers is "no," you shouldn't go the friendship route.
Friendship should be used sparingly. When class X
grants friendship to class or function Y
, you now have two separate places in code which must maintain X
's internal invariants: X
itself, and Y
. This requires more maintenance and is more error-prone.
In short, reserve friendship for very special cases. What you describe seems like a clear-cut use for normal measures - const
observers, non-const
modifiers.
Upvotes: 1