Reputation: 1746
I'm trying to build an object which is of a type which depends on input parameters. E.g. my object is called 'process' and at runtime an integer between 2 and 5 (inclusive) is entered and something a bit like this would happen:
if (input == 2) TwoJ process;
if (input == 3) ThreeJ process;
if (input == 4) FourJ process;
if (input == 5) FiveJ process;
Obviously the above will not work because the object goes out of scope immediately. Is there a way to implement this nicely? Cheers
Upvotes: 1
Views: 297
Reputation: 121971
Use a factory function that returns a smart pointer to a base Process
class and whose implementation is determined by an integer value supplied to the factory function (requires that all classes have a common base).
For example:
class Base_process
{
public:
virtual ~Base_process() {}
virtual void do_something() = 0;
};
class TwoJ : public Base_process
{
public:
void do_something() {}
}
class ThreeJ : public Base_process
{
public:
void do_something() {}
}
std::unique_ptr<Base_process> make_process(int a_type)
{
if (a_type == 1) return std::unique_ptr<Base_process>(new TwoJ());
if (a_type == 2) return std::unique_ptr<Base_process>(new ThreeJ());
// Report invalid type or return an acceptable default if one exists.
throw std::invalid_argument("Unknown type:" + std::to_string(a_type));
}
Upvotes: 8
Reputation: 417
you can but, you need 1 base class for those all e.g.
Base* process;
if (input == 2) process = new TwoJ();
if (input == 3) process = new ThreeJ();
then to access those class all you need is:
if (input == 2) (TwoJ*)process->someTwoJMethod();
or by using dynamic_cast:
TwoJ* p = dynamic_cast<TwoJ*>(process);
if(p != 0) {
p->someTwoJMethod();
}
with this you own responsibility to delete your object once it's go out of scope.
The previous answers are the best way in cpp using std::unique_ptr
the object will get deleted automatically when the object go out of scope.
Upvotes: 0
Reputation: 31952
A factory method of sorts
std::unique_ptr<ProcessType> CreateProcess(int input){
if(input == 2) return std::unique_ptr<ProcessType>(new TwoJ());
.....
}
This assumes, of course, that the various classes you use have a common base class, here ProcessType
, and that you are satisfied with interacting with it via a base class pointer.
Upvotes: 2