Go Down

Topic: Passing I/O functions to a class. (Read 1 time) previous topic - next topic

Chaul

Yes, or you can just pass the object via reference to a class function. The & marks reference. You have the class already instantiated and you just write the function definition like this:
Execute(MyClass & rClass);

OutOfLine


Pass it by reference. In all that post you didn't have much code. Post a minimal sketch that demonstrates what you are trying to do, even if it doesn't compile.


Yes, only problem that I have tried too many approaches and they have all grown beyond 'minimal',
and need cleaning up (too much #ifdef magic and debugging code inside).

I have the code in git, so could start from any one of some quite different trial implementations.
But I'm not decided on what version to base discussion on.
That's why I ask for the right c++ approach first ;)

Did I get that right, you suggest that I'd pass a reference to (let's say) Serial I/O functions from the sketch to the Menu constructor or some Menu.init() function?  I would call Serial.init() from setup(), right?

Or did you mean to pass a reference to a class (let's say Serial)?  I have never heard of pointers/references to a class before, btw.

Nick Gammon

Serial isn't a class. It's an instance of a class and you can pass a reference to it.

Nick Gammon

Example:

Code: [Select]

void displaySomething (HardwareSerial & whichPort)
  {
  whichPort.println ("Hello world."); 
  }

void setup ()
  {
  Serial.begin (115200);
  displaySomething (Serial);
  }  // end of setup

void loop () { }

Nick Gammon

Or even, to be fancier:

Code: [Select]

void displaySomething (Stream & whichPort)
  {
  whichPort.println ("Hello world."); 
  }

void setup ()
  {
  Serial.begin (115200);
  displaySomething (Serial);
  }  // end of setup

void loop () { }

Go Up