Expand scope of a variable initialized in a if/else sequence

c++, scope

Solution

try the following :)

MyClass my_object = my_boolean ? MyClass(arg1) : MyClass(arg1,arg2);

Take into account that this code will work even if the class has no default constructor.

Here is a demonstrative example

#include <iostream> 
#include <cstdlib>
#include <ctime>

int main () 
{
    struct Point
    {
        Point( int x ) : x( x ) {}
        Point( int x, int y ) : x( x ), y( y ) {}
        int x = 0;
        int y = 0;
    };

    std::srand( ( unsigned )std::time( 0 ) );

    Point p = std::rand() % 2 ? Point( 1 ) : Point( 1, 2 );

    std::cout << "p.x = " << p.x << ", p.y = " << p.y << std::endl;  

    return 0; 
}

I have gotten the following output

p.x = 1, p.y = 2

What output have you gotten? :)

Problem

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?

Original source

Related problems