A user-defined struct automatically inherits an Equals method that performs a value equality check by comparing each field of the struct. The == operator, however, is not automatically defined.  If you want to use the == operator for instances of a struct, you need to overload the == operator.

```    public struct PersonHeight
{
public int Feet { get; set; }
public int Inches { get; set; }

public PersonHeight(int feet, int inches) : this()
{
Feet = feet;
Inches = inches;
}

public static bool operator ==(PersonHeight ph1, PersonHeight ph2)
{
return (ph1.Feet == ph2.Feet) && (ph1.Inches == ph2.Inches);
}

public static bool operator !=(PersonHeight ph1, PersonHeight ph2)
{
return !(ph1 == ph2);
}
}
```

Some test cases:

```            PersonHeight ph1 = new PersonHeight(5, 10);
PersonHeight ph2 = new PersonHeight(5, 10);

// Returns true, default Equals method compares each field
bool check = ph1.Equals(ph2);

// == operator also now works - true
check = (ph1 == ph2);
``` About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

### 3 Responses to #410 – Overloading the == Operator for a Value Type

1. inez says:

can you help? I am receiving LOTs of errors….

#include
#include
#include

using namespace std;

struct electionList
{
void print() const;
void voteTotal();
void solvePercentage();
void calcWinner();
double percentage;
string candidates;
int count;
int total;

};

//CALCULATES TOTAL AMOUNT OF VOTES FOR EACH CANDIDATE
void electionList::print() const
{

for (int i=0; i<count; i++)
{
cout<<candidates[i];
cout<< percentage[i];
}

cout<<"Total"<<total<<endl;
}

void electionList::voteTotal()
{
int total;
for (int i=0; i<count; i++)
{
}
}

//CALCULATES PERCENTAGE OF VOTES FOR EACH CANDIDATE

void electionList::solvePercentage()

{
for (int i=0; i<count; i++)
{
}
}

//cOMPARES NUMBER OF VOTES FOR WINNER

void electionList::calcWinner()
{
string winner = candidates;

for (int i=0; imax)
{
winner = candidates[i];
}
}

};

int main()
{

electionList election;
electionList insert();

string name;
int count;

int tally;
string candidate;

//INPUT DATA

cout<> count;

for (int i=0; i<count; i++)

{
cout<>name>>tally;
candidate[i]=name;

}
count = 1;
candidate=”thomas”;

• Sean says:
2. inez says: