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
You can use a smart pointer instead of a direct instance:
std::unique_ptr my_object;
if (my_boolean) {
//calling a first constructor
my_object.reset(new MyClass(arg1));
}
else {
//calling another constructor
my_object.reset(new MyClass(arg1,arg2));
}
//more code using my_object
In contrast to some other solutions proposed here, this will also work for bigger if() {} else if() {} sequences, or switch 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.
"I tried using the
statickeyword without success so far."
Good so! A static variable is certainly not what you want here.