سؤال

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 :)

هل كانت مفيدة؟

المحلول

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;
}

نصائح أخرى

There is no magic. There is plain BUG. So, lets use tracing: trace every 'mutator' call. Make sure that nobody can access the _ID field in other way than through the mutator call. Trace constructor, copy constructor, copy assignment operator and destructor calls also. Then run your code and follow the trace log. I'm sure everything will become clear in your case.

NOTE: if your implementation misses some of the member functions mentioned above you should to define them with the bodies consisting of tracer call only.

You shouldn't let the compiler to make any implicit member function generation in order to be sure that you've the full control of you class and particularly the _ID field.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top