Karnataka II PUC Computer Science (KSEAB) study materials
Karnataka II PUC Computer Science (KSEAB) study resources

Karnataka II PUC Computer Science (KSEAB): Operator Overloading

Karnataka II PUC Computer Science (KSEAB) · Work through your exam, one topic at a time.

All guide sections

Operator Overloading

Operator Overloading

This domain tests giving existing C++ operators new meaning for user-defined types. The keyword operator is followed by the operator symbol, e.g. operator+. Overloading must involve at least one user-defined operand; you cannot change arity, precedence or associativity. You cannot overload the scope-resolution, member-access, conditional and sizeof operators.

Forms

  • Member function: the left operand is the object; a binary operator takes one explicit parameter.
  • Friend function: takes both operands explicitly and can access private members.
  • Unary operators such as - or ++ can be overloaded with zero (member) or one (friend) parameter. Return by value for a new result; return by reference when chaining assignment.

Worked example

class Complex { int r, i; public: Complex(int a=0,int b=0){r=a;i=b;} Complex operator+(const Complex &c) { return Complex(r+c.r, i+c.i); } }; Complex a(2,3), b(1,4), c; c = a + b; gives real 3 and imaginary 7. The compiler translates a + b to a.operator+(b). The member function can read c.r and c.i because it is inside the class, even though they are private.

Traps

You cannot overload operators for two built-in types. operator+ must not be given three operands. Overloading = requires care with self-assignment. Prefix and postfix ++ have different signatures. Overloading does not change precedence.