I'm new to c++ (coming from Java and C#), and I'm trying to override the == operator in one of my classes so I can see if I have 2 object that have the same value for a given property. I've been doing a bunch of googling and trying to make something that works. What I need is for the == operator to return TRUE when 2 objects have the same _name text.
Here's the header file:
//CCity.h -- city class interface
#ifndef CCity_H
#define CCity_H
#include <string>
class CCity
{
friend bool operator ==(CCity& a, CCity& b)
{
bool rVal = false;
if (!(a._name.compare(b._name)))
rVal = true;
return rVal;
}
private:
std::string _name;
double _x; //need high precision for coordinates.
double _y;
public:
CCity (std::string, double, double); //Constructor
~CCity (); //Destructor
std::string GetName();
double GetLongitude();
double GetLatitude();
std::string ToString();
};
#endif
In my main() method:
CCity *cit1 = new CCity("bob", 1, 1);
CCity *cit2 = new CCity("bob", 2, 2);
cout<< "Comparing 2 cities:\n";
if (&cit1 == &cit2)
cout<< "They are the same \n";
else
cout << "They are different \n";
delete cit1;
delete cit2;
The problem is that my code in the friend bool operator == block never gets executed. I feel like I'm doing something wrong with either how I'm declaring that operator, or how I'm using it.