Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison between two objects under the same class

Tags:

c++

comparison

I am still new to C++ (programming in general)and forgive me if this question is stupid or has been asked numerously. Here is the question..Let's say there are two objects A and B under the same class.

e.g

  class Fruit{
  int apple;
  int banana;
      fruit(int x, int y){
       apple=x;
       banana=y;
      }
  }
  Fruit A(1,1);
  Fruit B(1,1);

If I want to check if content from Object A is the same as Object B's, do I have to compare every variablefrom A to B, or

   if(Object A == Object B)
   return true;

will do the job?

like image 802
GalaxyVintage Avatar asked May 15 '15 00:05

GalaxyVintage


1 Answers

if(Object A == Object B)
    return true;

will do the job? No it won't, it won't even compile

error: no match for 'operator==' (operand types are 'Fruit' and 'Fruit')

You need to implement a comparison operator==, like

bool Fruit::operator==(const Fruit& rhs) const
{
    return (apple == rhs.apple) && (banana == rhs.banana);
    // or, in C++11 (must #include <tuple>) 
    // return std::tie(apple, banana) == std::tie(rhs.apple, rhs.banana); 
}
like image 101
vsoftco Avatar answered Sep 28 '22 16:09

vsoftco