Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional operator in member-initialization list

Tags:

c++

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?

like image 723
Zack Avatar asked Feb 05 '10 09:02

Zack


People also ask

What is member initialization list?

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.

What is initialization list in C++?

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.

How do you initialize a class member in C++?

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.

What is the advantage of initializer list in C++?

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.


1 Answers

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() )
like image 154
CB Bailey Avatar answered Oct 18 '22 00:10

CB Bailey