OOPortal OOPortal


Operator Overloading  «Prev  Next»
Lesson 12Overloading I/O operators
ObjectiveOverload operator << to output playing card

Overloading Output Operator in C++

Overload the operator << so it outputs a playing card in a nicely formatted style.
Let us write these functions for the type rational:

class rational {
public:
  friend ostream&
    operator<<(ostream& out, rational x);
  friend istream&
    operator>>(istream& in, rational& x)
.....
private:
  long  a, q;
};

ostream& operator<<(ostream& out, rational x){
  return (out << x.a << " / " << x.q << '\t');
}

Operators as Member Functions and Global Functions

Whether an operator function is implemented as a member function or as a global function, the operator is still used the same way in expressions. So which is best? When an operator function is implemented as a member function, the leftmost (or only) operand must be an object (or a reference to an object) of the operator’s class. If the left operand must be an object of a different class or a fundamental type, this operator function must be implemented as a global function. A global operator function can be made a friend of a class if that function must access private or protected members of that class directly. Operator member functions of a specific class are called (implicitly by the compiler) only when the left operand of a binary operator is specifically an object of that class, or when the single operand of a unary operator is an object of that class.

Why Overloaded Stream Insertion and Extraction Operators Are Overloaded as Global Functions

The overloaded stream insertion operator (<<) is used in an expression in which the left operand has type ostream &, as in cout << classObject. To use the operator in this manner where the right operand is an object of a user-defined class, it must be overloaded as a global function. To be a member function, operator << would have to be a member of the ostream class. This is not possible for user-defined classes, since we are not allowed to modify C++ Standard Library classes. Similarly, the overloaded stream extraction operator (>>) is used in an expression in which the left operand has type istream &, as in cin >> classObject, and the right operand is an object of a user-defined class, so it, too, must be a global function. Also, each of these overloaded operator functions may require access to the private data members of the class object being output or input, so these overloaded operator functions can be made friend functions of the class for performance reasons.

Overloading Insertion Operator - Exercise

Click the Exercise link below to overload the operator << so it outputs a playing card in a nicely formatted style.
Overloading Insertion Operator - Exercise