Re: Pointers to member funtctions

From: Anthony Borla (ajborla_at_bigpond.com)
Date: 03/28/05


Date: Mon, 28 Mar 2005 21:11:45 GMT


"sss" <xxx@xxx.edu> wrote in message news:d29q59$fhb$1@news1.ucsd.edu...
>
> Consider the followning.
> int main(){
> int (*move)();
> int (*mve)(int);
> int temp();
> int temp(int);
>
> move = temp;
> move = &temp;
>
> mve = temp;
> mve = &temp;
> }
>
> The compiler does not seem to have any complaints on the
> above lines. But when I change the everything to being part
> of a class it no longer works.
>
> class xxxx{
> int (*move)();
> int (*mve)(int);
> int temp();
> int temp(int);
> xxxx();
> };
>
> xxxx::xxxx(){
> move = temp;
> move = &temp;
>
> mve = temp;
> mve = &temp;
> }
>
> Anybody know why the second approach does not
> work.
>

The approach used would work if you made each member function 'static'.
Relevant information available at:

    http://www.parashift.com/c++-faq-lite/pointers-to-members.html

Post again if more explanation is required.

I hope this helps.

Anthony Borla

P.S.

A couple of pointers:

* Generally wise to prototype functions globally, that is,
   outside of any function, including 'main'

* Generally wise to avoid using a constructor for purposes
   other than to construction / initialisation related matters; let
   it execute, then perform tasks inside another member function
   by calling it

Therefore, you may wish to alter your code to something along these lines
[untested]:

   class xxxx{
   public:
       int (*move)();
       int (*mve)(int);
       static int temp();
       static int temp(int);
       void runTest();
    };

    int temp();
    int temp(int);

    int main(){
        int (*move)();
        int (*mve)(int);

        move = temp;
        move = &temp;

        mve = temp;
        mve = &temp;

        xxxx t;
        t.runTest();
   }

    void xxxx::runTest(){
        move = xxxx::temp;
        move = &xxxx::temp;

        mve = xxxx::temp;
        mve = &xxxx::temp;
    }



Relevant Pages