Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use one object's method to update another object's attribute?

Tags:

c++

methods

oop

I have three (C++) classes: Player, Hand, and Card.

Player has a member, hand, that holds a Hand. It also has a method, getHand(), that returns the contents of hand.

Hand Player::getHand() {
    return hand;
}

Hand has a method, addCard(Card c), that adds a card to the hand.

I want to do this:

player1.getHand().addCard(c);

but it doesn't work. It doesn't throw an error, so it's doing something. But if I examine the contents of player1's hand afterward, the card hasn't been added.

How can I get this to work?

like image 923
rarbuthnot Avatar asked Mar 31 '26 00:03

rarbuthnot


1 Answers

If getHand() returns by-value you're modifying a copy of the hand and not the original.

like image 87
Adam Mitz Avatar answered Apr 02 '26 13:04

Adam Mitz