Wednesday, February 18, 2009

C++: Pointer to members

Pointer to member operators are not an everyday operators that we use but those can be useful if used in the correct way. Pointer to member operator ::* is used to declare a pointer that points to a member variable, pointer or function of a class. The operators .* and ->* are used to access it.

Following is an example of how we can use Pointer to member function (also called member function pointer).

  1 #include <iostream>
2 using namespace std;
3
4 class A{
5 public:
6 A(){
7 }
8 int Func(int a){
9 return a * 2;
10 }
11
12 };
13
14 int main(){
15 int (A::*fp)(int) = &A::Func;
16
17 A a;
18 cout << (a.*fp)(10) << endl;
19
20 return 0;
21 }
22

Following is another (almost random) example of how we can write generic classes to wrap pointer to member function to use with multiple classes.

  1 #include <iostream>
2 using namespace std;
3
4 class A{
5 public:
6 int Func1(int a){
7 return a * 2;
8 }
9
10 };
11
12 class B{
13 public:
14 int Func2(int a){
15 return a / 2;
16 }
17
18 };
19
20 template <class T>
21 class MemFnPtr
22 {
23 public:
24 MemFnPtr(int (T::*fp)(int), T &t) : m_fp(fp), m_t(t){
25 }
26 int Fn(int n)
27 {
28 return ((m_t).*(m_fp))(n);
29 }
30
31 //member vars
32 int (T::*m_fp)(int);
33 T &m_t;
34 };
35
36 int main(){
37 A a_obj;
38
39 MemFnPtr<A> fp_a(&A::Func1, a_obj);
40 cout << fp_a.Fn(10) << endl;
41
42 B b_obj;
43
44 MemFnPtr<B> fp_b(&B::Func2, b_obj);
45 cout << fp_b.Fn(10) << endl;
46
47 return 0;
48 }
49

3 comments:

Giancarlo Niccolai said...

Hello

I wanted to contact you to ask if you may be interested participating in The Falcon Programming Language. We're forming the core developers group in this days, so this is an interesting moment to be in.

I am linking here (http://falconpl.org/devel_mail.txt) the complete text of the request we are sending to 20 developers carefully selected throughout all the net.

You can contact me back through the "People at work" page on our site, clicking on my name.

Bests,
Giancarlo Niccolai.

luc said...

Time to time, I still look into your old C/C++ blog posts, to refresh my memory of some intricate stuffs. Thanx for the posts, it's really is of great help to me.

Kaisar said...

@luc: hey, thanks. That inspires me to write more :).