- Overview
- Table of Contents
- Special Member Functions: Constructors, Destructors, and the Assignment Operator
- Operator Overloading
- Memory Management
- Templates
- Namespaces
- Time and Date Library
- Streams
- Object-Oriented Programming and Design Principles
- The Standard Template Library (STL) and Generic Programming
- Exception Handling
- Runtime Type Information (RTTI)
- Signal Processing
- Creating Persistent Objects
- Bit Fields
- New Cast Operators
- Environment Variables
- Variadic Functions
- Pointers to Functions
- Function Objects
- Pointers to Members
- Lock Files
- Design Patterns
- Dynamic Linking
- Tips and Techniques
- A Tour of C99
- C++0X: The New Face of Standard C++
- C++0x Concurrency
- The Reflecting Circle New
- We Have Mail New
- The Soapbox
- Numeric Types and Arithmetic
- Careers
- Locales and Internationalization
Operator Overloading
Last updated Mar 1, 2004.
Object-oriented (OO) programming languages treat user-defined types as first-class citizens. One of the manifestations of this principle is that programmers can extend the semantics of built-in operators to support user-defined types as if they were built-in types. Such an extension overloads rather than overrides the predefined meaning of an operator.
NOTE
C++ requires at least one of the operands of an overloaded operator to be a user-defined type.
Although you can use ordinary functions for the same purpose, operator overloading provides a uniform notational convention that's clearer than the ordinary function call syntax. Consider the following example:
Monday < Tuesday; //overloaded < Greater_than(Monday, Tuesday);
Clearly, the use of an overloaded < operator is a better choice.
The capacity to redefine the meaning of a built-in operator in C++ was a source of criticism. People (mostly C programmers making the migration to C++) felt that overloading an operator was as dangerous as enabling the programmer to add, remove, or change keywords of the language. Still, notwithstanding the potential Tower of Babel that might arise as a result, operator overloading is one of the most fundamental features of C++ and is mandatory in generic programming, as the following sections will show. Today, even languages that tried to do without operator overloading are in the process of adding this feature.
An overloaded operator is merely a function whose name is an operator preceded by the keyword operator. The following code listing defines an overloaded version of operator < that compares two Book objects and returns the one with the lower ISBN (for example, to sort a book collection by ISBN):
class Book
{
private:
long ISBN;
public:
//...
long get_ISBN() const { return ISBN;}
};
//overloaded version of <
bool operator < (const Book& b1, const Book& b2)
{
return b1.get_ISBN() < b2.get_ISBN();
}


Account Sign In
View your cart