By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,820 Members | 1,189 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,820 IT Pros & Developers. It's quick & easy.

Passing address of a member function

P: n/a
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.
Jul 19 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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

Jul 19 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.