Passing address of a member function

J

J Solowiej

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.
 
A

Andrey Tarasevich

J said:
...
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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top