Yes, my non-const return value answer was "confused". Sorry, my brain didn't come up with a good answer, but yes, the reason is that it disables your ability to call non-const member functions.
If the compiler doesn't pick up
a+b=c for you, it's crap.
Should they not be members? |
It still doesn't matter. Being able to compute a standard mathematical function over a user type is part of that type's API.
It is not a violation of encapsulation to use friend functions, and I think it is an extremist POV to teach that it is.
Friends are part of the encapsulation..
That said, I agree that you should try to keep it down to as few things that know how to handle the innards of a class as possible. But at this point, we're overloading OP.
The following are equivalent when calling quux( a, b ):
1 2 3 4 5 6 7 8 9 10 11 12
|
struct foo
{
foo quux( const foo& z ) const
{
...
}
};
foo quux( const foo& a, const foo& b )
{
return a.quux( b );
}
|
1 2 3 4 5 6 7 8 9
|
struct foo
{
friend foo quux( const foo& a, const foo& b );
};
foo quux( const foo& a, const foo& b )
{
...
}
|
The difference is that you are confusing encapsulation and style. If a function
needs to access an object's internals to accomplish its goal, then it
must be a part of that object's encapsulating API.
Being able to implement things in terms of other things is a nice, handy trick, and can help keep maintenance nightmares down. These kinds of things should be recognized and used whenever possible, but in some cases it isn't something that should get your knickers twisted.
1 2
|
bool operator == ( const foo& z ) { return digits == z.digits; }
bool operator != () { holy crap! should I use !operator==() or not? }
|
You are wasting your time if you let the decision take more time than it would to write the code, because in this case
it doesn't matter.
If anyone intends to modify the way that operator == works, he should know enough to look at all the other operators as well, and for such a simple piece of code it takes nothing to make any needed adjustments.
Don't overload the OP.