Question

Im working my way through some C++ code and came across the following

void Classname::operator()()
{   
    //other code here
}

I assume this has something to do with overloading the constructor, but can someone elaborate on that?

Was it helpful?

Solution

operator() is the function-call operator. It allows you to use a class instance like a function:

Classname instance;
instance(); //Will call the overload of operator() that takes no parameters.

This is useful for functors and various other C++ techniques. You can essentially pass a "function object". This is just an object that has an overload of operator(). So you pass it to a function template, who then calls it like it were a function. For example, if Classname::operator()(int) is defined:

std::vector<int> someIntegers;
//Fill in list.
Classname instance;
std::for_each(someIntegers.begin(), someIntegers.end(), instance);

This will call instance's operator()(int) member for each integer in the list. You can have member variables in the instance object, so that operator()(int) can do whatever processing you require. This is more flexible than passing a raw function, since these member variables are non-global data.

OTHER TIPS

It makes your class an object called a "Functor" ... it's often used as a closure-type object in order to embed a state with the object, and then call the object as-if it were a function, but a function that has "state-ness" without the downside of globally accessible static variables like you would have with traditional C-functions that attempt to manage a "state" with internal static variables.

For instance, with

void Classname::operator()()
{   
    //other code here
}

An instance of Classname can be called like class_name_instance(), and will behave like a void function that takes no arguments.

It's not overloading the constructor -- it's overloading the function-call operator. If you define this for a class, then you can invoke an instance of the class as if it were a function. Such an object is generally called a functor.

That's the code to overload the operator '()' which basically allows you to use the class as a function with no parameters, you could also have something like:

SomeOtherClass Classname::operator ()(Argument1 a, Argument2 b, *[etc]*); and use it like:
Classname instance;
SomeOtherClass someother =  instance(arg1, arg2);

For more info on overloading you can check: Operators_in_C_and_C++

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top