Operator Overloading CSCE 121 Based on Slides created by Carlos Soto.
Operators Assignment: = Arithmetic: +, -, *, /, % Compound assignment: +=, -=, *=, /=, %= Increment/decrement: ++, -- Logical: !, &&, || Comparison: ==, !=, <, >, <=, >= Other: <<, >>, etc.
Operators (kind of like functions...) int a = 0, b = 5; int c = a + b; // int +(int a, int b); c++; // void ++(int& c); int d = a; // void =(const int& a, int &d);
Operators (a lot like functions...) int i = 0, j = 5; string s; i++; // matches ++ operator’s ‘arguments’ s++; // no match int k = i + j; // integer addition string s2 = s + s; // string concatenation
is a PRIMITIVE datatype Operator Overloading int k = i + j; // int +(int a, int b); string s2 = s + s; // string +(string a, string b); NOT actually a function, because int is a PRIMITIVE datatype
Operator Overloading int k = i + j; // int +(int a, int b); string s2 = s + s; // string operator+(const& string a, const& string b);
Does not have access to private MyClass data and methods. Operator overloading class MyClass { int myAttr = 7; }; // outside class scope MyClass operator+(const MyClass& a, const MyClass& b) { // ... } Does not have access to private MyClass data and methods.
Operator overloading (inside class scope) class MyClass { int myAttr = 7; // ... public: MyClass(int k) : myAttr(k) {} MyClass operator==(const MyClass& b) { } }; MyClass operator+(const MyClass& a, const MyClass& b); Has access to private MyClass data and methods
Parameters (implicit and explicit) bool MyClass::operator==(const MyClass& other){ return (myAttr == other.myAttr); } // ... MyClass a = MyClass(7); MyClass B = MyClass(11); if (a == b) { Equivalent to calling: if (a.operator==(b)) {
Alternatively element access operator for pointers to objects bool MyClass::operator==(const MyClass& other){ return (this->myAttr == other.myAttr); } element access operator for pointers to objects Recall: ‘this’ is a pointer to the instance of the class Student that called the == operator
Return types string operator+(const string& a, const string& b); bool MyClass::operator==(const MyClass& other); MyClass& MyClass::operator=(const MyClass& other);
Returning a reference in a overloaded operator MyClass& MyClass::operator=(const MyClass& other) { this->myAttr = other.myAttr; return *this; } Essentially, dereference ‘this’ and the compiler knows how to get the address from the class.
Rules for Operator Overloading Can only overload existing operators can’t create your own Cannot change the number of operands Must take at least one non-primitive datatype operand