Passing Member Function as Parameter to Another Member Function

I want to be able to pass a function as a parameter to another function within a class.

In the example below, I want to pass 'Function_2' or 'Function_3' into 'Function_1' so that either function can be called from 'Function_1' under the formal parameter 'Function'.

In the constructor of the class, I have assigned 'name' with a pointer to 'Function_2' and would like to pass this into 'Function_1' and then call it from there (vice versa with 'Function_3') but I am having trouble understanding:

1). how the actual parameter should be passed from the constructor to 'Function_1'
2). what the formal parameter in 'Function_1' should be
3). how the function (formal parameter) can be called from 'Function_1'


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
#pragma once
#include "Errors.h"

class Demo
{
    void Function_1(some_type Function)
    {
	ClearErrors();
	Function();
	CheckErrors();
    }
	
    void Function_2(unsigned int& param_1, unsigned int& param_2)
    {
	param_1 = param_2;
    }

    void Function_3(const char* name, const char* new_name)
    {
	name = new_name;
    }
public:
    Demo()
    {
	void (Demo:: * name) (unsigned int&, unsigned int&) = &Demo::Function_2; // 'name' is a pointer to 'Function_2'
	unsigned int x{ 101 }, y{ 202 }; 
	(this->*name)(x, y); // call to 'Function_2' via 'name'
    }
};
Last edited on
You basically already have everything you need. I'm just going to apply a few transformations to your own code:

1
2
3
unsigned int x{ 101 }, y{ 202 };
void (Demo:: * name) (unsigned int&, unsigned int&) = &Demo::Function_2;
(this->*name)(x, y);


1
2
3
4
unsigned int x{ 101 }, y{ 202 };
typedef void (Demo:: * some_type) (unsigned int&, unsigned int&);
some_type name = &Demo::Function_2;
(this->*name)(x, y);


1
2
3
4
5
6
7
8
9
10
11
typedef void (Demo:: * some_type) (unsigned int&, unsigned int&);
void Function_1(some_type Function)
{
	ClearErrors();
	Function();
	CheckErrors();
}

unsigned int x{ 101 }, y{ 202 };
some_type name = &Demo::Function_2;
(this->*name)(x, y);


1
2
3
4
5
6
7
8
9
10
11
typedef void (Demo:: * some_type) (unsigned int&, unsigned int&);
void Function_1(some_type Function, unsigned int &x, unsigned int &y)
{
	ClearErrors();
	(this->*Function)(x, y);
	CheckErrors();
}

unsigned int x{ 101 }, y{ 202 };
some_type name = &Demo::Function_2;
this->Function_1(name, x, y);


1
2
3
4
5
6
7
8
9
10
typedef void (Demo:: * some_type) (unsigned int&, unsigned int&);
void Function_1(some_type Function, unsigned int &x, unsigned int &y)
{
	ClearErrors();
	(this->*Function)(x, y);
	CheckErrors();
}

unsigned int x{ 101 }, y{ 202 };
this->Function_1(&Demo::Function_2, x, y);
Thanks helios that's great!
Topic archived. No new replies allowed.