Passing address of a member function

Discussion in 'C++' started by J Solowiej, Nov 7, 2003.

  1. J Solowiej

    J Solowiej Guest

    Hi,

    I am wondering: is it possible to pass pointer to member function (non
    static) to initialize another class? For exmaple:

    class X {
    public:
    typedef double (*F)(double);
    X(F f) : f_(f) {}
    private:
    F f_;
    };

    class Y {
    public:
    Y() { t=1.0; X x(&Y::g);}
    private:
    double t;
    double g(double x) {
    return(x+t);
    }
    };


    int main() {
    Y y;
    return(0);
    }

    wont's compile, g++ (3.2) gives the following messages:

    In constructor `Y::Y()': no matching function for call to
    `X::X(double (Y::*)(double))' : candidates are: X::X(const X&),
    X::X(double (*)(double))

    Thanks.
    J Solowiej, Nov 7, 2003
    #1
    1. Advertising

  2. J Solowiej wrote:
    > ...
    > I am wondering: is it possible to pass pointer to member function (non
    > static) to initialize another class?


    Yes, it is possible.

    >For exmaple:
    >
    > class X {
    > public:
    > typedef double (*F)(double);
    > X(F f) : f_(f) {}
    > private:
    > F f_;
    > };
    >
    > class Y {
    > public:
    > Y() { t=1.0; X x(&Y::g);}
    > private:
    > double t;
    > double g(double x) {
    > return(x+t);
    > }
    > };
    > ...
    > wont's compile, g++ (3.2) gives the following messages:
    >
    > In constructor `Y::Y()': no matching function for call to
    > `X::X(double (Y::*)(double))' : candidates are: X::X(const X&),
    > X::X(double (*)(double))
    > ...


    A pointer of type 'pointer to member function' (that's what you are
    trying to pass) is not convertible to pointer of type 'pointer to a
    non-member function' (that's what the 'X's constructor expects). This
    causes the error.

    An example that will compile might look like this

    class Y;

    class X {
    public:
    typedef double (Y::*F)(double);
    X(F f) : f_(f) {}
    private:
    F f_;
    };

    class Y {
    public:
    Y() { t=1.0; X x(&Y::g);}
    };

    But don't know how useful it is to you because I don't know what exactly
    you are trying to do

    --
    Best regards,
    Andrey Tarasevich
    Andrey Tarasevich, Nov 7, 2003
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Newsgroup - Ann
    Replies:
    5
    Views:
    589
    John Carson
    Jul 30, 2003
  2. James Vanns
    Replies:
    7
    Views:
    7,011
    Evan Carew
    Jan 21, 2004
  3. Replies:
    8
    Views:
    544
    PJP of NYC
    May 24, 2005
  4. Azdo
    Replies:
    2
    Views:
    427
  5. Ramon F Herrera
    Replies:
    2
    Views:
    373
    Pascal J. Bourguignon
    Sep 21, 2009
Loading...

Share This Page