Tuesday, January 19, 2010

When should a non-member function be a friend

Let's be clear, a private variable in a class is no longer really private when you define a get or set methods to read or update the variable.  Having the variable private in this case just means that you are hiding the name of the variable, not it's existence.


If you have to add a new public get/set method in order to get a non friend function to work, it is probably better that this function is a friend, rather than expose the private variable (via the get/set) to all other functions.  

Having a get/set method is OK if it makes sense that all other functions can use these to see the private variable, otherwise best not to expose the internals of the class via get/set.

No comments: