Easy C++


C++ Tutorial - Lesson 26: Operator Overloading, Part II

General Rules, Operators in Global Scope

by John Kopp

Support this site at no cost to you

Welcome to EasyCPlusPlus.com's tutorial on C++ programming. This is the second part of a lesson on operator overloading. It presents some general rules, operators in global and namespace scope and the concept of friend functions. Overloaded operators can be declared with within a class or outside in global or namespace scope. In C++ a function declared as a friend to a class can access and manipulate the non-public members of that class. Classes can also be declared as friends of a class as will be described in a later lesson.

General Rules for Operator Overloading

  1. Only existing operator symbols may be overloaded. New symbols, such as ** for exponentiation, cannot be defined.
  2. The operators ::, .*, . and ?: cannot be overloaded.
  3. Operators =, [], () and -> can only be defined as members of a class and not as global functions.
  4. At least one operand for any overload must be a class or enumeration type. It is not possible to overload operators involving only built-in data types. For example, an attempt to overload addition, +, for the int data type would result in a compiler error. int operator+(int i, int j) is not allowed.
  5. The arity or number of operands for an operator may not be changed. For example, addition, +, may not be defined to take other than two arguments regardless of data type.
  6. The precedence of operators is not changed be overloading.

Overloaded Operators in Global and Namespace Scope
In addition to being defined in class scope (within a class), overloaded operators may be defined in global or namespace scope. Global scope means that the operator is defined outside of any function (including main) or class. Namespace scope means that the operator is defined outside of any class but within a namespace, possible within the main program.

Let's return to the Fraction class introduced in the last lesson. This time, we will enhance the class to allow mathematical operations between Fractions and integers. As a start, on the next page is the Fraction class with an added overloaded operator to handle the addition of an integer to a Fraction.

Previous Page       Next Page