Suppose I have this class:
class foo
{
public:
foo() { }
foo(const std::string& s) : _s(s) { }
private:
std::string _s;
};
Which is a member of another class:
class bar
{
public:
bar(bool condition) :
_f(condition ? "go to string constructor" : **go to empty ctor**)
{
}
private:
foo _f;
};
When initializing _f in bar‘s member initialization list I would like to choose which constructor of foo to invoke based on condition.
What can I put instead of go to empty ctor to make this work? I thought of putting foo(), is there another way?
The result of a conditional operator is always a fixed type determined at compile time by finding a common type that both options can be converted to. (The exact rules are a little involved, but in common use it usually ‘does the right thing’.)
In your example the simplest thing to do is to let that type be a temporary
fooand then use the copy constructor to intialize_fin bar.You can do this as follows.