Reputation: 25492
How do I call a pointer member function within a class definition? My code:
//Myclass.h
struct Booking{
int src;
int dest;
int pos;
};
class MyClass{
public:
void ExecutePlan();
private:
struct FlightPlan{
string name;
vector<Booking> bookings
};
typedef FlightPlan FP;
FP firstplan;
FP secondplan;
void FirstPlan(Booking& book);
void SecondPlan(Booking& book);
void Execute(FP& fplan, void (MyClass::*mptr)(Booking& book));
};
// Myclass.cpp
void MyClass::FirstPlan(Booking& book){
// do something with booking
}
void MyClass::SecondPlan(Booking& book){
// do something with booking
}
void MyClass::Execute(FP& fplan, void(MyClass::*mptr)(const FlightPlan& fp)){
for (int i=0; i<.fplan.bookings.size(); i++){
cout << "Executing Plan: "<< fplan.name << endl;
// Problematic line ...
mptr(bookings[i]); // <----- can't compile with this
}
}
void MyClass::Execute(){
// is this the correct design to call this member functions ???
Execute(firstplan, &MyClass::FirstPlan)
Execute(secondplan, &MyClass::SecondPlan)
}
How can i structure the Execute Function to receive a member function as a pointer?
Pls: Am a newbie in C++, maybe the design is weird!!
Paul
Upvotes: 0
Views: 343
Reputation: 254751
How to call pointer member function inside a class definition?
Unlike member names, member pointers aren't implicitly applied to this
. You have to be explicit:
(this->*mptr)(fplan.bookings[i]);
is this the correct design to call this member functions ???
Apart from a few obvious errors (such as missing ;
here and there, saying const FlightPlan&
where you mean Booking&
in the definition of Execute
), the rest of the code looks fine. Specifically
Execute(firstplan, &MyClass::FirstPlan)
Execute(secondplan, &MyClass::SecondPlan)
is the correct syntax for obtaining the member-function pointers.
Upvotes: 3
Reputation: 21003
The operator to call a member function pointer is ->*
. Since you want to call it on this
object, you need to use
(this->*mptr)(bookings[i]);
Upvotes: 1