Justin
Justin

Reputation: 543

C++ object within object

I'm writing a program for Arduino in C++ from OOP perspective and ran into a problem: a class's method is unable to see an object defined in that class's constructor. What I attempted to accomplish is create an object (class) for housing various methods which are used to calculate and output data from a DHT11 sensor. Full code:

* DhtSensor.h
 *
 *  Created on: 2017-04-18
 *      Author: Secret
 */

#ifndef DhtSensor_h
#define DhtSensor_h

class DhtSensor {
public:
    DhtSensor(int dhtPin); //constructor
    void read();
    void printToScreen(); //a method for printing to LCD

private:
    unsigned long previousMillis; //Millis() of last reading
    const long readInterval = 3000; //How often we take readings
    float readingData[2][30]; //store current ant last values of temperature [0] and humidity [1] readings
    int readingIndex;
    bool initDone; //Bool value to check if initialization has been complete (Array full)
    float totalTemp;
    float totalHumidity;
    float avgTemp;
    float avgHumidity;
    float hic; //Heat Index

};

#endif

/*
 * DhtSensor.cpp
 *
 *  Created on: 2017-04-18
 *      Author: Secret
 */

#include "DhtSensor.h"
#include "DHT.h"
#include "Arduino.h"

DhtSensor::DhtSensor(int dhtPin){
    DHT dht(dhtPin,DHT11);
    dht.begin();
    previousMillis = 0;
    totalTemp = avgTemp = 0;
    totalHumidity = avgHumidity = 0;
    hic = 0;
    readingIndex = 0;
    initDone = false;
    for(int i = 0; i<2; i++){ //matrix init
        for(int j=0; j<30; j++){
            readingData[i][j]=0;
        }
    }
}

void DhtSensor::read(){
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= readInterval){
        readingData[0][readingIndex] = dht.readTemperature();
    }
}

The problem occurs within read() method in .cpp file. It doesn't see object dht created in the constructor. What am I missing here? Is this even a good practice to have objects within objects? Perhaps I should exclude the DHT library from DhtSensor class and create a DHT object in a main class where I'd use library's methods to send data to DhtSensor?

Upvotes: 3

Views: 2932

Answers (1)

aslad
aslad

Reputation: 120

You're declaring your 'dht' variable in the constructor, that's automatic allocation so it'll dissapear once the block is left (which is when your object in created here). You should declare your object in your class specification and then initialize it in the constructor.

Also, when working with objects within objects, use the initialization list, here's an answer that describes the pros of doing so.

Upvotes: 5

Related Questions