Reputation: 29
The compiler gives the error cannot instantiate abstract class due to following members:
how do I sort this?
'double PayOff::operator ()(const double &) const' : is abstract
this the abstract class
class PayOff {
public:
virtual ~PayOff() {}
virtual double operator()(const double& spot) const = 0;
virtual std::shared_ptr<PayOff> clone() const = 0;
};
derived class is
class AsianGeometric: public PayOff{
private:
double strike;
public:
AsianGeometric(const double& strike);
virtual ~AsianGeometric(){};
virtual double asianpay()(const std::vector<double>& spot_prices) const;
virtual std::shared_ptr<PayOff> clone()const;
};
AsianGeometric::AsianGeometric(const double& strike){
this-> strike = strike;
}
double AsianGeometric::asianpay(const std::vector<double>& spot_prices) const{
unsigned num_times = spot_prices.size();
double log_sum = 0.0;
for (unsigned int i=0; i<spot_prices.size(); i++){
log_sum += log(spot_prices[i]);
}
double geom_mean = exp(log_sum/static_cast<double>(num_times));
if (geom_mean > strike) return geom_mean - strike;
else return 0;
}
std::shared_ptr<PayOff> AsianGeometric::clone()const{
return std::shared_ptr<PayOff>(new AsianGeometric(*this));
}
Upvotes: 0
Views: 317
Reputation: 20383
To instantiate the derived class AsianGeometric
, it needs some implementation of the following all the pure virtual functions in the base class.
virtual double operator()(const double& spot) const = 0;
virtual std::shared_ptr<PayOff> clone() const = 0;
That is, something like the following.
class AsianGeometric: public PayOff{
private:
double strike;
public:
AsianGeometric(const double& strike);
virtual ~AsianGeometric(){};
virtual double operator()(const double& spot) const {
// put implementation here
}
virtual std::shared_ptr<PayOff> clone() const {
// put implementation here
}
Note that the implementation may be put inline in the class body or offline, it does not matter, the important point is that the method signatures must exactly match.
In addition, in C++11, as a good designer, you can use the override
keyword to indicate the compiler that your intention is to override. That way, if the signature of the derived method has any difference with the signature of the base class, then the compiler would flag it as an error.
That is,
virtual double operator()(const double& spot) const ovrerride;
^^^^^^^^^
Upvotes: 1
Reputation: 81926
You are aware that:
virtual double operator()(const std::vector<double>& spot_prices) const;
Does not override:
virtual double operator()(const double& spot) const = 0;
Right?
Upvotes: 5