operators

Operator Overloading

Just like Function Overloading C++ also provides operator overloading, it means we can make new functionality for operators. For example, the addition operator is used to add two numeric values or two variables containing numbers, but we can overload its functionality to concatenate string values. This procedure of creating new definition for operator is called Operator Overloading.

 

Example:
#include<iostream>
using namespace std;
class Complex {
private:
    int real, imag;
public:
    Complex(int r = 0, int i =0) {
real = r;   imag = i;
}   
    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, 5), c2(2, 4);
    Complex c3 = c1 + c2; 
    c3.print();
}

 

1 Comment

  • נערות ליווי

    Itís nearly impossible to find well-informed people for this topic, but you seem like you know what youíre talking about! Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *