Is there a way to make a C++ variable persistent in object scope?
"static" key word makes the variable persistent but it is class scope.
I need a persistent variable for each instance of class.
Here is an example
class MyClass
{
public:
void myFunction()
{
static int staticCounter=0; // variable shared by all instances of class
int autoCounter=0; // value forgotten after every call
Serial.print("staticCounter=");
Serial.print(staticCounter);
Serial.print(", autoCounter=");
Serial.print(autoCounter);
Serial.println();
staticCounter++;
autoCounter++;
}
};
MyClass obj1;
MyClass obj2;
void setup()
{
Serial.begin(9600);
delay(500);
}
void loop()
{
for (int i=0; i<3; i++)
{
obj1.myFunction();
}
for (int i=0; i<3; i++)
{
obj2.myFunction();
}
while (true)
{
}
}
For each object there is a unique int counter but for all there is one static int staticCounter.
All Objects in a class share functions and by extension static variables in them.
Nice example code in that it does show only what you're concerned with, BTW.
So that only creates a static variable whose scope is only inside that object's function & not to all functions in the object. If you were wanting the scope to all functions in the object & you wanted to maintain the scope only to that class...
Simply initialize the variable outside the class or at the top of the .cpp file.
// Example of a properly used static variable used inside class, BUT INITIALIZED OUTSIDE OF CLASS!
#define PrintArg(v){ \
Serial.print(#v); \
Serial.print(" = "); \
Serial.println(v); \
}
class Example{
public:
int16_t ID; // Member Variable
static int16_t NextID;
Example(){ // Class contstructor
ID = NextID++; // reads static variable stores in id unique to each individual object
}
int16_t getNextID(){
return(NextID);
}
};
int16_t Example::NextID = 0;
Example Ex0, Ex1, Ex2;
void setup(){
Serial.begin(115200); // Start serial at 115200 baud rate
while(!Serial); // Wait for Serial Terminal to startup
delay(300); // Initial delay seems to work
PrintArg(Ex0.ID); // Prints: "Ex0.ID = 0"
PrintArg(Ex1.ID); // "Ex1.ID = 1"
PrintArg(Ex2.ID); // "Ex2.ID = 2"
PrintArg(Ex0.getNextID()); // Prints: "3"
PrintArg(Ex1.getNextID()); // "3"
PrintArg(Ex2.getNextID()); // "3"
}
void loop(){ }
If you want a static variable to be shared by all instances of the class, you declare that variable to be static, inside the class, but not inside one of the functions.