I have two classes, Yatzy and YatzyPlayer. In YatzyPlayer.h i create vector<int> mResults and in the constructor in (YatzyPlayer.cpp) i resize it by mResults.resize(15,-2). I also have a function to return this vector declared like vector<int> getResults() and returns mResults. Then in my Yatzy file I'd like to have a vector with this class to keep track on the different players. So in Yatzy.h i declare vector<YatzyPlayer> mNbrPlayers and in the constructor in Yatzy.cpp i add a player: mNbrPlayers.push_back(YatzyPlayer()). The thing is now when i try to call the method getResults() it returns a vector of zero size, why is that? When I print out cout << YatzyPlayer().getResults().size(); it returns 15 which I want to, so anyone have a guess at what I'm doing wrong?
In this last code snippet in startGame the above statement returns zero and the other YaztyPlayer().getResults().size() returns 15. I'd like the first one to return 15 aswell. Thanks
The default copy constructor provided by the compiler does a member-wise copy of all the elements. Yours has to do the same.
1 2 3 4 5
Yatzy::Yatzy( const Yatzy& that ) :
mNbrPlayers( that.mNbrPlayers ) // Invokes copy constructor of the only class member
// You'd do the same for the rest of your members here, separated by commas.
{
}
Things start getting trickier when you have raw pointers as data members and you need to take "deep" copies (ie, copy what the pointer points to rather than the pointer value itself).
EDIT: I just noticed your assignment operator has the same problem: it does nothing. (Also, it does not have the right signature):
1 2 3 4 5 6 7 8 9 10 11
Yatzy& operator=( Yatzy that ) // Or const Yatzy&, but NOT (non-const) Yazty&
{
std::swap( mNbrPlayers, that.mNbrPlayers );
// If passing by const reference, then instead of above line, do:
// mNbrPlayers = that.mNbrPlayers;
// However understand that this function would not be exception-safe
// if more data members are ever added. As I've written it, as long
// as you use the copy-swap idiom as I've done, this method will be
// exception-safe.
return *this;
}