Reputation: 299
I'm wondering if the following procedure is actually doing what I intend for it to do, and convince myself of the different ways of doing it.
I have a base class called simulationEngine that has an object of type class ValuationFunction as a member that looks like this:
class SimulationEngine
{
public:
SimulationEngine(double horizon, Wrapper<valuationFunction>& theFunction_);
virtual void DoOnePath(double vol, double normvariate) = 0;
virtual SimulationEngine* clone() const = 0;
virtual double GetHorizon();
virtual Wrapper<valuationFunction> GetFunction();
protected:
double horizon;
Wrapper<valuationFunction> theFunction;
};
Then I have a third class called MCEngine which has an object of the type SimulationEngine Class as a member. In it I have functions that look like this:
void MCEngine::ValuePortfolio()
{
V = 0;
for (unsigned long i = 0; i < EngineVector.size(); ++i)
{
double placholder = 3;
EngineVector[i]->GetFunction()->valueInstrument(placholder);
V += EngineVector[i]->GetFunction()->getValue();
}
return;
}
The GetFunction() retrieves the function object while
valueInstrument(placholder)
Will modify a member of the class and
getValue()
Will retrieve that value just modified. Now my question is essentially how should my GetFunction() function look like? I think depending on how you do it you will either modify the member of the ValuationFunction class object in place (what we want to do) or get a copy of the valuationFunction that you modify and then lose when it goes out of scope (which we don't want), is that correct? So should I write it like this:
Wrapper<valuationFunction> SimulationEngine::GetFunction()
{
return theFunction;
}
Or would this be the correct way to do it:
Wrapper<valuationFunction> SimulationEngine::GetFunction()
{
return *theFunction;
}
I want to say the second approach is the correct one but I'm never really sure of myself when it comes to this stuff and would love to be able to convince myself of the difference here.
Upvotes: 0
Views: 434
Reputation: 429
I think what you are looking to do is return by reference like so:
const Wrapper<valuationFunction> & SimulationEngine::GetFunction() const
{
return theFunction;
}
Note the use of const (twice) avoids the member from being inadvertently modified. Returning by reference avoids a copy but runs the risk of being unintentionally modified when returned without the const qualifier. Hope this answers your question.
Upvotes: 1