0

I am very new to this so forgive me if I call something the wrong name. What I am trying to do is pass an instance of a class into the constructor of another class. I know these are normally done in .h and .cpp files but for the code I was running it didn't seem to care, I could be wrong however. I have taken out most of the code except the class defs and constructors.

I want to have some existing instance of Thermistor like coldtherm in my code and pass into the constructor of Tempcontroller so I can call coldtherm like what I show in the printfromthermistor function.

//Thermistor Class
    class Thermistor
{

  int Thermpin;

public:
  Thermistor(int pin)
  {
  Thermpin = pin;
  }


double TEMPOutput()
  {
  return Thermpin;
  }  
void Update()
  {

  }
};

Thermistor coldtherm(1);

//Tempcontrol Class
class TempController
{

public:

TempController(Thermistor&) //Right here I want to pass in coldtherm to the Tempcontroller and be able to call functions from that class.


void printfromthermistor()
{

  Thermistor.TEMPOutput();
}


};

1 Answer 1

3

Duplicate of this.

References can only be initialized, not changed. To use it in the constructor like you have shown means that the reference member has to be initialized in the constructor:

class TempController
{
  Thermistor & member;
public:
  TempController( Thermistor & t ) { member = t; }; // assignment not allowed
  TempController( Thermistor & t ) : member(t) { }; // initialization allowed
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.