Hi,

I was given this class member function that overloads the == operator. I don't understand it. Please could you help me understand it?

Here is the class

class Word
{
public:
	// constructor
	Word(const string& word);		
	// overloads is-equal-to (or equivalence) operator - this is very useful for testing, 
	// as we can compare words directly
	bool operator==(const Word& rhs) const;			
	bool isQueryable() const;

private:	
	string _word;	
};

Here is the function:

// overloads the equivalence operator which allows two Words to be compared using ==
bool Word::operator==(const Word& rhs) const		
{
	if (_word == rhs._word)			  
		return true;
	else
		return false;
}

So is the function parameter an object (rhs) of class Word. If it is, then what is the if statement comparing and how? If _word belongs to rhs on the RHS, then what object does _word on the LHS belong to? I plan on testing this code with gTest, as in:

TEST(Word, identicalWordsAreEqual) {  
	Word word1("that");		
	Word word2("that");
	EXPECT_TRUE(word1 == word2);
}

Recommended Answers

All 3 Replies

// overloads the equivalence operator which allows two Words to be compared using ==
bool Word::operator==(const Word& rhs) const		
{
	if (_word == rhs._word)			  
		return true;
	else
		return false;
}

That compares another Word with the current Word. The current Word has its own '_word' variables, so it checks if the another Word( rhs )'s '_word' value is the same as the current Word's. In other words, it checks if rhs._word is equal to this->_word

Two things:
To expand on what firstPerson mentioned, I always find it more descriptive to write functions that take an equivalent type like:

bool Word::operator==(const Word& that) const {
   return this->_word == that._word;
}

It helps keep explicit the relationship between the two types even though the this is redundant.

Also, when you see something like word1 == word2 what is actually happening is something along the lines of word1.operator==(word2) if that helps you understand the translation to what you actually put in the class definition.

Ohhh I think I see. Thanks for your replies. So basically if I say "word1 == word2" then word1 is the "current" this word, and word 2 is the new that word.

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.