Reputation: 33
When running my code, it compiles fine, but I don't understand why it isn't iterating and printing out my list.
I have a sub class Games
and super classes: play_ball
and statistics
.
The goal is to have the player play through the games, tracking how many attempts it takes them to win. At the end of each play, it will keep track of each play's statistics and push it to the end of the stats
list.
I think I have everything set up for it, but when I go to print the stats, it doesn't even loop through any part of the list.
I initialize my list in main.cpp
, and push the stats at the end of the play()
function in the play_ball
class.
Is the list not being filled for some reason at the end of each game? If so, how can I fix this?
Here is my code:
games.h:
class games {
friend class statistics;
friend class play_ball;
private:
std::string type;
int attempts = 0;
public:
games();
~games();
virtual void play(std::list<stats>) = 0;
};
static int plays = 0;
play_ball.cpp:
void stats::play(std::list<stats> sts)
{
// Plays the game...
sts.push_back(stats(get_plays(), "Ball ", count));
}
stats.cpp
void stats::play(std::list<stats> sts)
{
if (get_plays() == 0)
{
printf("ERROR: No game history.\n");
}
else
{
std::cout << "[Game Type Attempts:]\n";
// This should go through and print out: [game number] Ball (# of attempts)
// but when I run it, it just skips the loop and prints the "Thanks for playing!"
for (std::list<stats>::iterator p = sts.begin(); p != sts.end(); ++p)
{
std::cout << '[' << (*p).get_plays() << "] "<< (*p).get_type(sts) << " "<< (*p).get_atmpts(sts) << '\n';
}
std::cout << "Thanks for playing!";
}
}
main.cpp:
stats sts;
std::list<stats> l_sts;
play_ball ball;
ball.play(l_sts);
sts.play(l_sts);
Upvotes: 1
Views: 190
Reputation: 94
The argument 'sts' is being passed in by value instead of by reference. When a parameter is passed by reference, the caller and the callee use the same variable for the parameter. If the callee modifies the parameter variable, the effect is visible to the caller's variable. When a parameter is passed by value, the caller and callee have two independent variables with the same value. If the callee modifies the parameter variable, the effect is not visible to the caller.
Upvotes: 2