0

How do I check whether the data members of two objects belonging to the same class are equal? Will the following code do or is it done in some other manner??

class Sample
{
 int a;
public:
 S(int x)
 {
  a = x;
 }

 int getA()
 {
  return a;
 }

 void putA()
 {
  cout<<a;
 }
};

int main()
{
 Sample s1(4), s2(4);

 if(s1 == s2) //IS THIS ALRIGHT??
 {
  cout<<"Same";
 }
 return 0;
}
3
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by Fbody
0

Try creating a == operator, something like below

bool operator ==(const Sample & s) { return a == s.a; }
0

How do I check whether the data members of two objects belonging to the same class are equal? Will the following code do or is it done in some other manner??

class Sample
{
 int a;
public:
 S(int x)
 {
  a = x;
 }

 int getA()
 {
  return a;
 }

 void putA()
 {
  cout<<a;
 }
};

int main()
{
 Sample s1(4), s2(4);

 if(s1 == s2) //IS THIS ALRIGHT??
 {
  cout<<"Same";
 }
 return 0;
}

Have you tried compiling this? I'm guessing not, because you would know if it works or not... This will not work.

For starters, your class is not properly defined. "S" is formatted like a constructor, but it's not a valid constructor. It must be named "Sample" for it to work. Additionally, you will need to define a default constructor because you will no longer have a compiler-provided one.

If you want to use a certain operator (such as the equality operator '==') with a custom class, you must implement your own version of the operator to tell the compiler how that operator should behave when requested. To do so, you must write an "operator function". For example, a function called "operator==" would be required to use the equality operator:

bool Sample::operator==(const Sample &other) {
  if (...) {
    return true;
  } else {
    return false;
  }
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.