Go Down

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

Nick Gammon

And to use it in a class:

Code: [Select]

class myMenu
  {
  private:
    Stream & port_;
  public:
    myMenu (Stream & port) : port_ (port) { }
    void begin ();
  };

void myMenu::begin ()
  {
  port_.println ("Menu initialized.");
  }

myMenu menu (Serial);

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

void loop () { }

OutOfLine


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


Thanks, that was one of my wrong assumptions, there must be some more.

OutOfLine


Code: [Select]

void displaySomething ();



Your code makes me smile: I once tried:
Code: [Select]

/*
something.cpp  Passing a function pointer to a function to do something:
*/

#include <iostream>

bool something() {
  std::cout << "\t\"Something in the way she moves...\"\n";
  return true;
}

void do_it(bool (*do_something)(void)) {
  (*do_something)();
}


bool (*learned)(void);

void learn_anything(bool (*what)(void)) {
  learned=what;
}

void do_anything() {
  (*learned)();
}

int main() {
  std::cout << "something.cpp\n";

  std::cout << "\n  passing something as argument:\n";
  do_it(&something);

  std::cout << "\n  learning something:\n";
  learn_anything(&something);
  do_anything();

  std::cout << "\n(done)\n";
  return 99; // test only ;)
}


Trying the same in a class was more difficult then I expected, though.

Nick Gammon

References have to be initialized in the constructor, as Chaul said, but it wasn't that bad.

OutOfLine


And to use it in a class:
[...]


Oh, thanks. This looks like a starting point.
I think I had tried a very similar example.

I must read up about streams, never really used them.
How do I call that for tests on a Linux text console (not Arduino)?

Go Up