C ++: abstract class as a member

I have a question about style. I have a class (in my case, Option), which depends on the value of the exogenous object (Interest rate). My goal is to create an abstract base class for an exogenous object (Rate) so that I can create variations like SimulatedRate or ConstantRate that will work inside my Dependent Option class.

However, I am in C ++, since I obviously cannot create an abstract base class, I must store either a pointer or a reference to the base class. I am concerned that when instances of exogenous objects go beyond the bounds of the dependent class, my dependent class will point to undesirable ones.

Is there a reasonable way to use polymorphism for this problem in C ++?

My current code is:

class Dependent 
{
public:
    Dependent(const Exogenous& exo) : exo_(exo) {}
    double getSomething() const { exo_.interfaceMethod(); }
private:
    Exogenous& exo_;
}

class Exogenous
{
public:
    virtual double interfaceMethod() const=0;
}

class ExogenousVariationA
{
public:
    virtual double interfaceMethod() const { return resultA; }
}

class ExogenousVariationB
{
public:
    virtual double interfaceMethod() const { return resultB; }
}
+5
2

sftrabbit , :

  • virtual clone() ( - - ); , , ; , , (, ).
  • , , , std/boost ... , "" ( 't include you)

ExogenousVariationA ~ B Exogenous, , , virtual. :

class Exogenous
{
public:
    virtual double interfaceMethod() const=0;
}

class ExogenousVariationA : public Exogenous
{
public:
    double interfaceMethod() const { return resultA; }
}
+3

. , , , , . . , , . delete , , .

, - . - . std::unique_ptr std::shared_ptr. , , . , std::unique_ptr, Dependent :

class Dependent 
{
public:
    Dependent(std::unique_ptr<Exogenous> exo) : exo_(std::move(exo)) {}
    double getSomething() const { exo_->interfaceMethod(); }
private:
    std::unique_ptr<Exogenous> exo_;
}

:

std::unique_ptr<Exogenous> ptr(new ExogenousVariationA());
Dependent dep(std::move(ptr));

, std::unique_ptr, . , std::unique_ptr ( , Dependent , ).

, std::shared_ptr, , std::shared_ptr.

+4

All Articles