title: Creating an instance inside an instance in Arduino
body: <p>I have a <code>TemperatureSensor</code> class that creates <code>OneWire</code> and <code>DallasTemperature</code> within itself and exposes the actual temperature. The problem is that when I create it, it doesn't work. I sense a very weird behavior related to the scope of objects created inside the <code>Attach</code> method.</p>
  <p>If I supply a <code>DallasTemperature</code> instance from outside to the <code>Attach</code> method, then all works fine. If I try to instantiate it within a class - then the sketch doesn't work, the temperature is constantly <code>-127.0C</code>.</p>
  <p>I tried instantiating the members in the constructor initialization list - same result.
  What am I doing wrong?</p>
  <pre><code>#include &lt;OneWire.h&gt;
  #include &lt;DallasTemperature.h&gt;
  
  class CTemperatureSensor {
      private:
          OneWire *ow;
          DallasTemperature *dt;
          float toF(float c);
      public:
          float Celsius;
          float Fahrenheit;
          void Attach(uint8_t SignalPin, DallasTemperature *_dt = NULL);
          void Read();
  };
  
  void CTemperatureSensor::Attach(uint8_t SignalPin, DallasTemperature *_dt) {
      if (_dt == NULL) {
          // This branch does not work: the sensor returns -127.0.
          // All other devices behave in the same way:
          // instantiating an object inside another object creates weird behavior.
          ow = &amp;OneWire(SignalPin);
          dt = &amp;DallasTemperature(ow);
      } else {
          // When OneWire and DallasTemperature are declared directly in the sketch
          // and supplied as a refence, all seems to work.
          dt = _dt;
      }
      pinMode(SignalPin, INPUT);
      Celsius = 0;
      Fahrenheit = toF(Celsius);
  }
  
  void CTemperatureSensor::Read() {
      dt-&gt;requestTemperatures(); 
      Celsius = dt-&gt;getTempCByIndex(0);
      Fahrenheit = toF(Celsius);
  }
  
  float CTemperatureSensor::toF(float c) {
      return (c * 9.0) / 5.0 + 32.0; }
  </code></pre>