CSIT Object Oriented Programming with C++(Unary Operator Overloading) Part III

 I am assuming that, You have already studied Part I and II of Operator Overloading Series. So in this post, I am going to teach you How to do Unary operator Overloading.

Before we get started towards our topic, I wanted to remind you, what  Unary Operator Really is?

An operator which acts upon only one operator is called unary operator. For example: Increment operator, Decrement operator and Negation operator (Minus) which  acts as both unary as well as binary operator.

Now, lets do coding to understand , how to perform unary operator overloading.

Here, I will do Pre-Increment operator overloading.


Have a look at this simple code and understand the basic.


//Overloading pre-increment operator

#include<iostream>

class A{

int length,breadth;

public:

A(int l, int b)

{

length=l;

breadth=b;

}

void operator ++()

{

++length;

++breadth;

}

void display()

{

cout<<"Length: "<<length<<endl<<"Breadth: "<<breadth<<endl;

}

};

int main()

{
A a(7,14);

++a;    //equivalent to a.operator ++();

a.display();

return 0;

}


OUTPUT

Length: 8

Breadth: 15


This is for pre-increment operator.

For post increment we have to pass dummy argument to operator function as follows.

void operator ++(int)

{

length++;

breadth++;

}

and invoking will be like this: a++;


In the same manner we can do decrement operator overloading.


In next post, I will teach you overloading unary operator using friend function. So refer next  post for that topic.


If This post Helped you, Please leave a comment, and share with your Coder Friends.
Thank You.

Keep Learning, Keep Growing


Comments

Popular posts from this blog

CSIT Object Oriented Programming with C++(Unary Operator Overloading using Friend function) Part IV

CSIT Object Oriented Programming with C++(Insertion and Extraction Operator Overloading ) Part VI