Dolav
Dolav

Reputation: 45

Operator= overloading not working unless object was already initialized

I have a class called game, this is the code of it's operator=:

Game& Game::operator=(const Game &other){
if(this==&other){
    return *this;
}else{
    for(unsigned i=0;i<other.players.size();i=i+1){
        Player* copy;
        int str= other.players.at(i)->getStr();
        if(str==1)
            copy = new PlayerType1(dynamic_cast<const PlayerType1&>(*other.players.at(i)));
        if(str==2)
            copy = new PlayerType2(dynamic_cast<const PlayerType2&>(*other.players.at(i)));
        if(str==3)
            copy = new PlayerType3(dynamic_cast<const PlayerType3&>(*other.players.at(i)));
        if(str==4)
            copy = new PlayerType4(dynamic_cast<const PlayerType4&>(*other.players.at(i)));
        players.push_back(copy);
    }
    winners = other.winners;
    state = vector<string>(other.state);
    deck = Deck(other.deck);
    verbal = other.verbal;
    highestNum = other.highestNum;
    turnNum = other.turnNum;
    currPlayer = other.currPlayer;
    lastAsker = other.lastAsker;
    lastAskee = other.lastAskee;
    lastAskedCard = other.lastAskedCard;
    return *this;
}

}

And I try to call it here:

char* cf= "../src/config1.txt";
Game* game = new Game(cf);
game->init();
Game game2=*game;
game->play();
game2.printState();

In that case, my operator= won't be used. But if game2 was already initialized, for example here:

Game* game = new Game(cf);
game->init();
Game game2=*(new Game());
game2=*game;
game->play();
game2.printState();

Any idea what could be the issue?

Upvotes: 1

Views: 47

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140168

In the first case, copy elision avoids that assignment operator is called, in favor of copy constructor.

In the second case, the object is already built, so assignment operator has to be called.

The conclusion is that you have to implement all 3 operators: destructor, assignment, and copy (also known as rule of three) else you can have unpredictable behaviour depending on the compiler.

And the best way to avoid implementing them in an inconsistent way is to use the copy & swap idiom

Upvotes: 1

Related Questions