Unary Operator Overloading

Refers to operator overloading that act on a single object.

 

NOT Address One's Comp Point deref Plus Increment Negation Decrement
! & ~ * + ++ - --

 

The ! Logical NOT operator is being overloaded here on line 11 to return a bool to the test condition on line 28:

#include <iostream>
using namespace std;

class Value {

private:
	int val;
public:
	Value (int something = 0) : val(something) { }

	bool operator ! () {
		if( val % 2 == 0) {
			return true;
		} else {
			return false ;
		}
	}
} ;

int main() {

	int a ;
	cout << "Please enter a number" << endl ;
	cin >> a ;

	Value myVal(a);

	if (!myVal){
		cout << a << " is an even number" ;
	} else {
		cout << a << " is an odd number" ;
	}

	return 0 ;
}

Compile & Run:

Please enter a number
56
56 is an even number

Leave a Reply