What is a callable object in C++?

Xegara picture Xegara · Oct 9, 2013 · Viewed 20.6k times · Source

I'm currently studying boost threads. And I came across that the thread class has a constructor that accepts callable objects. What are callable objects?

class CallableClass
{
private:
    // Number of iterations
    int m_iterations;

public:

    // Default constructor
    CallableClass()
    {
        m_iterations=10;
    }

    // Constructor with number of iterations
    CallableClass(int iterations)
    {
        m_iterations=iterations;
    }

    // Copy constructor
    CallableClass(const CallableClass& source)
    {
        m_iterations=source.m_iterations;
    }

    // Destructor
    ~CallableClass()
    {
    }

    // Assignment operator
    CallableClass& operator = (const CallableClass& source)
    {
        m_iterations=source.m_iterations;
        return *this;
    }

    // Static function called by thread
    static void StaticFunction()
    {
        for (int i=0; i < 10; i++)  // Hard-coded upper limit
        {
            cout<<i<<"Do something in parallel (Static function)."<<endl;
            boost::this_thread::yield(); // 'yield' discussed in section 18.6
        }
    }

    // Operator() called by the thread
    void operator () ()
    {
        for (int i=0; i<m_iterations; i++)
        {
            cout<<i<<" - Do something in parallel (operator() )."<<endl;
            boost::this_thread::yield(); // 'yield' discussed in section 18.6
        }
    }

};

How does this become a callable object? Is it because of the operator overloaded or the constructor or something else?

Answer

Mike Seymour picture Mike Seymour · Oct 9, 2013

A callable object is something that can be called like a function, with the syntax object() or object(args); that is, a function pointer, or an object of a class type that overloads operator().

The overload of operator() in your class makes it callable.