Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > Passing address of a member function

Reply
Thread Tools

Passing address of a member function

 
 
J Solowiej
Guest
Posts: n/a
 
      11-07-2003
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.
 
Reply With Quote
 
 
 
 
Andrey Tarasevich
Guest
Posts: n/a
 
      11-07-2003
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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Passing a member function as a parameter of a member function Azdo C++ 2 03-06-2007 11:21 AM
Passing pointer to member function to different member function that then calls for_each pookiebearbottom@yahoo.com C++ 8 05-24-2005 01:50 PM
Passing a C++ object's member function to a C function expecing a function pointer! James Vanns C++ 7 01-21-2004 02:39 AM
Function pointer member variable to non-member function slide_o_mix C++ 0 10-15-2003 03:37 PM
Passing a pointer to member function as a parameter to another member function Newsgroup - Ann C++ 5 07-30-2003 02:54 AM



Advertisments