Reputation: 197
I am trying to change the value of an int variable in my Card class shown below:
class Card {
public:
enum Suits {diamond, heart, club, spade};
Card (int _rank, Suits _suit) : rank{_rank}, suit{_suit} {}
int getRank();
void changeRank(int change);
private:
int rank;
Suits suit;
};
card.cpp:
int Card::getRank() {
return rank;
}
void Card::changeRank(int change) {
rank = change;
}
Here is the Player class:
class Player {
private:
vector<Card> playerHand;
public:
Card getCard(int index);
};
player.cpp:
Card Player::getCard(int index) {
return playerHand[index];
}
Here is the dealer.cpp file that actually makes the call:
if (oneOrEleven == 11) {
player.getCard(i).changeRank(11);
cout << "The ace will have a value of 11" << endl;
}
This code is calling the method "changeRank()", it's just not changing the value of "rank" in the Card object.
What am I doing wrong?
Upvotes: 1
Views: 83
Reputation: 11
This code is calling the method "changeRank()", it's just not changing the value of "rank" in the Card object.
Change the function declaration of getCard to return by reference, i.e:
Card& getCard(int index);
The way you have your function declaration right now, it is returning a Card object by value, and not by reference.
When you return by value, you are returning a copy of the object, and not the actual object itself.
Upvotes: 1
Reputation: 172964
You should change Player::getCard
from return-by-value to return-by-reference. e.g.
Card& Player::getCard(int index) {
return playerHand[index];
}
Ohterwise, you'll always modify on the returned copy, which has nothing to do with the original element in the vector.
Upvotes: 2