Function pointers drive me nuts ;-)

Dear experts,

I have a widget class that displays values on a dashboard. These values are generated by several other classes measuring different stuff. While configuring the widgets, I would like to store a pointer to the function that delivers the value for this widget in a member variable of the widget. When rendering, the widget calls this function using the pointer and is good to go.

That means I have to create a member variable in my widget class that is a pointer to a member function of an instance of another class. Is that even possible? This is what I have tried:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class MeasureSomething {
public:
	uint16_t get_value();
};

uint16_t MeasureSomething::get_value()
{
	return 42;
}

class Widget {
public:
	uint16_t (MeasureSomething::*get_value_ptr)();
};


void setup() {
	Serial.begin(115200);

	MeasureSomething measure_obj = MeasureSomething();
	Widget widget_obj = Widget();

	widget_obj.get_value_ptr = &MeasureSomething::get_value;

	Serial.println( (widget_obj.*get_value_ptr)() );
}


This is how it SHOULD work as far as I understand. I get a "error: 'get_value_ptr' was not declared in this scope" from the compiler.

Can somebody explain what happens here?

BTW: I ideally would like the pointer "get_value_ptr" to not be bound to one source class as it is now. But that is something to think about in a second step ;-)

Thank you!
Keith
Last edited on
 
(measure_obj.*widget_obj.get_value_ptr)()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <cstdint>

struct MeasureSomething {

	std::uint16_t get_value() const { return 42 ; }
};

struct Widget {

    // convenient type alias for pointer to member function
    using mem_fun_ptr_type = std::uint16_t (MeasureSomething::*)() const ;

    Widget( mem_fun_ptr_type mem_fun_ptr, const MeasureSomething& mst )
        : get_value_ptr(mem_fun_ptr), object(mst) {}

    std::uint16_t value() const { return (object.*get_value_ptr)() ; }

	mem_fun_ptr_type get_value_ptr ; // pointer to member function
	const MeasureSomething& object ; // object on which the member function is to be called
};


int main() {

	MeasureSomething measure_obj ;

	Widget widget_obj( &MeasureSomething::get_value, measure_obj ) ;

	std::cout << widget_obj.value() << '\n' // 42
	          << (measure_obj.*widget_obj.get_value_ptr)() << '\n' ; // 42
}

http://coliru.stacked-crooked.com/a/ea32b188a97dcb2a
I always liked this site for explaining the intricacies of function pointers.
https://www.newty.de/fpt/fpt.html

Very cool, thank you all for the quick replies! I will now try to understand them ;-)
https://www.newty.de/fpt/callback.html looks very interesting in my context.

Best regards
Keith
Topic archived. No new replies allowed.