Stephen
Stephen

Reputation: 491

How to use another classes member variables in c++?

I'm currently programming a Yahtzee game, and I'm having trouble with some of my classes

I have two classes, Player, and Scorecard.

class Player {
  private:
    string name;
    Scorecard scorecard;
};


class Scorecard {
  public:
    void display() {
      //...
    }
};

(All the classes have the appropriate getters and setters)

I'd like the scorecard class to be able to display the name of the player to the user. Is there any way that can be done?

Upvotes: 1

Views: 3060

Answers (6)

Thomas Matthews
Thomas Matthews

Reputation: 57678

I would not have Scorecard print the Player's name. A player has-a scorecard. A scorecard does not have a a player.

The Player class should have a display method that displays the player's name followed by the score card:

class Player
{
  private:
     string name;
     Scorecard scorecard;

  public:
    void display(void)
    {
        cout << "Player name: " << name << endl;
        scorecard.display();
    }
};

Also, since Player contains a Scorecard, you should declare the Scorecard class before class Player:

class Scorecard
{
 /*... */
};

class Player
{
 /* ... */
};

Upvotes: 5

Mike DeSimone
Mike DeSimone

Reputation: 42795

Typically, I'd tell the Scorecard about the Player that owns it:

class Scorecard;

class Player {
  public:
    explicit Player(const string& name_): name(name_), scorecard(*this) {}
    const string& Name(oid) const { return name; }
  private:
    string name;
    Scorecard scorecard;
};

class Scorecard {
  public:
    Scorecard(Player& player_): player(player_) {}
    void display() {
      cout << player.Name() << endl;
      //...
    }
  private:
    Player& player;
};

Upvotes: 0

Falmarri
Falmarri

Reputation: 48559

You have to somehow give Scorecard the instance of player. Also, Player needs either a public getter or make name public.

Upvotes: 1

Notter
Notter

Reputation: 588

You could add a PlayerName property to the Scorecard, and then it will be able to store a name. then the display() function will get the name as a parameter

Upvotes: 0

atzz
atzz

Reputation: 18010

There are several options.

  1. Pass name as a parameter to display() function. (You are calling display() from within a member function of Player, right? If not, you'll also need to add a public accessor method to Player for getting its name.)

  2. Pass a reference to the owining Player to Scorecard object (e.g. via constructor) and store it within Scorecard. Add a public accessor menthod to Player for getting its name.

Personally, I like (1) better, because it allows to minimize dependencies between Player and Scorecard classes.

Upvotes: 0

Beanz
Beanz

Reputation: 1977

The best way to do that is to add a public accessor method to Player that returns either a copy or constant reference to Player::name.

Upvotes: 0

Related Questions