C++ Logical (&&, ||, !) Operator Overloading
Last Updated :
27 Nov, 2022
Prerequisites:
Logical operators are used for combining two or more conditions or constraints or to complement the evaluation of the original condition in consideration. The result returns a Boolean value, i.e., true or false. In C++, there are 3 logical operators:
- Logical AND (&&): This operator returns true only if all the operands are true or non-zero.
- Logical OR ( || ): This operator returns true if either of the operands is true or non-zero.
- Logical NOT ( ! ): This operator returns true if the operand is false or zero and vice-versa.
To use a logical operator on user-defined data type operator overloading is needed. Redefining the meaning of operators really does not change their original meaning, instead, they have been given additional meaning along with their existing ones.
Example 1:
C++
#include <iostream>
using namespace std;
class A {
private :
int a;
public :
A( int l) { a = l; }
bool operator!()
{
a = !a;
if (a)
return true ;
else
return false ;
}
};
int main()
{
A a1(7), a2(0);
if (!a1) {
cout << "a1 value is zero" << endl;
}
else {
cout << "a1 value is non-zero" << endl;
}
if (!a2) {
cout << "a2 value is zero" << endl;
}
else {
cout << "a2 value is non-zero" << endl;
}
}
|
Output
a1 value is non-zero
a2 value is zero
Example 2: Overloading AND (&&) Logical Operator
C++
#include <iostream>
using namespace std;
class A {
private :
int value;
public :
A() {}
A( int l) { value = l; }
A operator&&( const A& a)
{
A obj;
obj.value = value && a.value;
return obj;
}
void result()
{
if (value)
cout << "Both value is non zero" << endl;
else
cout << "Any one or both value is equal to zero"
<< endl;
}
};
int main()
{
A a1(95), a2(78);
A a3;
a3 = a1 && a2;
a3.result();
return 0;
}
|
Output
Both value is non zero
Example 3: Overloading OR (||) Operator
C++
#include <iostream>
using namespace std;
class A {
private :
int value;
public :
A() {}
A( int l) { value = l; }
A operator||( const A& a)
{
A obj;
obj.value = value || a.value;
return obj;
}
void result()
{
if (value)
cout << "Any one or both value is non zero"
<< endl;
else
cout << "Both value is equal to zero" << endl;
}
};
int main()
{
A a1(95), a2(0);
A a3;
a3 = a1 || a2;
a3.result();
return 0;
}
|
Output
Any one or both value is non zero
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...