C++: initialize vs assignment?

Viewed 1096

I'm reading Stroustrups C++ 4th Ed. Page 153 and have questions about initialization vs assignment. It's my understanding that initialization is occurs in the constructor and assignment in operator= overloaded function. Is this correct?

Also, I don't recall seeing the brackets i.e. int count {1} in his 1998 3rd Ed. book. Should I be defining variables like counters using int count {1} or int count = 1? Seems like an awkward difference from C if using the brackets.

Thanks for your guidance

void f() {
   int count {1}; // initialize count to 1
   const char∗ name {"Bjarne"}; // name is a    variable that points to a constant (§7.5) 
   count = 2; // assign 2 to count
   name = "Marian";
}
2 Answers

The curly braces is part of uniform initialization which was added with the C++11 standard.

Using

int value {1};

is equivalent to

int value = 1;

There's some differences between using curly braces and "assignment" syntax for initialization of variables, but in this simple case they're equal.

initialize means you write the variable for the first time and give it an initial value like int x=5; but assignment means that you already had a variable and you change its value like when you come later and set x=10; now you assignment number 10 at variable x

Related