Download presentation
Presentation is loading. Please wait.
1
Operator Overloading CSCE 121 J. Michael Moore
Based on Slides created by Carlos Soto.
2
Operators Assignment: = Arithmetic: +, -, *, /, % Compound assignment: +=, -=, *=, /=, %= Increment/decrement: ++, -- Logical: !, &&, || Comparison: ==, !=, <, >, <=, >= Other: <<, >>, etc.
3
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);
4
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
5
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
6
Operator Overloading int k = i + j; // int +(int a, int b); string s2 = s + s; // string operator+(const& string a, const& string b);
7
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.
8
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
9
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)) {
10
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
11
Return types string operator+(const string& a, const string& b); bool MyClass::operator==(const MyClass& other); MyClass& MyClass::operator=(const MyClass & other);
12
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.
13
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.