If you wish to talk about the exact same instance, you need to indeed use a reference or a pointer (they are fairly similar in what happens under the hood).
The choice falls to a pointer in this case, because you can only initialize a reference, but not set its value later on anymore. Since you have a setJoint
, this is clearly a reason to use a pointer.
To keep the rest of the code mostly the same, we will let setJoint
take a reference argument however, and then take its address to gain access to a pointer to the memory location that was passed by reference to the function.
When accessing members (be they data or function) of objects to which we have a pointer, there are two options: You can either dereference the pointer and then use the resulting object as you normally would, or you can use the ->
operator to do this in one step.
Putting everything together, this is the result:
// Dancer.h
class Dancer {
public:
Joint* joint;
void setJoint(Joint& newJoint);
void animate();
}
// Dancer.cpp
Dancer::setJoint(Joint& newJoint) {
joint = &newJoint;
}
Dancer::animate() {
joint->moveTo(random(90));
}
// MainArduinoSketch.ino
Joint frontLeftJoint;
void setup() {
dancer.setJoint(frontLeftJoint);
}