Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare an object from a condition and make it available through the rest of the function?

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();
like image 200
thorvald Avatar asked Jan 21 '23 00:01

thorvald


1 Answers

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.

like image 121
Stuart Golodetz Avatar answered Jan 30 '23 00:01

Stuart Golodetz