One of the most common operators which is overloaded is
Up to this point, displaying a Money object required the use
of the Output( ) function and code that looked like this
cout << "The fee is ";
cout << " and is not negotiable\n";
The natural thing to want to do is to use the insertion operator
for objects just like for basic data types and write code like this
cout << "The fee is " << fee << " and is not negotiable\n";
By overloading operator<<, we can do just that
and assure that Money objects are always displayed in the same format.
The statement cout << fee; is actually a function call.
ostream& operator<< (ostream& out, const Money& money);
Assuming such a function exists, the compiler generates the function call.
What if the function doesn't exist?
The name of the function being called is
The compiler looks for a function whose signature is
The operator<< function
In this example, the code for Money's operator<< is written as a
friend function. The declaration for the overloaded operator<<
as friend function inside the Money class definition would be
friend ostream& operator<< (ostream& out, const Money& amount);
Of course, if sufficient accessors exist, operator<< need not be
The implementation of the function is shown below along with its
pre- and post-conditions.
// PreConditions: none
// the Money argument is displayed as dollars
// and cents with a leading $
// the modified output stream is returned
ostream& operator<< (ostream& out, const Money& money)
out << "$" << money.m_dollars << "." << money.m_cents;
Why does this function return an ostream reference?
- You can and should overload
operator<< for all your objects.
- Note that we did not output an endl.
- operator<< is a binary operator. The left hand operand is
an ostream object. Therefore, operator<< cannot be a member function
of your class.
- operator<< is not a member function.
- operator<< always returns an ostream&.
- You can also overload the extraction operator,
operator>>, for inputting a class.
Last Modified: Monday, 28-Aug-2006 10:15:53 EDT