1

I just came across some code and I believe I have never seen the syntax shown below.

struct A {
  int m_int;
  A (int a = int {}) : m_int(a) {}
};

So its clear that the constructor accepts an integer, by value, i.e. int a followed by assignment operator and type int, and empty braces & right parenthesis close. I am not able to decipher the latter part (int {}). What is meant by int a = int {}?. Please guide me to find out more about it. How do I address it?

Thank you, Gaurav

User9102d82
  • 1,172
  • 9
  • 19

2 Answers2

2

In you constructor you are defining a constructor that takes an integer and the default constructor. Remember that a constructor that provides default arguments for all of its parameters defines also the default constructor.

  • You can write it this way:

    A (int a = 0); // a is a default parameter.

In your example:

A (int a = int {});//

The parameter a is a default parameter initialized (not assigned) from a temporary integer which is value-initialized so because it is integer then it is value-initialized to 0 and then is used to initialize the parameter a. (a is a copy of it). Compiler optimize the code to remove the copy in many scenarios.

A (int a = int {5.6});// error
A (int a = int(5.6));// truncated to 5
Maestro
  • 2,512
  • 9
  • 24
1

followed by assignment operator

No. This is not an assignment operation. This is syntax for default argument. It means that you can invoke the constructor without passing the argument explicitly, in which case int {} will be passed instead. The subexpression is syntax for value initialisation of a temporary object.

eerorika
  • 232,697
  • 12
  • 197
  • 326