Difference between Operator Functions and Normal Functions
Operator functions are the same as normal functions. The only differences are, that the name of an operator function is always the operator keyword followed by the symbol of the operator, and operator functions are called when the corresponding operator is used.
Example
C++
#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 & c1, Complex const & c2); }; Complex operator+(Complex const & c1, Complex const & c2) { return Complex(c1.real + c2.real, c1.imag + c2.imag); } int main() { Complex c1(10, 5), c2(2, 4); Complex c3 = c1 + c2; // An example call to "operator+" c3.print(); return 0; } |
Output
12 + i9
Operator Overloading in C++
in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning.
In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot overload in C++.