For built-in types, a + b just works. Operator overloading lets your own classes use operators naturally: price1 + price2, v1 == v2, cout << student. It is an example of compile-time polymorphism.
An overloaded operator is simply a function named operator followed by the symbol: operator+, operator==, operator<<.
Overloading + as a member function#
a + b = (4, 6) a - b = (2, 2) b * 3 = (3, 6) a == b ? false
a + b is translated by the compiler into a.operator+(b): the left operand is the object, the right operand is the parameter.
Operator overloading का मतलब है अपनी class के लिए +, ==, << जैसे operators का अर्थ खुद तय करना। a + b लिखने पर compiler असल में a.operator+(b) call करता है। इससे code पढ़ने में बिल्कुल गणित जैसा लगता है।
Overloading << for printing#
To print with cout << obj, the left operand is cout (an ostream), so the operator cannot be a member of your class. Write it as a friend function that returns the stream:
[120] Tanvi - CGPA 9.31 [121] Manav - CGPA 6.84
Overloading comparison operators - and sorting with them#
If your class has operator<, the STL sort can sort your objects directly:
Virat 82 Rahul 64 Rohit 45 Gill 31
Unary operators: ++ (prefix and postfix), unary -#
6 6 7 -7
The subscript operator []#
67 60 Caught: bad index
Rules and good practice#
- You cannot create new operators or change precedence; you cannot overload
::,.,.*,?:,sizeof. - At least one operand must be a user-defined type (you cannot redefine
int + int). - Keep the natural meaning:
+should add,==should compare. Surprising operators make code hard to read. - Return a new object from arithmetic operators (
+,-), a reference from compound ones (+=, prefix++), andboolfrom comparisons.
Summary#
operator+,operator==,operator<... are ordinary functions with special names.- Member operators take the left operand as
this; use friend functions when the left side is not your class (likecout <<). - Overloading
<letssortwork on your objects;[]should return a reference.