Reputation: 9242
Based on issues growing out of previous questions: vector::erase with pointer member, Remove elements of a vector inside the loop, I still need some help on vector.erase function. I was indicated to implement a copy constructor to make the erase function work on a vector, something that is also mentioned in another question. It is essential to implement a function operator in my relevant class. On doing this I get another error on creating the copy constructor and I cannot find the reason for long. The error is “Player::Player(const Player& otherPlayer) does not provide an initiallizer for:” . What am I doing wrong? Take into consideration that Player contains as class members map, pointers and a reference (bank is a reference) . Is a simple assignment adequate for the initialization?
What should I do?
class Player
{
public:
Player(int,int,string, Bank&);
Player(const Player&);
Player& operator = (const Player& rhs);
Player::Player(const Player& otherPlayer)
{
ID = otherPlayer.ID;
pName = otherPlayer.pName;
pMoney = otherPlayer.pMoney;
doubleIndicator = otherPlayer.doubleIndicator;
position = otherPlayer.position;
bank = otherPlayer.bank;
colBought = otherPlayer.colBought;
housesColBuilt = otherPlayer.housesColBuilt;
}
Update: I get a warning at the point of implementantion of the operator= as:"returning address of a local variable or temporary". Does this evoke a real problem? If so, how could I modify it to get over this?
Player& Player::operator=(const Player& rhs)
{
return Player(rhs);
}
In this way, I still receive a warning that the recursive function will cause stack overflow:
Player& Player::operator=(const Player& rhs)
{
*this = Player(rhs);
return *this;
}
Any hint?
Upvotes: 0
Views: 995
Reputation: 110174
You must initialize references that are members of a class with a member initializer in the constructor:
Player::Player(const Player& otherPlayer) :
bank(otherPlayer.bank)
{
//...
}
This is needed because otherwise the reference would be uninitialized, which is not allowed.
Note that the assignment bank = otherPlayer.bank;
does something different: It assigns the object that is referenced, rather than sets the reference itself.
It's also good style to initialize other members (even if they aren't references) in the same way, as it can lead to more optimal code (otherwise members could be default-constructed before being assigned).
Upvotes: 3