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?
Member initializer list is the place where non-default initialization of these objects can be specified. For bases and non-static data members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified.
Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.
There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.
The most common benefit of doing this is improved performance. If the expression whatever is the same type as member variable x_, the result of the whatever expression is constructed directly inside x_ — the compiler does not make a separate copy of the object.
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 foo
and then use the copy constructor to intialize _f
in bar.
You can do this as follows.
_f( condition ? foo("string") : foo() )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With