***Welcome to ashrafedu.blogspot.com * * * This website is maintained by ASHRAF***

Monday, June 14, 2021

Overloading Unary Operators

The operator overloading can allow the unary operators to overload. The unary operators can perform the operations on a single operand.

The unary operators can be overloaded using a friend function and member function.

Using a member function to overload a unary operator

In operator overloading, the unary operators can be overloaded using a class member function. These member functions are defined as follows:

Syntax:-

public:

returntype operator op()

{

---------

}

Here, op is any unary operator that can be overloaded

 

Example. //overloading the prefix increment and decrement operators

#include<iostream.h>

#include<conio.h>

class sample

{

private:

int n;

public:

sample()

{

 n=0;

}

sample(int k)

{

 n=k;

}

void operator++()

{

n=n+2;

}

void operator--()

{

n=n-2;

}

void show(char *msg)

{

cout<<msg<<n<<endl;

}

};

void main()

{

clrscr();

sample s1(10),s2(10);

s1.show("S1 : ");

s2.show("S2 : ");

++s1;

--s2;

cout<<"After using operator overloading...\n";

s1.show("++S1 : ");

s2.show("--S2 : ");

getch();

}

Overload a unary operator using a Friend function

Like member functions, friend functions are also used in operator overloading. When a unary operator is overloaded using a friend function consider the following:

1) The function will take one operand as an argument.

2) The operand will be an object of the class.

3) The function will use the private members of the class only with the object.

4) The function may or may not return a value.

5) The function may take the object by using a value or by reference.

6) The friend function does not allow this pointer.

A friend function is declared inside the class and is defined outside the class.

Syntax:-

public:

friend returntype operator op ( classname obj);


No comments:

Post a Comment