🔃Operator overloading
Operator overloading in C++ allows you to define how operators behave when applied to objects of user-defined classes. This feature enables you to use standard operators like +, -, *, /, =, etc., with your custom types, making your code more intuitive and readable.
Here's an example that demonstrates operator overloading:
Run it here.
In this example, we've created a Complex
class to represent complex numbers and overloaded several operators:
+
operator: This allows us to add two Complex numbers.*
operator: This enables multiplication of Complex numbers.==
operator: This allows comparison of Complex numbers.<<
operator: This is overloaded as a friend function to allow easy output of Complex numbers.
Try it here.
Key points about operator overloading:
You can overload most built-in operators in C++, but not all (e.g.,
.
,::
).Operator overloading doesn't change the precedence or associativity of operators.
You can overload operators as member functions or as non-member functions.
Some operators (like =, [], (), ->) must be overloaded as member functions.
The
friend
keyword is often used with operator overloading to give the operator function access to private members of the class.
When you run this program, it will output:
This demonstrates how we can now use standard operators with our custom Complex class, making the code more intuitive and closer to mathematical notation.
Last updated