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