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
    Stream & port_;
    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 () { }


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.


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)) {

bool (*learned)(void);

void learn_anything(bool (*what)(void)) {

void do_anything() {

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

  std::cout << "\n  passing something as argument:\n";

  std::cout << "\n  learning something:\n";

  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.


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