Question and Answer Database FAQ407C.txt Operator Overloading Category :C/C++ Language Issues Platform :All Product :BC++ 5.x Question: What is operator overloading? Answer: Basics of operator overloading: using an operator like "a + b" is like calling a function with 2 parameters "operator+(a,b)" or calling a member function "a.operator+(b)". Note: the former 2 expressions are valid C++ expressions and can be used in programs. overloading operator "+" between type A and B is in fact overloading the function "operator+(A,B)" or the member function "operator+(B)" of the A class (A must be a class in this case of course). So defining a "+" and "+=" operation for a complex classes could be: class complex { public: double re, im; complex() {} complex(double r, double i = 0) : re(r), im(i) {} complex& operator+=(const complex& a) { re += a.re; im += a.im; return *this; } }; inline complex operator+(const complex& a, const complex& b) { return complex(a.re + b.re, a.im + b.im); } You can use them as follow: complex a(1,-1), b(2,2); complex c = a + b; // c will be (3,1). Same as c = operator+(a,b); c += a; // c will be (4,0). Same as c.operator+=(a); Note: operator+() could also have been defined as a member function. Some special points of operators: — You can only overload operators if at least one operand is a class, structure or reference to class or structure. If every operand were built-in types, that would mean redefining an existing or forbidden operation. — You cannot overload "::" (scope operator) "?:" (ternary operator) "." and ".*" (member resolution operators). — "->" and "->*" are special, can be only defined as unary member functions returning a type supporting the "->" or "->*" operator (generally a pointer to a class or structure) — operator "=" (assignment operator) have special behavior like copy constructors (and it's one of the most important operator...) and can only be defined as a member function. — postcript "++" and "--" operator differs from their non-postfix counterpart using a dummy "int" argument: "operator++(A)" defines "++a" while "operator++(A,int)" defines "a++". — special operators called cast operators (always member functions) defined as "operator()" without return types are used to define a conversion to another type. — the call operator (member function) emulates a function call. Example: struct functor { int operator()(int, int); }; functor f; int result = f(2,3); 7/2/98 10:32:32 AM
Last Modified: 01-SEP-99