The function takes as a parameter a pointer to a member function of the base class. How to call this function, passing it the necessary pointer to the corresponding member function?

Example:

void MyClass::func(void(*fptr)()){ for(size_t i = 0; i < items.size(); i++){ for(size_t q=0; q<nit.size();q++){ (items[i]->*nit[q])(); } } } void MyClass::fill1(){ func(void(*fill)()); } void MyClass::delete1(){ func(void(*delete)()); } 

The fact that heder:

  typedef void (Base::*fptr)(); std::vector<fptr> nit; MyClass(){ fptr delete=&Base::delete; fptr fill=&Base::fill; nit.push_back(delete); nit.push_back(fill); } 

The compiler throws the following error: invalid use of member function (did you forget the "()"?) Func (void (* delete) ()); func (void (* fill) ());

  • Uh ... Your func doesn't use the argument passed at all, this time. And secondly, in the definition of func fptr is not a typedef type, but a local variable name. What should func actually do? - VladD
  • @VladD For each of the objects of the child classes in the items vector, it should call the corresponding virtual function from the base class. - ascot
  • OK, does this mean that the double loop in func not needed? - VladD
  • @VladD You are right, you only need to call this function when passing a specific pointer. - ascot

1 answer 1

Apparently, you need to rewrite the functions like this:

 void MyClass::func(fptr f) { for (size_t i = 0; i < items.size(); i++) { (items[i]->*f)(); } } void MyClass::fill1() { func(&Base::fill); } void MyClass::delete1() { func(&Base::delete); } 

However, since delete is a keyword, I think it will not compile either, and it’s worth renaming the delete function to something else.

  • It works, many thanks for the help! - ascot
  • @ascot: No thanks, no success in learning the language! - VladD