CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Apr 2002
    Location
    Mumbai,India
    Posts
    567

    Question function pointer

    Dear Gurus
    i have come across a term function pointer what it is and how to use it
    Thanks in advance
    Vishal

  2. #2
    Join Date
    Jun 2002
    Location
    Germany
    Posts
    1,557
    VNS,

    A function pointer is a pointer to a statically defined function, where the function has a physical address. It is relatively simple to create a data-type for function pointers and to use such data-types in simple operations. There are many uses for function pointers and it is possible to have all kinds of function pointers for functions with other return values and input parameters.

    Look at the simple sample below which defines a function pointer to void f(void).

    Code:
    #include <iostream>
    
    // Function pointer: This is a pointer to a void function taking void.
    typedef void (*PFN)(void);
    
    void test(void)
    {
      ::std::cout << "Hello World!" << ::std::endl;
    }
    
    int main(int argc, char* argv[])
    {
      // Use of a function pointer
      PFN pfn = test;
    
      pfn();
    
      return 1;
    }
    You're gonna go blind staring into that box all day.

  3. #3
    Join Date
    Oct 2002
    Location
    Singapore
    Posts
    3,128
    In addition to that, it also works for public member function within a class.

    Code:
    in .h file
    class MyClass;
    typedef void (MYClass::*memFunc)() const;
    
    class MyClass
    {
    public:
        void foo() const;
        void bar() const;
        void display(int n);
        static memFunc func[];
    }
    
    
    in .cpp file
    memFunc MyClass::func[] = {MyClass::foo, MyClass::bar};
    
    void MyClass::foo() const
    {
        cout << "in foo" << endl;
    }
    
    void MyClass::bar() const
    {
        cout << "in bar" << endl;
    }
    
    
    int main()
    {
        MyClass a;
        (a.*MyClass::func[0])();   // Call foo
        (a.*MyClass::func[1])();   // Call bar
        return 0;
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured