Member Function or Not?
We have seen Money's operator+ function overloaded as
both a member function and as a non-member function.
Which way is better?
A subtle issue
This code from last time works just fine regardless of
whether operator+ is a member function or not. Do you
see why this is true?
Money total, popcorn, candy;
// get popcorn sales amount
cout << "Enter the amount of the popcorn sales: ";
// get candy sales amount
cout << "Enter the amount of the candy sales: ";
// output total sales
total = popcorn + candy;
cout << endl;
What about this code?
Money total, cost;
cout << "Enter item cost: " ";
// add $10 shipping and handling
total = cost + 10;
cout << "Total cost: ";
The statement total = cost + 10; seems like a natural thing to
want to do. But 10 is not a Money object. How can this compile
The statement total = cost + 10; becomes the function call
cost.operator+( 10 );. Since 10 is an integer, the compiler
looks for a function named operator+ whose single argument is an integer
since this would be an exact match for the function call.
No such function exists.
Since cost is a Money object, the compiler next looks to see if there
is a Money constructor which takes a single integer argument. Since such
a constructor exists, the compiler converts 10 to a Money object and calls
Money's operator+ function.
This code works regardless of whether operator+ is a member function or
This example illustrates an important point --
Any class constructor that has a single argument can be used by the
compiler to automatically convert that argument to an object of that class
A bigger issue
Now, let's change the line total = cost + 10; to
total = 10 + cost; and look at what the compiler tries to do.
If operator+ is not a member function, 10 is converted to a Money object
and operator+ can be called with it's two Money parameters.
If operator+ is a member function of Money, however, we have a problem
because 10 (which is an int) cannot be a calling object. Conversions
to type Money works only for arguments, not for calling objects.
So what does this mean for our original question? Should operator+ be
a member function or not?
So what's the final decision?
- One the one hand, overloading an operator as a non-member function gives
you automatic type conversion for all arguments, which is needed for commutivity
of binary operators.
- On the other hand, overloading an operator as a member function allows
us to directly access private member data without the use of accessors or
Last Modified: Monday, 28-Aug-2006 10:15:53 EDT