Hatefiend
Hatefiend

Reputation: 3596

C++ Passing in Vector by Reference but changes still not being saved

I made a project with a class called Card which has a name, suit, and value.

I have a deck class which makes a vector of which has 52 elements.

I have a table class which handles many vectors: discard pile, players hand, etc.

Then just my main cpp which runs it all.

Deck.h

public:    
Deck();
void deal(vector<Card>& pile); //Deals a card from the top 
//of the deck to any passed-in hand or pile. 

private:
vector<Card> deck;

Deck.cpp

void Deck::deal(vector<Card>& pile) //Deal a card to whichever pile on the table.
{
    pile.push_back(deck[deck.size() - 1]); //Add the card from the deck to the pile
    deck.pop_back(); //Remove the card that we copied from      
}

Table.h

public:    
Table();
void deal(vector<Card>& pile); //Deals a card from the top 
//of the deck to any passed-in hand or pile. 
vector<Card> getPlayersCards();

private:
vector<Card> playersCards;
vector<Card> discard;

Table.cpp

vector<Card> Table::getPlayersCards()
{
    return playersCards;
}

vector<Card> Table::getDiscardPile()
{
    return discard;
}

Main.cpp

//VARIABLES
Deck theDeck;
Table theTable;

int main()
{
    theDeck.deal(theTable.getPlayersCards()); //Attempt to deal a card
    //out to the player's hand
}

so here's the problem, I put some couts in the program and here's what is happening. Notice how it works perfectly once it's in the deal method but as soon as it goes back to my main cpp, it forgets all about ever having moved that card. However the main deck has 51 cards, meaning THAT worked, which makes sense because the variable deck was not passed in.

enter image description here

If you guys can offer any help, I would be so appreciative.

Upvotes: 0

Views: 664

Answers (2)

ChronoTrigger
ChronoTrigger

Reputation: 8617

The problem is that theTable.getPlayersCards() is returning a copy of vector<Card> playersCards instead of a reference to it.

Try changing this in Table.cpp:

vector<Card>& Table::getPlayersCards()
{
  return playersCards;
}

vector<Card>& Table::getDiscardPile()
{
  return discard;
}

and this in Table.h:

vector<Card>& getPlayersCards();
vector<Card>& getDiscardPile();

Upvotes: 3

Zan Lynx
Zan Lynx

Reputation: 54325

The result from getPlayersCards() is a copy of the cards. Not a reference. So when deal returns the copy of its argument gets destroyed.

Upvotes: 1

Related Questions