The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. 
Home Vectors of Objects The Equals Function  
The Equals Function
It is clear that the return value from equals should be a boolean that indicates whether the cards are the same. It is also clear that there have to be two Cards as parameters. But we have one more choice: should equals be a member function or a freestanding function? As a member function, it looks like this: bool Card::equals (const Card& c2) const{ return (rank == c2.rank && suit == c2.suit); } To use this function, we have to invoke it on one of the cards and pass the other as an argument: Card card1 (1, 11);Card card2 (1, 11); if (card1.equals(card2)) { cout << "Yup, that's the same card." << endl; } This method of invocation always seems strange to me when the function is something like equals, in which the two arguments are symmetric. What I mean by symmetric is that it does not matter whether I ask "Is A equal to B?" or "Is B equal to A?" In this case, I think it looks better to rewrite equals as a nonmember function: bool equals (const Card& c1, const Card& c2){ return (c1.rank == c2.rank && c1.suit == c2.suit); } When we call this version of the function, the arguments appear sidebyside in a way that makes more logical sense, to me at least. if (equals (card1, card2)) {cout << "Yup, that's the same card." << endl; } Of course, this is a matter of taste. My point here is that you should be comfortable writing both member and nonmember functions, so that you can choose the interface that works best depending on the circumstance.


Home Vectors of Objects The Equals Function 