I
I
Ihor Bratukh2020-02-02 23:17:59
Arduino
Ihor Bratukh, 2020-02-02 23:17:59

How to dynamically initialize a class?

Code from PlatformIO ESP32 dev, Arduino framework.
There is a global structure, it still contains an empty reference to an instance of the dht sensor class. If the condition is positive, then you need to initialize the class reference to this global object so that other parts of the program can use the sensor in this way:global.sensors.dht->method(). Can't do it dynamically. After the launch, it throws out the backtrace (since I initialized the class in the init () method, assigned the link to the global object, and then after the init () function was executed, the class that I created called the destructor and was destroyed, the link in the global object, as I understand it, is no longer valid, from this and the error at runtime). If you initialize dht globally (always, without any runtime conditions) and throw the instance reference into the global object in the init() method, then everything works. But I would like to dynamically initialize the sensors, for example, by accepting parameters via http and if the response is, for example dht: true, then initialize the sensor and collect data, for example, every 2 seconds. If the condition does not match, then let the entire program execution time in this global sensor object be simplynullptr

// global.h
typedef struct {
  SensorDht *dht = nullptr;
} GlobalSensors_t;

class Global {
  public:
    static void init(Global *global);
    GlobalSensors_t sensors;
};

void Global::init(Global *global) {
  if (/* условие */) {
    global->sensors.dht = /* что-то типа &new SensorDht(...args) */
    Serial.println(F("Create sensor dht"));
  }
}


// main.cpp
Global global;

void setup() {
  Global::init(&global);

  // global.sensors.dht->init();
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Armenian Radio, 2020-02-02
@BRAGA96

You can not rearrange the link on the go somewhere. Pointer is possible.

C
CityCat4, 2020-02-03
@CityCat4

Remove the "C" tag - it has nothing to do with classes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question