Delegation of constructors in C ++ () or {}

I read this link in Straustup with the following code:

class X { int a; public: X(int x) { if (0<x && x<=max) a=x; else throw bad_X(x); } X() :X{42} { } X(string s) :X{lexical_cast<int>(s)} { } // ... }; 

My question is about the line:

X() X{42}{}

Are there any differences between parentheses and braces?
If there is no difference, can I use curly braces in other function calls? Or is it just a matter of designer? And finally, why should we have both syntaxes? This is a bit ambiguous.

+8
c ++ constructor c ++ 11 delegation
source share
2 answers

() uses value initialization if parentheses are empty, or direct initialization if not empty.

{} uses list initialization , which means initializing the value if the curly braces are empty, or aggregate initialization if the initialized object is an aggregate.

Since your X is a simple int , there is no difference between initializing it with () or {} .

+7
source share

Initialization values ​​can be specified using brackets or curly braces.

The initialization of brackets was introduced with C ++ 11, and it is intended for "uniform initialization", which can be used for all non-static variables.

Brackets can be used in place of brackets or an equal sign and introduced to increase uniformity and reduce confusion.

This is a syntax construct only and does not lead to performance advantages or penalties.

0
source share

All Articles