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
statements to construct the object, but the instance is then 'trapped' in the brackets and can't be used further in the code.
Here is what it looks like in code:
if (my_boolean){
MyClass my_object(arg1); //calling a first constructor
}
else {
MyClass my_object(arg1,arg2); //calling another constructor
}
//more code using my_object
I tried using the static
keyword without success so far. Is there a common way of conditionally using different constructors without having to redefine the constructors?
You can use a smart pointer instead of a direct instance:
In contrast to some other solutions proposed here, this will also work for bigger
if() {} else if() {}
sequences, orswitch
blocks.In case you can't use a compiler capable of the latest standard, you can use the good old
std::auto_ptr
in the exactly same manner.Good so! A
static
variable is certainly not what you want here.try the following :)
Take into account that this code will work even if the class has no default constructor.
Here is a demonstrative example
I have gotten the following output
What output have you gotten? :)
If you want to use a variable outside of a given scope, it must be declared outside that scope.
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 theif
/else
blocks and object construction to a separate function, then do something like:Or, if
arg1
andarg2
aren't global,If creating an object gets more complicated than what you've asked about here, you may wish to look into the factory pattern.