<aside> *️⃣ Allows us to redefine/overload standard behaviour of operators such as +, -, *, ==, etc for user defined data types.

</aside>

Consider the following class:

class Complex {
private:
    double real, img;

public:
    Complex(){real = 0.0; img = 0.0;}
		Complex(double r, double i){real = r; img = i;}

    // Overload the + operator
		Complex operator+ (const Complex& rhs)
};

Complex Complex::operator+(const Complex& rhs){
	return Complex(real + rhs.real, img+ rhs.img);
}

Now we can finally do this in the main

Complex c1(3, 2), c2(1, 7);
Complex c3 = c1 + c2;  // Uses the overloaded + operator

Overloading << to print

We can make it a friend function

class Complex{
    private:
        double real;
        double img;
    public:
        Complex(){real = 0,0; img = 0,0;}
        Complex(double r, double i){real = r; img = i;}
        Complex operator+ (Complex& rhs);
        friend ostream& operator<<(ostream& os, const Complex& x);

};

ostream& operator<<(ostream& os, const Complex& x){
    os << "(" ,, x.real << ", " << x.img << ")";
    return os;
}

Copy Constructor

Constructor that initializes an object using another object of the same type: ClassName(const ClassName& source);

When class members are pointers, especially pointing to dynamically allocated memory, there are some issues:

Shallow Copy

Bit-wise copy of an object’s members- for pointer members, this means copying the address they point to, and not the data