Answer the question
In order to leave comments, you need to log in
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();
}
stack smashing protector failure esp32
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
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 questionAsk a Question
731 491 924 answers to any question