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

Operator overloading, Class, Function implementation, Single mathematical statement, Alternative way, Mathematical expression, C pp code, Predefined types, Low level function for addition are the points you can learn in this object oriented programming subject.

Typology: Slides

2011/2012

Uploaded on 11/09/2012

bacha
bacha 🇮🇳

4.3

(41)

213 documents

1 / 32

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Object-Oriented Programming
(OOP)
Lecture No. 16
Docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20

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 $