Can someone please explain?

In this Code:

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
33
34
35
36
37
38
39
#include <iostream>
using namespace std;
class Data
{
private:
   int y;
   static int x;

public:
   void SetData(int value) {y = value; return;};
   int GetData() {return y;};
   static void SSetData(int value) {x = value; return;};
   static int SGetData() {return x;};
};

int Data::x = 0;

void main(void)
{
   Data mydata, mydata2;

   // Initialize pointer.
   void (Data::*pmfnP)(int) = &Data::SetData; // mydata.SetData;

   // Initialize static pointer.
   void (*psfnP)(int) = &Data::SSetData;

   mydata.SetData(5); // Set initial value for private data.
   cout << "mydata.data = " << mydata.GetData() << endl;

   (mydata.*pmfnP)(20); // Call member function through pointer.
   cout << "mydata.data = " << mydata.GetData() << endl;

   (mydata2.*pmfnP)(10) ; // Call member function through pointer.
   cout << "mydata2.data = " << mydata2.GetData() << endl;

   (*psfnP)(30) ; // Call static member function through pointer.
   cout << "static data = " << Data::SGetData() << endl ;
}


On line 23 why is the scope resolution used in void (Data::*pmfnP)(int)

and &Data::SetData;

and on line 26

&Data::SSetData;

I am really confused? and what does the .* operator do? I found this code somewhere else out of my book so can someone please explain? Thanks!

And also pmfnP isnt even defined in the class so what does Data::*pmfnP)(int) do?
Last edited on
It is a pointer to a member function.
I know but I am confused on the use of ::
and why you need Data:: in Data::*pmfnp) (int)
¿How will you say that it is a pointer to member function of `Data' then?
Yes, the syntax is awful.

Remember the equivalence
1
2
void foo::bar(baz);
void bar(foo *this, baz);
Last edited on
Can you reference me to a documentation or something more detailed please?
So the :: just tells the compiler that it is a function pointer to that class? So I cant assign it to anything else other then a function of that class?
Yes

It would be the same as
1
2
3
4
void (*function)(int); //function pointer, receives int returns nothing
void foo(std::string);

function = &foo; //illegal 
Last edited on
Oh awesome :D thanks
Topic archived. No new replies allowed.