I\'m writing a piece of code in which I\'d like to use a different constructor of a class depending on a condition. So far I\'ve used if
and else
s
If you want to use a variable outside of a given scope, it must be declared outside that scope.
void foo()
{
MyClass my_object;
if (my_boolean){
my_object = MyClass(arg1); //calling a first constructor,
//then copy or move assignment
}
else {
my_object = MyClass(arg1,arg2); //calling another constructor,
//then copy or move assignment
}
//more code using my_object
}
//Can no longer access my_object
If you want to do it this way, I suggest defining a move assignment operator if the default will not work for your purposes (or there isn't a default move assignment operator).
Also, the code where you are using my_object
may be cleaner if you move the if
/else
blocks and object construction to a separate function, then do something like:
MyClass my_object = make_object(my_boolean);
Or, if arg1
and arg2
aren't global,
MyClass my_object = make_object(my_boolean, arg1, arg2);
If creating an object gets more complicated than what you've asked about here, you may wish to look into the factory pattern.