Search code examples
c++non-static

Clarification with accessing non-static class member function via pointer


I am having difficulty accessing a non-static member function from a function pointer and can't quite figure out my syntax issue. When attempting to compile as seen below I receive "error: fnc_ptr not declared in this scope." and when if the code is modified to not access the function it should point to it compiles and will print out 1 for bar.fn_ptr .To compile I used:

g++ -std=c++11 -Wall example.cpp foo.cpp

The split file structure/namespace is just meant to emulate the same conditions as my original issue.

example.cpp

#include "foo.h"
#include <iostream>

int main(int argc, char* argv[]){

  pizza::foo bar;
  bar.fn_ptr = &pizza::foo::fnc_one;
  std::cout << (bar.*fn_ptr)(1) << std::endl;

  return 0;
}

foo.cpp

#include <cmath>
#include "foo.h"

namespace pizza{

   double foo::fnc_one(double x){
        return pow(x,3) - x + 2;
   }
}

foo.h

namespace pizza{

   class foo{
       public:
        double (foo::*fn_ptr)(double);
        double fnc_one(double);

        foo(){
           fn_ptr = 0;
        }
   };
}

A very similar question can be found here, with additional reference here.


Solution

  • You are missing bar. when referring to fn_ptr which is an attribute of that object. Change it to:

      std::cout << (bar.*(bar.fn_ptr))(1) << std::endl;
    

    And it works.

    I also recommend reading this FAQ on the subject: https://isocpp.org/wiki/faq/pointers-to-members