Jonas Jonas - 1 month ago 16
C++ Question

c++ overload operator ++

For a school project I have to implement a sensor class in c++ which has a private property active (boolean) which indicates if the sensor is active or not.
I have to overload the ++ operator in such way that if the operator ++ is used the property active will be set to true.

I implemented the following (sensor.cpp):

Sensor::Sensor(int id, std::string vendor) : _id(id), _vendor(vendor) {
std::cout << "Sensor created with id: " << Sensor::getId() << std::endl;
_status = false;
}

bool Sensor::getStatus() {
return _status;
}

void Sensor::setStatus(bool status) {
_status = status;
}

Sensor& Sensor::operator++() {
Sensor result = *this;
this->setStatus(true);
return result;
}


main.cpp:

int main(int argc, char *argv[]) {
Sensor * sensor = new Sensor(1, "sample vendor");
sensor->setStatus(false);
sensor++;
std::cout << "status: " << sensor->getStatus() << std::endl;
}


I noticed that the program stops executing (finishes) with the last method to be executed the sensor->setStatus(false); in main.cpp but no error is shown in my terminal nor did my compiler complain.

Does someone has an idea what i did wrong and how I can correct it so that the status is set to true?

Thanks in advance

Answer

Since sensor is a pointer, sensor++ increments the pointer not the object. Easiest solution is to just not use a pointer in the first place.

int main() {
    Sensor sensor{1, "sample vendor"};
    sensor.setStatus(false);
    sensor++;
    std::cout << "status: " << sensor.getStatus() << std::endl;
}

Another solution is to use (*sensor)++...

int main() {
    std::unique_ptr<Sensor> sensor =
        std::make_unique<Sensor>(1, "sample vendor");
    sensor->setStatus(false);
    (*sensor)++;
    std::cout << "status: " << sensor->getStatus() << std::endl;
}

Another error in your code is here:

Sensor& Sensor::operator++() {
    // You don't want to do this... it creates a copy!
    Sensor result = *this;
    this->setStatus(true);
    // This is a dangling reference!
    return result;
}

Use this instead:

Sensor& Sensor::operator++() {
    this->setStatus(true);
    return *this;
}