Function pointers in class scope: Problem!
Oct 7, 2009 at 8:05am UTC
I have a problem:
I write a class.
There is a function, member of this class.
There is another function, member of this class, takes a “function pointer” as parameter.
Inside this class there is also a third function and it calls the second function with a function pointer to first function as parameter.
Here is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
#include <iostream>
using namespace std;
class Kas {
public :
int ada;
int firstfunction (int );
void secondfunction (int (*ptofunction)(int ), int t);
void thirdfunction ();
};
void Kas::secondfunction ( int (*ptofunction)(int ),int t){
(*ptofunction)(t);
};
int Kas::firstfunction (int s) {
return ada+s;
};
void Kas::thirdfunction (){
secondfunction(firstfunction,3); //The problem is here!! Compiler Error
};
int main () {
Kas den;
den.thirdfunction();
cout<<den.ada<<"\n" ;
system("PAUSE" );
return 0;
}
how can I call the second function?
Last edited on Oct 7, 2009 at 8:08am UTC
Oct 7, 2009 at 9:46am UTC
In this situation you must pass firstfunction as a pointer to member function, not as a pointer to function. The corrected version of the code is shown below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
#include <iostream>
using namespace std;
class Kas {
public :
int ada;
int firstfunction (int );
void secondfunction (int (Kas::*ptofunction)(int ), int t);
void thirdfunction ();
};
void Kas::secondfunction ( int (Kas::*ptofunction)(int ),int t){
(this ->*ptofunction)(t);
};
int Kas::firstfunction (int s) {
return ada+s;
};
void Kas::thirdfunction (){
secondfunction(&Kas::firstfunction,3);
};
int main () {
Kas den;
den.thirdfunction();
cout<<den.ada<<"\n" ;
system("PAUSE" );
return 0;
}
Oct 7, 2009 at 9:48am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include <iostream>
using namespace std;
class Kas {
public :
int ada;
int firstfunction (int );
void secondfunction (int (Kas::*ptofunction)(int ), int );
void thirdfunction ();
};
void Kas::secondfunction ( int (Kas::*ptofunction)(int ),int t){
//(ptofunction)(t);
(*this .*ptofunction)(t);
};
int Kas::firstfunction (int s) {
return ada+s;
};
void Kas::thirdfunction (){
secondfunction(&Kas::firstfunction,3); //The problem is here!! Compiler Error
};
int main () {
Kas den;
den.thirdfunction();
cout<<den.ada<<"\n" ;
system("PAUSE" );
return 0;
}
Oct 8, 2009 at 2:26pm UTC
Thanks Abramus and Dennis. My mistake was at the 18th line.
Topic archived. No new replies allowed.