Docsity

Operator Overloading - Object Oriented Programming - Lecture Slides, Slides of Object Oriented Programming

Partial preview of the text

Download Operator Overloading - Object Oriented Programming - Lecture Slides and more Slides Object Oriented Programming in PDF only on Docsity!

Object-Oriented Programming

(OOP)

Lecture No. 16

  • Consider the following class:

class Complex{ private: double real, img; public: Complex Add(const Complex &); Complex Subtract(const Complex &); Complex Multiply(const Complex &); … } Docsity.com

  • The following statement:

Complex c3 = c1.Add(c2);

Adds the contents of c2 to c1 and assigns it to c3 (copy constructor)

  • To perform operations in a single

mathematical statement e.g:

c1+c2+c3+c

  • We have to explicitly write:

c1.Add(c2.Add(c3.Add(c4)))

  • If the mathematical expression is big:
    • Converting it to C++ code will involve complicated mixture of function calls
    • Less readable
    • Chances of human mistakes are very high
    • Code produced is very hard to maintain
  • C++ provides a very elegant solution:

“ Operator overloading ”

  • C++ allows you to overload common operators like + , - or ***** etc…
  • Mathematical statements don’t have to be explicitly converted into function calls
  • C++ automatically overloads operators for pre-defined types
  • Example of predefined types:

int float double char long

  • Example:

float x;

int y;

x = 102.02 + 0.09;

Y = 50 + 47;

  • Operator functions are not usually

called directly

  • They are automatically invoked to

evaluate the operations they

implement

  • List of operators that can be overloaded in C++:
  • The precedence of an operator is

NOT affected due to overloading

  • Example:

c1c2+c*

c3+c2c*

both yield the same answer

  • Associativity is NOT changed due

to overloading

  • Following arithmetic expression

always is evaluated from left to

right:

c1 + c2 + c3 + c

  • Always write code representing

the operator

  • Example:

Adding subtraction code inside the

  • operator will create chaos
  • Creating a new operator is a syntax

error (whether unary, binary or ternary)

  • You cannot create $