Click to See Complete Forum and Search --> : Selecting a child class problem


danielsbrewer
July 17th, 2004, 09:07 AM
Hi,

I have an abstract class called Integrator and two child classes, EmbedRK and Rungekutta. In my main.cc what I want to do is define a variable rk as the type that I want to use (either EmbedRK and Rungekutta) depending on a config file. I have the following:


const string integrator_type = config.read<string>( "Integrator" );
cout << integrator_type << endl;
if ( integrator_type == "embedrk" )
{
cout << "Integrator: Adaptive step RungeKutta" << endl;
const double startstep = config.read<double>( "StartStep" );
cout << startstep << endl;
EmbedRK rk(equation, startstep, tolerance);
}
else if ( integrator_type == "rungekutta" )
{
cout << "Integrator: RungeKutta" << endl;
Rungekutta rk(equation, tolerance);
}
else
{
cout << "Integrator not recognised .. exiting" << endl;
exit(1);
}


The problem is that when I compile it, it complains when I use rk that 'rk' is not defined. I use it like this:

Model model_2(rk,equation);

where in this case the function is declared as follows:

Model(const Integrator &, Equations *);


Any help to sort this out would be great.

Daniel Brewer

kuphryn
July 17th, 2004, 09:49 AM
One solution is RTTI. Pass the base case in the first parameter of model_2().

Kuphryn

Graham
July 17th, 2004, 11:40 AM
Your problem is that you are declaring "rk" inside a block statement. That means it immediately goes out of scope at the end of that block. Your only real solution is to use a pointer:

const string integrator_type = config.read<string>( "Integrator" );
cout << integrator_type << endl;

Integrator* rk;

if ( integrator_type == "embedrk" )
{
cout << "Integrator: Adaptive step RungeKutta" << endl;
const double startstep = config.read<double>( "StartStep" );
cout << startstep << endl;
rk = new EmbedRK(equation, startstep, tolerance);
}
else if ( integrator_type == "rungekutta" )
{
cout << "Integrator: RungeKutta" << endl;
rk = new Rungekutta(equation, tolerance);
}
else
{
cout << "Integrator not recognised .. exiting" << endl;
exit(1);
}

Model model2(*rk, equation);