An operator is a symbol designed to operate on data.
They can be a single symbol, di-graphs, tri-graphs or keywords.
Operators can be classified in different ways.
This is similar to function overloading
2. What is an operator?
An operator is a symbol which designed to
operate on data.
They can be a single symbol, di-graphs,
tri-graphs or keywords.
Operators can be classified in different ways.
Based on a number of
arguments
• Unary operators
• Binary operators
• Ternary operators
Based on the location
• prefix operators
• postfix operators
• infix operators
3. Operator overloading
This is similar to function overloading.
Remember:
Programmers are not allowed to change the
meaning of existing operator but can define on
a new domain.
(eg: cannot force “+” to substract int or float. But can introduce into
“String” which is a new domain)
C++ does not allow programmer to define completely new operator.
(eg: cannot define new operator “$#”)
Overloaded operator is treated as very specific function.
4. Implement operator
overloading
An operator function can be implemented in two different ways.
• As a member function of a class
(Implicitly assumed that an object of that class is one of the
required operator’s argument)
• As a standalone function
(Function must explicitly specify the types of all arguments)
Operator overloading will not increase either code efficiency or
reliability. But that may improve code readability.
5. Number of
arguments
Number of arguments are strictly restricted.
Key factors are
• location – (where the operator function is defined)
• operator – (overloading operator)
6. Keep in mind !
Don’t
• define new operators that is not exist
in C++
• change the priority
• Overload operators that working in
existing data types
7. Operators
Operator type Operator
Implementation
Return type
As global
function
As a member
function
Arithmetic operator + - * / % Yes Yes Depending on context
Bitwise operator ^| & ~ << >> Yes Yes Depending on context
Assignment operator = No Yes
Reference to an object
or l-value
Relational operator
== != > >= <=
&& ||
Yes Yes Boolean
! Yes Yes -
Compound
assignment operator
+= -= *= %= /= &=
|= ^= >>= <<=
No Yes
Reference to an object
or l-value
Prefix increment and
decrement
++ -- No Yes
Reference to an object
or l-value
Postfix increment and
decrement
++ -- No Yes
Reference to an object
or l-value
Subscript operator [] No Yes
Reference to an object
or l-value
Function invocation
operator
() No Yes Any
& * Yes Yes Any
9. This is an introduction for operator
overloading. It is better to try these
things and feel free to experiment
with them on your own.
Lahiru Dilshan