CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: operator()

  1. #1
    Join Date
    Jun 2002
    Posts
    1,417

    operator()

    Found your FAQ about 2d arrays -- really liked that template class. One of the comments was to suggest implemting () operator. What does that operator do?? I understand what the [] operator does, but have no clue about the () operator. Can you give me a simple example?

  2. #2
    Join Date
    Jun 2001
    Location
    Switzerland
    Posts
    4,443
    The operator () is the function call operator. A class that defines this operator is also called a "functor" because it behaves simmilary to a function. But, being a class (i.e. actually an object) it can "retain" state information from one "call" to another and much more.

    Example:
    Code:
    #include <iostream>
    
    class functor
    {
    public:
        functor(int i):i_(i){}
        void operator ()(int j){std::cout<<i_+j;}
    private:
        int i_;
    };
    
    int main()
    {
        functor f(1); // ctor; f.i_==1
        f(3); // will print 4
        return 0;
    }
    The example is a naïve one, I know. Also note that I didn't compile this code
    Gabriel, CodeGuru moderator

    Forever trusting who we are
    And nothing else matters
    - Metallica

    Learn about the advantages of std::vector.

  3. #3
    Join Date
    Apr 1999
    Posts
    27,449
    To add to Gabriels explanantion, operator() is the reason why you can pass a function pointer as well as a function object to many STL functions.

    Note that algorithms such as std::sort take a function object and a "normal" function pointer as an optional third argument. The reason why this is possible is that the syntax to call a function through a pointer is exactly the same as calling an object's operator().
    Code:
    void (*foo)(int);
    struct foo2
    {
        void operator()(int n) { }
    };
    //...
    foo(); // calls a function pointed to by foo. 
    //...
    foo2 sFoo;
    sFoo();  // calls sFoo's operator()
    Therefore when you write a template function or class, and you expect a function pointer as one of the template args, your template function will more than likely work automatically with function objects as well as function pointers.

    Regards,

    Paul McKenzie

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