Docsity

Unary Operators - Object Oriented Programming - Lecture Slides, Slides of Object Oriented Programming

Partial preview of the text

Download Unary Operators - Object Oriented Programming - Lecture Slides and more Slides Object Oriented Programming in PDF only on Docsity!

Object-Oriented Programming

(OOP)

Lecture No. 21

  • Unary operators are usually prefix,

except for ++ and --

  • ++ and -- both act as prefix and

postfix

  • Example:
    • h++;
    • g-- + ++h - --i;
  • Example:

int x = 1, y = 2; cout << y++ << endl; cout << y;

  • Output:
  • Example:

int y = 2; y++++; // Error

y++ = x; // Error

Post-increment ++ returns by value, hence an error while assignment

  • Example:

int y = 2; cout << ++y << endl; cout << y << endl;

•Output:

  • Example:

int x = 2, y = 2; ++++y; cout << y; ++y = x; cout << y;

  • Output:

4 2

Pre-increment ++ returns by reference, hence NOT an error

  • Member function definition:

Complex & Complex::operator++(){

real = real + 1;

return * this;

}

  • Friend function definition:

Complex & operator ++ (Complex & h){

h.real += 1;

return h;

}

  • How does a compiler know

whether it is a pre-increment

or a post-increment?

  • A post-fix unary operator is

implemented using:

Member function with 1 dummy int argument

OR

Non-member function with two arguments

  • Post-increment operator:

class Complex{

...

Complex operator ++ (int);

// friend Complex operator // ++(const Complex &, int);

}

  • Member function definition:

Complex Complex::operator ++ (int){

*complex t = this;

real += 1;

return t;

}

  • The dummy parameter in the

operator function tells compiler that it

is post-increment

  • Example:

Complex h1, h2, h3;

h1++;

h3++ = h2 + h3++; // Error…

  • The pre and post decrement

operator -- is implemented in

exactly the same way