Delegating constructors in c++ () or {}

Govan picture Govan · Oct 17, 2015 · Viewed 17.9k times · Source

I read this link of Stroustrup 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}{}

Is there any differences between parentheses and curly brackets?
If there is no differences can I use curly brackets in other function calls as well? Or is it just in constructor delegation? And at last Why we should have both syntaxes? It is a little ambigous.

Answer

emlai picture emlai · Oct 17, 2015

() uses value initialization if the parentheses are empty, or direct initialization if non-empty.

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

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