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
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
#include
#include
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? :)