Search code examples
c++pointerscompiler-errorsdereferencepointer-to-member

Understanding Pointer-to-Member operators


I copied this program from a c++ practice book. What's going on behind the scenes?

The expected output is:

sum=30 sum=70

#include<iostream>
using namespace std;

class M
{
    int x;
    int y;
public:
    void set_xy(int a, int b)
    {
        x=a;
        y=b;
    }
    friend int sum(M m);
};

int sum (M m);
//so far so good, problem begins from here. what's happening after here?
{                               
    int M ::*px = &M ::x;
    int M ::*py = &M ::y;
    M *pm =&m;
    int s= m.*px+ pm->*py;
    return s;
}

int main()
{
    M n;
    void (M :: *pf)(int, int) = &M ::set_xy;
    (n.*pf)(10, 20);
    cout <<"sum=" << sum(n) << endl;

    M *op= &n;
    (op-> *pf)(30,40);
    cout << "sum=" << sum(n)<< endl;

    cin.ignore();
    getchar();
    return 0;
}

Solution

  • The problem is because of extra whitespace at op-> *pf:

     (op->*pf)(30,40);  // ok
    

    I think @fefe has probably said the reason in comment. ->* is a single operator, similar to .*. So, if those 2 are separated, then it will result in different syntax, which gives compiler error.