I'm not good with the nomenclature... but I call this two instances of identical objects. Anyway, I expect the 'static' variable "wasa" to be INDEPENDENT for each instance, but they are not. Why? I clearly do not understand this well enough...
#include <Arduino.h>
namespace ns {
class C {
public:
C(void);
~C(void);
void m(int a);
private:
};
}
namespace ns {
C::C(void){}
C::~C(void){}
void C::m(int a){
static int wasa=999;
Serial.print("in:");Serial.print("a=");Serial.print(a);Serial.print(" wasa=");Serial.println(wasa);
wasa=a;
Serial.print("ot:");Serial.print("a=");Serial.print(a);Serial.print(" wasa=");Serial.println(wasa);
}
}
ns::C inst0; // instance 0
ns::C inst1; // instance 1
void setup() {
Serial.begin(9600);
while (!Serial) { Serial.print("."); }
Serial.println("\nSerialReady");
}
void loop() {
inst0.m(7);
inst1.m(3);
delay(100000);
}
I expect inst0 and inst1 to contain different values in 'wasa' and that they would not affect each other. But that is clearly not the case. Here's the output (I added the WTF text;-)
output:
SerialReady
in:a=7 wasa=999
ot:a=7 wasa=7 <---- WTF?
in:a=3 wasa=7 <---- WTF?
ot:a=3 wasa=3 <---- WTF again?
Inside a class definition, the static keyword declares members that are not bound to class instances.
The static keyword is used for a bunch of different things in C++ (e.g.function/file variable scope).
if you want each instance to contain its own wasa member, you declare it like this:
#include <Arduino.h>
namespace ns {
class C {
public:
C(void);
~C(void);
void m(int a);
//int wasa = 999; // can be accessed from outside the class using the dot operator i.e. instance.wasa
private:
int wasa = 999; // can only be accessed from class members here
};
}
namespace ns {
C::C(void){}
C::~C(void){}
void C::m(int a){
Serial.print("in:");Serial.print("a=");Serial.print(a);Serial.print(" wasa=");Serial.println(wasa);
wasa=a;
Serial.print("ot:");Serial.print("a=");Serial.print(a);Serial.print(" wasa=");Serial.println(wasa);
}
}
ns::C inst0; // instance 0
ns::C inst1; // instance 1
void setup() {
Serial.begin(9600);
while (!Serial) { Serial.print("."); }
Serial.println("\nSerialReady");
}
void loop() {
inst0.m(7);
inst1.m(3);
delay(100000);
}
Thanks BulldogLowell, that was exactly what I needed. I realized how I came to write what I had... I took some non-object oriented code and copied it verbatum to the OO code I was making. That's where that silly "static' thing came from. Once you spelled it out for me... I had to whack myself upside the head. Right. You're code is EXACTLY what I should have done.