Search code examples
c++oopgetter-setteraccessormutators

c++ int accessor return 0 even if mutator sets properly


I'm stuck at a problem I feel stupid about as it's basically just two lines of code in midst of a 2000 line working OOP script.

Cut to the chase - I have an Entity class which provides various information (name, address, ID). The problem is - even if the ID mutator (setter) sets a proper value (tested with cout and return value), the accessor always returns 0.

// ID accessor
int Entity::ID() const {
    return _ID;     
}
// ID mutator
int& Entity::ID( int newID ) {
    if ( newID >= 0 ) {
        _ID = newID;
    }
    return _ID;
}

Here are my classes (the ID( int ) method is called in AgencyNetwork::createXXX() and is used in every toStr() method (at the end of each class)):

Entity.cpp, AgencyNetwork.cpp, Agent.cpp

SOLVED: I forgot to add the ID mutator in every operator=. Thanks to everyone who helped :)


Solution

  • Most notably, the assignment operator of Entity is broken:

    Entity& Entity::operator= ( const Entity& tocopy ) {
        delete this; // <<< don't do that 
    
        this -> name ( tocopy.name() );
        this -> address ( tocopy.address() );
        // <<< missing _ID
    
        return *this;
    }