Function Pointer

S

santosh

class MyClass
{
private:
static int a;
float b;
char c;

public:
MyClass():b(0),c('\0'){};
static int DoMore(int p_a)
{
a=a+p_a;
cout<<"a="<<a<<endl;
return a;
}
float Increment(float p_f)
{
b+=p_f;
cout<<"b="<<b<<endl;
return b;
}
};
int main(void)
{
int (MyClass::*fn_ptr1)(int);
fn_ptr1=&MyClass::DoMore;
fn_ptr1(5);
return 0;
}

Here I am getting Compilation error.
If I write like this bellow, It is OK(working)

int main(void)
{
int (*fn_ptr1)(int);
fn_ptr1=&MyClass::DoMore;
fn_ptr1(5);
return 0;
}

Why it is so?
 
J

Jonathan Bartlett

Here I am getting Compilation error.
If I write like this bellow, It is OK(working)

Static methods are basically just normal functions with a different
scope. They are NOT real methods of an object, and therefore, the
method syntax doesn't work.

Jon
 
M

Mike Wahler

santosh said:
class MyClass
{
private:
static int a;
float b;
char c;

public:
MyClass():b(0),c('\0'){};
static int DoMore(int p_a)
{
a=a+p_a;
cout<<"a="<<a<<endl;
return a;
}
float Increment(float p_f)
{
b+=p_f;
cout<<"b="<<b<<endl;
return b;
}
};
int main(void)
{
int (MyClass::*fn_ptr1)(int);
fn_ptr1=&MyClass::DoMore;
fn_ptr1(5);
return 0;
}

Here I am getting Compilation error.
If I write like this bellow, It is OK(working)

int main(void)
{
int (*fn_ptr1)(int);
fn_ptr1=&MyClass::DoMore;
fn_ptr1(5);
return 0;
}

Why it is so?

Because 'MyClass::DoMore()' is declared 'static'.

For more information, see this section of the
C++ FAQ:
http://www.parashift.com/c++-faq-lite/pointers-to-members.html

-Mike
 

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

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,120
Latest member
ShelaWalli
Top