-1

I get a compiler error at the line func = &Fred::fa; saying:

[Error] '((Fred*)this)->Fred::func' cannot be used as a member pointer

since it is of type 'fptr {aka double (*)(int, int)}. However, I know that if I define the typedef as a class inside the class

 typedef double (Fred::*fptr)(int x, int y);

then it will not error it. But I want to be sure that the typedef is defined outside the class.

What am I doing wrong?

#include <iostream>
typedef double (*fptr)(int x, int y);
class Fred
{
private:
  //typedef double (Fred::*fptr)(int x, int y);
  fptr func;
public:
  Fred() 
  {
    func = &Fred::fa;
  }

  void run()
  {
    int foo = 10, bar = 20;
    std::cout << (this->*func)(foo,bar) << '\n';
  }

  double fa(int x, int y)
  {
    return (double)(x + y);
  }        
};

int main ()
{       
  Fred f;
  f.run();
  return 0;
}
jww
  • 97,681
  • 90
  • 411
  • 885
  • 2
    They are two different types: pointer to a function and a pointer to a class method. You can only assign a pointer to another pointer of the same exact type. This is no different than trying to assign a pointer to an `int` to a pointer to a `char`. – Sam Varshavchik Oct 13 '18 at 19:45
  • 1
    Possible duplicate of [Function pointer to member function](https://stackoverflow.com/questions/2402579/function-pointer-to-member-function) – JMAA Oct 13 '18 at 19:49
  • Hi, welcome to stackoverflow! Please do make sure you search for your problem before asking, there are several questions on the site about pointers to member functions already. Happy coding :) – JMAA Oct 13 '18 at 19:51
  • Just some incidental advice: in modern C++ `using` should be preferred over `typedef` (it's more flexible and, IMHO, syntactically clearer). – JMAA Oct 13 '18 at 19:53
  • Good reading on the topic: [Pointers to Member Functions](https://isocpp.org/wiki/faq/pointers-to-members). – user4581301 Oct 13 '18 at 20:43
  • https://isocpp.org/wiki/faq/pointers-to-members The answer was not here – narjes mashhadifarahani Oct 13 '18 at 23:02

1 Answers1

0

A function and a method are different. You cannot stuff a pointer to the method in a pointer to a function. So

typedef double (*fptr)(int x, int y);

must be

typedef double (Fred::*fptr)(int x, int y);

or you must use a wrapper that hides the differences such as std::function.

What's missing in

#include <iostream>
typedef double (Fred::*fptr)(int x, int y); // Fred unknown.
class Fred
{
    ...
}

is a forward declaration for Fred. You can't use Fred is the compiler doesn't know Fred exists.

Solution: Forward declare Fred.

#include <iostream>
class Fred;
typedef double (Fred::*fptr)(int x, int y); // Fred known enough to get pointers
class Fred
{
    ...
}

But what you really want is std::function.

user4581301
  • 33,082
  • 7
  • 33
  • 54