I have two classes, both with the same function names that do similar things based on user input. I need to do something like this.
if (myapp.advanced == true)
class1 a;
else
class2 a;
But since a is declared from inside the if, it's not available in the next line. How do fix the above condition?
a.something();
Two ways I can think of:
1) Make class1 and class2 derive from some base class classB
, then do:
shared_ptr<classB> a;
if(myapp.advanced == true) a.reset(new class1);
else a.reset(new class2);
a->something();
2) Write a template function:
template <typename T> void do_something(T& t)
{
t.something();
}
...
if(myapp.advanced)
{
class1 a;
do_something(a);
}
else
{
class2 a;
do_something(a);
}
Note that the second approach is more suitable if you can't change class1
and class2
to add the base class. I'm also assuming that the bit inside do_something
is more complicated than just calling something()
on the object in question -- otherwise you could just call it directly!
EDIT: Just to clarify, the second approach doesn't make it available throughout the rest of the function in question -- it adds a new function in which it's available instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With