Pointer to 2 different types

C holds few secrets from me but I'm a bit sketchy on C++.

Can I declare a pointer variable to which I can assign either a pointer to a SoftwareSerial object or a vanilla Serial object on a whim, and if so, how do I declare it?

Regards - Philip

Can I declare a pointer variable to which I can assign either a pointer to a SoftwareSerial object or a vanilla Serial object on a whim, and if so, how do I declare it?

In general, this is not a good idea. Pointers should be as strongly typed as the instances pointed to.

However, if you look at base classes, HardwareSerial derives from Stream, and SoftwareSerial derives from Stream.

Since it is the Stream class' capabilities that are of interest (read(), write(), available(), print(), etc.) a pointer of type Stream can be used to point to either a HardwareSerial instance or a SoftwareSerial instance.

Thank you - that answers it completely.

I understand perfectly your reservations but in this case I think I'm justified. It was a big step forward in OS design about 40 years ago when they allowed device independence, so you could run the same program directing its output to the line printer, teleprinter, paper tape punch or mag tape as you liked. I'm old enough to remember how good it felt! Essentially that's all I want to do. So much neater than hacking it with preprocessor macros or conditional compilation.

Thanks again - Philip

I understand perfectly your reservations but in this case I think I’m justified.

If you do

Stream *strPointer = &Serial;

you are.

If you do

void *strPointer = &Serial;

you are not.

That was my point.