CurriculumOperator Overloading

Operator Overloading

<strong>Operator Overloading</strong> lets you define what operators do when applied to your custom classes. Makes code natural: v1 + v2 instead of v1.add(v2).

01Arithmetic Operators (+, -, *)

Overload + to add two objects naturally. As a member function, 'this' is the left operand.
main.cpp
Loading...
Terminal
Waiting for execution...

02Comparison Operators (==, !=, <)

Overload comparison operators to make objects work with if conditions and sorting algorithms.
main.cpp
Loading...
Terminal
Waiting for execution...

03Stream Operators (<< and >>)

Overloading << lets you print your object with std::cout directly. Must be a friend because left operand is std::ostream.
main.cpp
Loading...
Terminal
Waiting for execution...

04Increment/Decrement (++/--)

Prefix (++obj) and postfix (obj++) are different. C++ uses a dummy int parameter to distinguish the postfix version.
main.cpp
Loading...
Terminal
Waiting for execution...

05Subscript Operator ([])

Overloading [] lets your class act like an array. This is exactly how std::vector implements element access.
main.cpp
Loading...
Terminal
Waiting for execution...
← Back to Curriculum