< Prev
Next >

C++ Operator Overloading

ob1 = -ob1;

where, ob1 is an object of a class and unary minus operator - is overloaded in a way that we could just simply apply the unary minus - operator on the objects of class, in the same manner as we apply unary minus - operator on any variables of built-in data-types to negate its value.

Without the concept of operator overloading, you wouldn't be able to work with the objects of a user-defined data type, the way you would work with built-in type variables and unary or binary operators.

How to achieve unary operator overloading?

As you know, the NOT ! operator when applied to any built-in type variable such as int will inverse its value from 0 to 1 or from 1 to 0 to represent a boolean value. But can we even negate the value in an object by using the unary NOT ! operator?

Yes, we can! Let us see how to overload the NOT ! operator -

// C++ Overloading unary NOT(!) operator


using namespace std;

class A
int a;


void set_a();
void get_a();
void operator !();

//Definition of set_a() function
void A :: set_a()
	a = 0;

//Definition of get_a() function
void A :: get_a()
	cout<< a <<"\n";

//Definition of overloading unary NOT operator ! function
void A :: operator !()
	a = !a;

int main()
	A ob;

	cout<<"The value of a is : ";

	//Calling operator overloaded function ! to inverse the value

	cout<<"The value of a after calling operator overloading function ! is : ";


The value of a is : 0
The value of a after calling operator overloading function ! is : 1

Program Analysis

As you can see in the last program, we have created an operator overloaded member function to successfully overload the meaning of NOT ! operator, in such a way that it could inverse the value of user-defined data type variables and not just built-in data type variables.

In the next article, we are going to explain how to apply operator overloading on binary operators.

Please share this article -

< Prev
Next >
< Functions of String Class
Operator Overloading >


Please Subscribe

Please subscribe to our social media channels for daily updates.

Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page



Please check our latest addition