Reputation: 1746
I have 2 questions in my journey to understanding functors in C++.
I was reading the answer to this question and looked at the example and couldn't see the difference between functors and constructors with the exception of a having a return type.
Would the functor's state and behavior be replicated with just the combination of a constructor and an instance method? The instance method would have a return type. The example already has a constructor hence the functor doesn't add much. Isn't the functor also an instance method?
Wouldn't you just need auto
to make it confusing to figure out if you are dealing with a function or constructor?
add_x add42(42);
// somewhere deeper in the code
auto X = add42(8);
Upvotes: 0
Views: 512
Reputation: 238361
A functor is an object, with an overloaded call operator.
Constructor is a function that cannot be called directly. The compiler will generate a call to a constructor when an (non trivial) object is created.
add_x add42(42);
This is syntax for direct initialisation. add_x
is a type, add42
is the name of a variable, and 42
is the parameter list to the constructor.
auto X = add42(8);
Because we know that add42
is a variable, we know that X
is initialised with the result of the invokation of the function call operator.
If add42
was a type instead of an object, this could potentially instead be initialisation of that type.
Yes, the syntax of the call operator and the syntax of initialisation are the same. The context determines which is being used.
Upvotes: 2