Say I define, instantiate, and use an adder functor like so:
class SomeAdder {
public:
SomeAdder(int init_x): x(init_x) {}
void operator()(int num) { cout << x + num <<endl; }
private:
int x;
};
SomeAdder a = SomeAdder (3);
a(5); //Prints 8
SomeAdder b(5);
b(5); //Prints 10
The constructor and the overloaded ()
operator are both called using double parenthesis and have the same types of parameters. How would the compiler determine which function to use during the instantiations of SomeAdder
and the "function calls", as to implement the correct behavior? The answer seems like it would be obvious on the surface, but I just can't wrap my head around this thought.
Thanks for your time!
The compiler selects which overloaded function to invoke based on the best match among the function declarations in the current scope to the arguments supplied in the function call. If a suitable function is found, that function is called. "Suitable" in this context means either: An exact match was found.
Which of the following operators are overloaded for functors? Explanation: () operator is overloaded to use functor property in a C++ program because this is the only operator used for a function call.
When you call an overloaded function or operator, the compiler determines the most appropriate definition to use, by comparing the argument types you have used to call the function or operator with the parameter types specified in the definitions.
The function call operator, when overloaded, does not modify how functions are called. Rather, it modifies how the operator is to be interpreted when applied to objects of a given type.
Every time an instance of a class is created the constructor method is called. Compiler for sure can determine constructor by its name. So it will be called first and operator ()
will be second.
Your example compares constructor and member function which overloads operator()
. The compiler knows which one to call and when. It is pretty much simple:
When an object is to be constructed, the constructor is called.
The member function is invoked on an already constructed object. In your case, the member function is operator()
.
That means, they're invoked in entirely different contexts. There is no ambiguity, no confusion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With