1 of 11

CS300: Object Oriented Analysis and Design

Polymorphism

(Using C++)

2 of 11

Operator overloading

Compiler sees an expression consisting of an argument followed by an operator followed by an argument, it simply calls a function.

An operator is simply a function call with a different syntax.

There must be a previously declared function to match that operator

Operator overloading is just “syntactic sugar,” which means it is simply another way for you to make a function call.

3 of 11

Is the knowledge about operator wrong ?

  • Maybe everything they know about operators in C is suddenly wrong

  • Operators for built-in types won’t suddenly start working differently

  • Overloaded operators can be created only where new data types are involved

1 << 4;

1.414 << 1;

won’t suddenly change its meaning

won’t suddenly start working.

4 of 11

Operator overloading

  • Specify more than one definition for an operator in the same scope

  • Declared (or defined) previously in the same scope

  • The compiler determines the most appropriate definition to use

  • Overload resolution

  • Redefine

5 of 11

We are already overloading

  • Inserters (<<) and extractors (>>)
  • A stream is an object that formats and holds bytes.

int i;

cin >> i;

float f;

cin >> f;

char c;

cin >> c;

char buf[100];

cin >> buf;

6 of 11

Operator overloading

  • Overloaded operators are functions with special names

  • The overloaded function will perform relative to the class upon which it will work

  • The keyword operator followed by the symbol for the operator being defined

  • Operator functions can be member or non-member of a class

  • Non-member operator function : friend functions

7 of 11

Creating a Member operator function

  • The general form of such a function is

Ret-type classname::operator#(arg-list){

//operations

}

// Overload + for loc.

loc loc::operator+(loc op2)

Demonstration

8 of 11

Can we overload all operators

+

-

*

/

%

^

&

|

~

!

,

=

<

>

<=

>=

++

--

<<

>>

==

!=

&&

||

+=

-=

/=

%=

^=

&=

|=

*=

<<=

>>=

[]

()

->

->*

new

new []

delete

delete []

::

.*

.

?:

9 of 11

Parameter passing to operator function

Operator function

Global

Unary (1)

Binary (2)

Member

Unary (0)

Binary (1)

The number of arguments in the overloaded operator’s argument list depends on two factors

10 of 11

Restrictions

  • Cannot combine operators that currently have no meaning

  • Cannot change the evaluation precedence of operators

  • Cannot change the number

11 of 11

Overloading Unary Operator

  • Takes just one operand

  • Takes no argument

  • Example:
  • Increment (++) and decrement(--) operator
  • Unary minus (-) operator
  • The logical not (!) operator