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;
}

Recommended Answers

All 2 Replies

Try creating a == operator, something like below

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

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;
  }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.