Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is this private variable in a c++ object not updating?

To demonstrate my issue I have written a very simple program in Arduino:

A class declaration that contains a single private variable thing

#ifndef LED_H
#define LED_H
#include <Arduino.h>

class LED {
  private:
    int thing;
  public:
    LED();
    void setThing(int newThing);
    int getThing();
};

#endif

The class implementation

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include "LED.h"

LED::LED() {}

void LED::setThing(int newThing) {
    thing = newThing;
}

int LED::getThing() {
    return thing;
}

My main program

#include <Arduino.h>
#include "LED.h"

LED MY_LED;
void updateLED(LED led);

void setup() {
    Serial.begin(9600);
    MY_LED.setThing(1);
    Serial.println(MY_LED.getThing()); // Outputs "1" as expected
}

void loop() {
    delay(2000);
    updateLED(MY_LED);
}

void updateLED(LED led) {
    led.setThing(led.getThing() + 1);
    Serial.println(led.getThing()); // Is stuck on "2", it should be incrementing 2,3,4,5 etc
}

Why is the private thing variable not being updated? I would expect it would be incrementing by 1 every time the loop runs.

>Solution :

This really has little (or nothing) to do with inheritance, just parameter passing.

void updateLED(LED led) {

Here you’re passing led by value, not by reference. That means the led received by the function is a copy of the led object you pass when you call the function.

The function updates the copy of the value that it receives–but that has no effect on the led object of which it’s a copy.

You apparently want to pass the led by reference instead:

void updateLED(LED &led) {

This way, when it executes led.setThing(led.getThing() + 1);, it’ll update the object to which you passed a reference.

However, if you’re going to write LED class, you might as well have it support the operations you actually want–something along this line, perhaps:

class LED {
    int thing = 0;
public:
    LED &operator++() {
        ++thing;
        return *this;
    }

    void print() {
        Serial.println(thing);
    }
};

// ...

LED my_led;
for (;;) {
    ++my_led.print();
    delay(2000);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading