views:

44

answers:

1

Here is my code that fails:

bool Table::win(const Card &card) {
   for (int i = 0; i < cards.size(); i++)
      if (card.getRank() == cards[i].getRank()) return true;

   return false;
}

Error message is: passing 'const Card' as 'this' argument of 'int Card::getRank()' discards qualifiers.

When I get a copy of the card and change the code to this it works:

bool Table::win(const Card &card) {
   Card copyCard = card;

   for (int i = 0; i < cards.size(); i++)
      if (copyCard.getRank() == cards[i].getRank()) return true;

   return false;
}

Is there any other way to do this?

+3  A: 

Is getRank a const-method? It should be declared like this":

int getRank( ) const;

Assuming the return type is int.

Space_C0wb0y
Sorry, I didn't provide that information. No, it's not.
pocoa
Ok, it's working. Thanks, but I didn't really understand why..
pocoa
So, if I'm passing an object as a constant variable, should I declare all of its methods as constant?
pocoa
Read this to understand more about const: http://www.parashift.com/c++-faq-lite/const-correctness.html
Space_C0wb0y
@pocoa - if a method does not modify an instance, it should be a `const` method. This allows the method to be called on `const` instances.
R Samuel Klatchko
@Space: Great link, thanks.
pocoa
@Samuel: So if I need to call setRank() into that function, I shouldn't pass that object as a const reference right?
pocoa
For any parameter, if you need to change it [via a `setRank()` function, for instance], you need to pass it as a non-const reference.
Dennis Zickefoose
@Dennis: Thanks.
pocoa