Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling constructor with braces

Simple question about C++11 syntaxis. There is a sample code (reduced one from source)

struct Wanderer
{
  explicit Wanderer(std::vector<std::function<void (float)>> & update_loop)
  {
    update_loop.emplace_back([this](float dt) { update(dt); });
  }
  void update(float dt);
};

int main()
{
  std::vector<std::function<void (float)>> update_loop;
  Wanderer wanderer{update_loop}; // why {} ???
}

I'd like to know, how it can be possible call constructor with curly brackets like Wanderer wanderer{update_loop}; It is neither initializer list, nor uniform initialization. What's the thing is this?

like image 309
Loom Avatar asked Mar 13 '13 20:03

Loom


People also ask

Can you call a constructor directly?

No, you cannot call a constructor from a method. The only place from which you can invoke constructors using “this()” or, “super()” is the first line of another constructor.

What do braces mean in C++?

In programming, curly braces (the { and } characters) are used in a variety of ways. In C/C++, they are used to signify the start and end of a series of statements. In the following expression, everything between the { and } are executed if the variable mouseDOWNinText is true.

What is brace initialization?

If a type has a default constructor, either implicitly or explicitly declared, you can use brace initialization with empty braces to invoke it. For example, the following class may be initialized by using both empty and non-empty brace initialization: C++ Copy.

Can I call constructor in member function?

Constructor and destructor can also be called from the member function of the class.


2 Answers

It is neither initializer list, nor uniform initialization. What's the thing is this?

Your premise is wrong. It is uniform initialization and, in Standardese terms, direct-brace-initialization.

Unless a constructor accepting an std::initializer_list is present, using braces for constructing objects is equivalent to using parentheses.

The advantage of using braces is that the syntax is immune to the Most Vexing Parse problem:

struct Y { };

struct X
{
    X(Y) { }
};

// ...

X x1(Y()); // MVP: Declares a function called x1 which returns
           // a value of type X and accepts a function that
           // takes no argument and returns a value of type Y.

X x2{Y()}; // OK, constructs an object of type X called x2 and
           // provides a default-constructed temporary object 
           // of type Y in input to X's constructor.
like image 50
Andy Prowl Avatar answered Oct 23 '22 14:10

Andy Prowl


It is just C++11 syntax. You can initialize objects calling their constructor with curly braces. You just have to bear in mind that if the type has an initializer_list constructor, that one takes precedence.

like image 24
juanchopanza Avatar answered Oct 23 '22 12:10

juanchopanza