Loading....
Coupon Accepted Successfully!

 

Exceptions And Operator Overloading

An exception handling can be sued with operator-overloaded functions. The following program illustrates the same:

19.10 Write a program to throw exception from overloaded operator function.

#include<iostream.h>

#include<process.h>

class number

{

int x;

public :

number() {};

void operator --();

void show() { cout<<“\n x=”<<x; }

number ( int k) { x=k; }

};

void number :: operator --() // prefix notation

{

if (x==0) throw number();

else --x;

}

void main()

{

try

{

number N(4);

cout<<“\n Before Decrementation:”;

N.show();

while (1)

{

cout<<“\n After Decrementation”;

--N;

N.show();

}

}

catch (number)

{

cout<<“\n Reached to zero”;

exit(1);

}

}

OUTPUT

Before Decrementation

x=4

After Decrementation

x=3

After Decrementation

x=2

After Decrementation

x=1

After Decrementation

x=0

After Decrementation

Reached to zero

Explanation: In this program, the operator – is overloaded. When used with class objects, this operator decreases the values of class members. Using the while() loop, the value of the object N is continuously decreased. The object N is initialized with four. The operator –() function checks the value of x (member of object N); if the value of x reaches zero, an exception is thrown, which is caught by the catch statement.





Test Your Skills Now!
Take a Quiz now
Reviewer Name