Let's say I have some function:
void myFunction(void (MyClass::*function)(int), MyClass& myClass) {
(myClass.*function)(1);
}
Which is called as follows:
class MyClass {
int value;
void setValue(int value) {
this->value = value;
}
}
MyClass myClass;
myFunction(&MyClass::set_value, myClass);
This function takes the object myClass and says to call its member function setValue, which it calls with the parameter set to 1.
Before I realized C++ had support for passing member functions as as parameters, I had manually set my code to take in a object and function pointer and then determine the offset between their addresses. This offset could then be saved to call the same member function if given a different instance of the same type of object.
But yeah, then I discovered you can just do Class::*function which (I assume) does exactly what I had previously built/described.
Which leads me to my issue, let's say I have the same function as before, except I change my class structure a bit:
class MyClass {
ChildClass childClass;
}
class ChildClass {
int value;
void setValue(int value) {
this->value = value;
}
}
Is there then a way in C++ to pass the setValue function into myFunction given that setValue is now within the ChildClass object within MyClass?
The most obvious solution would be to add a setValue member function to MyClass which calls the setValue function within its childClass object, like so:
class MyClass {
ChildClass childClass;
void setValue(int value) {
this->childClass.setValue(value);
}
}
class ChildClass {
int value;
void setValue(int value) {
this->value = value;
}
}
MyClass myClass;
myFunction(&MyClass::setValue, myClass);
However, due to the semantics of the project I am working on this would not be a desirable solution. Thus, I was curious about whether or not there is a way to achieve this in C++. If not, I can certainly just implement it manually (it would be the same as before, except you would save the offset between the childClass member and MyClass as well as the offset of the setValue member and ChildClass), but naturally I'd like to know if there is a more "built-in" way of achieving this.