Syntax to overload () parentheses operator in C++

517 Views Asked by At

I am a newbie at C++ and was given this assignment. I have to use this header file, from which I have provided the relevant excerpt. The class name is PayoffAsianCall.

PayoffAsianCall(double strike);
virtual double operator()(std::vector<double> & spot) const;
virtual ~PayoffAsianCall(){}

I want to assign some stuff to the operator in my main file I have been using

    PayoffAsianCall &PayoffAsianCall::virtual double operator()(std::vector<double> & spot) const { do stuff here}

but this has not been working. Can someone explain to me the correct syntax please?

1

There are 1 best solutions below

2
On

It´s always hard to gain some ground for beginners and c++ isn´t that easy to tame. So here are some hints for you:

We start with your try

PayoffAsianCall &PayoffAsianCall::virtual double operator()(std::vector & spot) const { do stuff here}

First: The first thing to note is the return type, you say the return type is

PayoffAsianCall &

btw. you should really pay attention to the position of the &. In this case it means referenece and its PayoffAsianCall Reference so it should have been PayoffAsianCall& and not PayoffAsianCall &.

But anyway: in the class definition you say the return value is double so it should be double:

double PayoffAsianCall::virtual double operator()(std::vector & spot) const { do stuff here}

thats already much better. Now we need the operator name, since it is a class member the name includes the class name virtual and double have nothing to do with the name, virtual is reserved for use in the class definition itself so there is no room for it here and double is already taken care of. So we now have:

double PayoffAsianCall::operator()(std::vector & spot) const { do stuff here}

That´s all. I would recommend, as mentioned before, to correctly place the &. It´s not a std::vector reference-spot but a std::vector-reference spot:

double PayoffAsianCall::operator()(std::vector& spot) const { do stuff here}

done.