Operator overloading

New meanings for operators can be defined in C++ by special kinds of function declarations. These new operations must be on classes. Operations on built in types cannot be changed.

#include<iostream.h>
class Complex {
   int v1, v2;
public:
   Complex * operator+(Complex);
   void printout();
   Complex(int iv1, int iv2);
};

Complex * Complex::operator+(Complex R) {
   return new Complex(v1+R.v1, v2+R.v2); }

Complex::Complex(int iv1, int iv2) { v1=iv1; v2=iv2; }

void Complex::printout() { cout<printout();
   return 0;
}
Plain text version to compile and run.


Back to overloading note

Back to index