Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does void Classname::operator()(){ .... } do?

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?

like image 730
madmaze Avatar asked Jan 01 '26 01:01

madmaze


2 Answers

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.

like image 140
Nicol Bolas Avatar answered Jan 02 '26 15:01

Nicol Bolas


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.

like image 32
Jason Avatar answered Jan 02 '26 16:01

Jason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!