Reputation: 657
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
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