Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegating constructors in c++ () or {}

Tags:

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.

like image 798
Govan Avatar asked Oct 17 '15 10:10

Govan


People also ask

What are delegating constructors?

Delegating constructors. Constructors are allowed to call other constructors from the same class. This process is called delegating constructors (or constructor chaining). To have one constructor call another, simply call the constructor in the member initializer list.

What are the 3 types of constructor?

Constructors in C++ are the member functions that get invoked when an object of a class is created. There are mainly 3 types of constructors in C++, Default, Parameterized and Copy constructors.

What is constructor chaining C++?

Show activity on this post. My understanding of constructor chaining is that , when there are more than one constructors in a class (overloaded constructors) , if one of them tries to call another constructor,then this process is called CONSTRUCTOR CHAINING , which is not supported in C++ .

How do you initialize a constructor?

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.


2 Answers

() 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 {}.

like image 138
emlai Avatar answered Oct 21 '22 12:10

emlai


Initialization values can be specified with parentheses or braces.

Braces initialization was introduced with C++11 and it is meant to be "uniform initialization" that can be used for all non-static variables.

Braces can be used in the place of parentheses or the equal sign and were introduced to increase uniformity and reduce confusion.

It is only a syntactical construct and does not result in performance benefits or penalties.

like image 23
dspfnder Avatar answered Oct 21 '22 12:10

dspfnder