I'm able to differentiate constructor of the class and function call operator () overload. However, still it's quite confusing to the user. So, i just wanna get some opinion, maybe from the design perspective, what's a good way to write these code. Using the following simple example which computes the payoff of a call option:
class payoff {
public:
int strike;
payoff (int k): strike(k) {} // constructor which populates the data member strike.
int operator()(int s) { return (s > strike) ? s - strike : 0; } // () overload
};
int main (){
payoff x(5);
cout << x(4) << endl; // output: 2
return 0;
}
When i do payoff x(5)
, I'm initiate a variable x of type payoff and passing 5 into the constructor. However, when i do x(4)
, i'm passing 4 as a function argument to do some calculation to get the payoff value. See the ambiguity here? the use of () doesn't seems to be very intuitive.
So I'm just start learning Function object / Functors in c++ and i'm wondering if this is the correct way of designing such a functor? thanks for answering!
Edit: just add some comments on this functor, because a call option will have a fixed 'strike', that's why i think it's appropriate to make it a data member of the class. However, the payoff of the option may vary, depends on the value of stock price 's'. So in the main program i can compute different payoff level with different stock price movement.