6

I googled about it, but can't find the answer. As I would guess I would have to inherit from the Print class and somehow pass to its print methods the part of my object I would like to be printed. But I am not sure how to go about it or if it is even possible.

dda
1,5951 gold badge12 silver badges17 bronze badges
asked Jun 19, 2018 at 14:25

1 Answer 1

15

There is a class called Printable. If you inherit from that, and implement the size_t printTo(Print& p) function, your object can then be passed to the print functions:

class myClass : public Printable {
 private:
 int _val1;
 int _val2;
 public:
 myClass(int v1, v2) : _val1(v1), _val2(v2) {}
 size_t printTo(Print& p) const {
 size_t r = 0;
 r += p.print("One: ");
 r += p.print(_val1);
 r += p.print(" Two: ");
 r += p.print(_val2);
 return r;
 }
};

Then:

myClass ob(4, 5);
Serial.println(ob);
=> One: 4 Two: 5
answered Jun 19, 2018 at 14:32
5
  • Majenko, thankyou very much for your answer. I got it working. Just little comment on your code. I think instead of "size_t printTo(Print& p)" should be "size_t printTo(Print& p) const". Thankyou Commented Jun 19, 2018 at 19:31
  • I just copied and pasted the prototype from the header. Commented Jun 19, 2018 at 19:38
  • I was getting an error of not overriding virtual function. Once added the const, all ok. Commented Jun 19, 2018 at 19:39
  • Ok. I have modified it for future reference Commented Jun 19, 2018 at 19:44
  • How are we supposed to know these things? The arduino documentation is quite... lacking... to say the best. Digging through the source code on github? Commented Jun 20, 2018 at 6:42

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.