ninazzo
ninazzo

Reputation: 657

C++ How can I call one constructor or the other depending on the parameters passed as input?

I have these two constructors:

MyClass(char* path);
MyClass(int n);

and I need to call the first if the user has passed the path as an argument, the other otherwise.

My problem is that I don't know how to do this since I can't define the class without initialising it first, nor can I define a reference and then create the class into an if-else block like this:

MyClass& c;
if (argc == n) // path passed
{
    c = MyClass(argv[n-1]);
}
else {
    c = MyClass(10);
}

Upvotes: 0

Views: 63

Answers (1)

cdhowie
cdhowie

Reputation: 169028

You can use a ternary expression. (Before C++17, this requires that your class is copyable or movable.)

MyClass c = argc == n ? MyClass(argv[n-1]) : MyClass(10);

Upvotes: 6

Related Questions