Operators in C++ allow us to perform operations like addition, subtraction, or comparison. However, what if you want to define how these operations work for your own data types, like adding two custom Point
objects or comparing two Student
objects? This is where operator overloading comes in.
What are operators?
Operators are special symbols or keywords in C++ that perform operations on variables and values. Common operators include:
Arithmetic operators (+
, -
, *
, /
)
Comparison operators (==
, !=
, <
, >
)
Logical operators (&&
, ||
, !
)
Operator overloading is a feature in C++ that allows us to redefine the way an operator works for user-defined types. For example, the +
operator can be overloaded to add two objects instead of just numeric values.
Now that we know what operator overloading is, let's explore how to overload some common operators with examples.
Types of operator overloading
Operator overloading can be classified into the following types:
Unary operators: Overload operators like -
, ++
, and --
that work with a single operand.
Binary operators: Overload operators like +
, -
, *
, ==
, and /
that works with two operands.
Relational operators: Overload operators like ==
, <
, and >
to compare objects.
Stream operators: Overload <<
and >>
for input and output streams.
Assignment operators: Overload =
to customize assignment behavior.
Note: We can overload almost all operators in C++ to customize their behavior for your classes, except a few like sizeof
or ::
.
Example of operator overloading in C++
Consider a simple example of a Point
class: