Menu

Function pointers to member functions

2002-12-14
2012-09-26
  • Nobody/Anonymous

    #include <iostream>
    #include <cstdlib>

    class foo
    {
    public:
        int bar(int i){return i;}

    };

    int main(int argc, char *argv[])
    {
        int (*fnPtr)(int i);
        foo f;
        fnPtr = &foo::bar;
        cout << (*fnPtr)(3);
       
        system("PAUSE");
    }

    compiler output:
    D:\Dev-Cpp\Untitled1.cpp [Warning] In function `int main(int, char **)':
    15 D:\Dev-Cpp\Untitled1.cpp converting from `int (foo::*)(int)' to `int (*)(int)'

    i copied this code from a tutorial, it SHOULD work, how can i disable the compiler warning, or get it to work?

     
    • Nobody/Anonymous

      Ah Figured  it out.

       
    • Nobody/Anonymous

      The wraning is there for a reason... you can't have a pointer to a member function without associating it with the class the member function is in. Whatever tutorial teaches you otherwise is wrong. The correct way to do it is as follows:

      #include <iostream>
      #include <stdlib.h>

      class foo
      {
      public:
          int bar(int i) { return i; }
      };

      int main(int argc, char *argv[])
      {
          int (foo::*fnPtr)(int i);
          foo f;
          fnPtr = &foo::bar;
          cout << (f.*fnPtr)(3) << endl;
         
          system("PAUSE");
          return 0;
      }

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.