0 votes
by
edited by

Uniform Initialization Syntax in C++

1 Answer

0 votes
by

C++ has at least four different initialization notations, some of which overlap.

Parenthesized initialization looks like this:

std::string s("hello");

int m=int(); //default initialization

You can also use the = notation for the same purpose in certain cases:

std::string s="hello";

int x=5;

For POD aggregates, you use braces:

int arr[4]={0,1,2,3};

struct tm today={0};

Finally, constructors use member initializers:

struct S {

int x;

S(): x(0) {} };

This proliferation is a fertile source for confusion, not only among novices. Worse yet, in C++03 you can't initialize POD array members and POD arrays allocated using new[]. C++11 cleans up this mess with a uniform brace notation:

class C

{

int a;

int b;

public:

C(int i, int j);

};

C c {0,0}; //C++11 only. Equivalent to: C c(0,0);

int* a = new int[3] { 1, 2, 0 }; /C++11 only

class X {

int a[4];

public:

X() : a{1,2,3,4} {} //C++11, member array initializer

};

With respect to containers, you can say goodbye to a long list of push_back() calls. In C++11 you can initialize containers intuitively:

// C++11 container initializer

vector<string> vs={ "first", "second", "third"};

map singers =

{ {"Lady Gaga", "+1 (212) 555-7890"},

{"Beyonce Knowles", "+1 (212) 555-0987"}};

Similarly, C++11 supports in-class initialization of data members:

class C

{

int a=7; //C++11 only

public:

C();

};

Related questions

+1 vote
asked Jan 2, 2020 in C Plus Plus by GeorgeBell
+1 vote
asked Jan 2, 2020 in C Plus Plus by GeorgeBell
+1 vote
asked Jan 2, 2020 in C Plus Plus by GeorgeBell
+1 vote
asked Jan 2, 2020 in C Plus Plus by GeorgeBell
+1 vote
asked Jan 2, 2020 in C Plus Plus by GeorgeBell
+1 vote
asked Jan 2, 2020 in C Plus Plus by GeorgeBell
+1 vote
asked Jan 2, 2020 in C Plus Plus by GeorgeBell
+1 vote
asked Jan 2, 2020 in C Plus Plus by GeorgeBell
+1 vote
asked Jan 2, 2020 in C Plus Plus by GeorgeBell
0 votes
asked Jun 15, 2023 in R Basics by john ganales
...