I found that some code won’t work unless declared on the header file itself. For instance, with the following code, “Hello World” will be printed when test() is called:
//Myclass.h
class Myclass {
private:
SoftwareSerial *ss;
public:
void test() {
ss = & SoftwareSerial(0,1);
ss->begin(9600);
ss->print("Hello World");;
};
};
But if I just declare the method test() on the header and code it on a separate cpp as usual, with the exact same code, it compiles but doesn’t output anything:
//Myclass.cpp
void Myclass::test(){
ss = & SoftwareSerial(0,1);
ss->begin(9600);
ss->print("Hello World");
};
//this won't output anything
Why is that?
SoftwareSerialis a type. You’re taking a pointer to a temporary, then dereferencing it after the temporary has died. This is illegal; I don’t know why your compiler is accepting it, but I’m going to go out on a limb and suggest that this doesn’t mean it’s doing what you think it is. It’s probably mangling something and causing odd behaviours that would be folly to attempt to rationalise about.Instead: