Operator Overloading in C++
Defination : Operator overloading is a technique by which operators used in a programming language are implemented in user-defined types with customized logic that is based on the types of arguments passed.
. (dot) :: ?: sizeof Why?
Rules for Operator Overloading
#include <iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0) { real = r, imag = i; }
void print() { cout << real << " + i" << imag << endl; }
// The global operator function is made friend of this class so
// that it can access private members
friend Complex operator + (Complex const &, Complex const &);
};
Complex operator + (Complex const &c1, Complex const &c2){
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
int main() {
Complex c1(10, 2), c2(2, 3);
Complex c3 = c1 + c2;
c3.print();
return 0;
}#include <iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0) { real = r, imag = i; }
// This is automatically called when '+' is used with
// between two Complex objects
Complex operator + (Complex const &obj){
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag <<endl; }
};
int main() {
Complex c1(10, 2), c2(2, 4);
Complex c3 = c1 + c2;
c3.print();
return 0;
}