operator – comparisons

Comparisons between classes are different compared to local variables e.g. int(eger), float, doubles.. because the comparisons aspects of the standard variables have already been done e.g.

int a=2;
int b =3;
if (a==b)....

the comparison being the “==”, within your own classes if you want to test against a another object that is of the same class you will have to write a comparison function that will either return true or false, of course there are other comparisons <,>, <=, >= etc and also +,- which can be implemented if you wanted to.

The basics of the comparison operator is

bool operator == (const yourclassname &tester)

where yourclassname is what you have called your class, of course you can run comparisons with other classes and also standard variables like floats, but you will need to write a separate one for each. The operator is the keyword, and it returns a bool(ean) result which is either true/false, so once you have done a comparison within this function you just return either true or false and the code below will still compile

classA a;
classA b;
if (a==b) ..

below is code that you can compile to demonstrate operator keyword abit more.

#include <iostream>
 
using namespace std;
 
class classA
{
  public : 
    int x;
 
  // of course you cannot alter the testing class so const 
  // the tester is the right hand side of the boolean test e.g.
  // if (A == B ) . A = this class and B = tester
  bool operator == (const classA &tester)
  {
      if (x == tester.x) 
	return true; 
      else 
	return false;
  };
};
 
int main()
{
    classA a;
    classA b;
    a.x = 0;
    b.x = 0;
 
    if (a==b)
      cout << "the same" << endl;
    else
      cout << "not the same" << endl;
 
    b.x = 1;
 
    if (a==b)
      cout << "the same" << endl;
    else
      cout << "not the same" << endl;
 
    return 0;
}

and the output would be

the same
not the same

Leave a Reply

Your email address will not be published.