Function Pointer as a class member

P

Pramod Sharma

I am trying to call function pointer using class pointer and compiler
is not allowing it.

//===================================================
#include <stdio.h>
class TestClass
{
public:
int func1(int a) {
printf("\nTestClass:func1 a = %d\n", a);
return a;}
TestClass() { fptr = &TestClass::func1; }
int (TestClass::*fptr)(int);
};
int main()
{
TestClass* T1 = new TestClass;
int result = (T1->*fptr)(4); // compiler says undeclared identifier
delete T1;
return 0;
}



whereas at the same it works

#include <stdio.h>

class TestClass
{
public:
int func1(int a) {
printf("\nTestClass:func1 a = %d\n", a);
return a; }
TestClass() {
fptr = &TestClass::func1; }
int (TestClass::*fptr)(int);
int fptrwrapper(int a) {
(this->*fptr)(a);
return 0;}
};

int main()
{
TestClass* T1 = new TestClass;
T1->fptrwrapper(4);
delete T1;
return 0;
}

could you please point out where i am making mistake.. ???
 
D

David White

Pramod Sharma said:
I am trying to call function pointer using class pointer and compiler
is not allowing it.

//===================================================
#include <stdio.h>
class TestClass
{
public:
int func1(int a) {
printf("\nTestClass:func1 a = %d\n", a);
return a;}
TestClass() { fptr = &TestClass::func1; }
int (TestClass::*fptr)(int);
};
int main()
{
TestClass* T1 = new TestClass;
int result = (T1->*fptr)(4); // compiler says undeclared
identifier

int result = (T1->*T1->fptr)(4);
delete T1;
return 0;
}

DW
 
Y

yinquan

I think your concept is wrong. Class has a point that don't see it. It's
"this" point.You declared point to Class.You can use T1 to directly visit
func1. Don't use fptr
I wrote this progamme.I hope you understand.

#include <iostream>
#include <stdlib.h>
using namespace std;
class TestClass
{
public:
int func1(int a)
{
cout << "TestClass:func1 a ="<< a;
return a;
}
};

int main()
{
TestClass *T1=new TestClass;
int result = (T1->func1)(4); // compiler says undeclared identifier
delete T1;

system("PAUSE");
return 0;
}

This programme use STL and impelment in visual c++.net.


=========================================
 

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,770
Messages
2,569,586
Members
45,086
Latest member
ChelseaAmi

Latest Threads

Top