I'm new to Arduino and C++ and I have a question about arduino (c++), class and "this" in class methods:
I create classname.cpp and classname.h In classname.cpp I try get "this" (ClassName instance) somehow (example below):
ClassName::ClassName(){}
...
void SomeCallback(char* name, uint8_t age){
// how to get "this" object (ClassName)?
}
...
void ClassName::Init(){
this->someobj->setCallback(someCallback); // callback signature <void(char*, uint8_t)>
}
In this solution I don't have the compiler error, but I can't get "that" in some callbacks
The question is: How do I modify the Init method or someCallback function to get "this" in SomeCallback?
I try put someCallback in to class like this:
ClassName::SomeCallback(char* name, uint8_t age)
Since this function is not a member of the class, there is no
thisfor it to refer to. If you had three instances of ClassName in your code, then whichthisshould it refer to?Class members use this to refer to whichever class instance they are a part of. When you create instances and use them:
for that first call to
Init,thispoints to instance1. For the second call toInitthispoints to instance 2.But in your callback method it is not a member of a class. So it doesn't get called with a class instance, so it doesn't have a
this.How you solve this problem depends on what you want the program to do. If you only will have one instance of the class, then make it a singleton. OR don't even make it a class. If you will have multiple instances then one option is to have a static list of pointers to instances and let the instances "register" themselves for callbacks by adding themselves to that list.