I
I
Ihor Bratukh2019-12-08 16:41:17
Arduino
Ihor Bratukh, 2019-12-08 16:41:17

How to initialize a class inside a method of another class?

Hello. How to correctly initialize a class inside a method of another class?
This code is working, but there are doubts that there are more correct ways.
How to correctly describe a class instance in a .h file so that it is not initialized immediately without parameters, but let it know that it will be initialized later, for example, in a class method or its constructor?

// SensorDht.h
class SensorDht {
  private:
    DHT* dht;
    uint8_t pin;
    uint8_t type;

  public:
    SensorDht(uint8_t pin, uint8_t type);
    void init();
};

// SensorDht.cpp
SensorDht::SensorDht(uint8_t pin, uint8_t type) {
  this->pin = pin;
  this->type = type;
}

void SensorDht::init() {
  DHT instance(this->pin, this->type);
  this->dht = &instance;
  this->dht->begin();
}

UPD: The method is not quite working, further along the code I get an exception: stack smashing protector failure esp32
If initialized like this, then everything works well, but requires additional initialization in the code, which I would like to avoid for code purity:
DHT dht(GPIO_NUM_17, DHT22);
SensorDht sensor_dht(&config, &dht);

SensorDht::SensorDht(Config* config, DHT* dht) {
  this->config = config;
  this->dht = dht;
}

void SensorDht::init() {
  this->dht->begin();
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2019-12-08
@BRAGA96

This instance is destroyed when you exit the method, so you cannot store a reference to it. Use dht = new SensorDht(pin, type)
In general, in modern C++, the use of raw pointers seems to be discouraged.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question