[SOLVED]Retained and variable of class


I managed to use retained variable of basic type, but not with variable of class. Is it possible ?
Should I “retained” all variable inside of the class ?

Thanks !

I’d add serialize/deserialize methods for a class to be stored away and recreated after wake.

No, you cannot make a class retained. You need to use Serialization (above) to do that.

The main reason is that retained variables are position dependent in SRAM, as determined by the compiler, and the compiler doesn’t know how many instances of the class there might be at runtime. Plus it would be crazy fragile from version to version of your code.

Now I would have thought that you might be able to make static class member variables, so there is only one instance of the member variable and the compiler might be able to handle that. As it turns out, it compiles, but does not link, so that doesn’t really work either. (Update Below: I figured out how to make this work!)

In any case, it’s probably best to use global variables for retained variables anyway, because changing the layout of the SRAM retained variables can cause massive confusion in your code. Remember that flashing a new version of your code doesn’t clear the SRAM, so if you move or change retained variables you can cause very unexpected data!

Thank you ! you confirm what I thought. Global variables are what i plan to do, but I wanted to kown that there is no other way. When I flash, I save data and remove power on Vbat, so no problem !

So you can retain static class member variables. I had an error my declaration when I was testing. This code works:

#include "Particle.h"


class TestClass {
	static int getAndIncrement();

	static int classVal;

retained int testInt = 0;
retained int TestClass::classVal;
TestClass testClass;

void setup() {

void loop() {
	Serial.printlnf("testInt=%d", testInt);

	Serial.printlnf("classVal=%d", TestClass::getAndIncrement());


int TestClass::getAndIncrement() {
	return classVal++;

Thanks a lot, I will try that before !