What is Operator Overloading?

#include <iostream>
#include <string>
using namespace std;

int main(){
	string s1 = "ECE";
	string s2 = "244";
	// to concatenate them, we can simply add them
	string s3 = s1 + s2;
}

We’ve just done an operator overloading with +

Custom Class Example

class complex{
	private:
		double real;
		double img;
	public:
		// our first constructor... the default one
		complex(){
			real = 0;
			img = 0;
		}
		// our second constructor, where user defines the values for Re and Im
		complex(double r, double i){
			real = r;
			img = i;
		}
}

int main(){
	complex x(3, 4);
	complex y(5, 6);
	complex z;
	// can I say the following?
	z = x + y; // I'm calling the "+" operator
}
complex complex::operator+(complex rhs){
	complex result(real + rhs.real, img + rhs.img);
	return res;
}
z = x + y;
z = x.operator+(y);

Making it more secure

  1. Passing the object as a reference will make the function less secure in terms of changes that might affect the object.
    1. Solution: make the RHS object const
  2. operator+ should not change data members of the object
    1. Solution: make the return object const