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";
}
Initialization lists. In fact, constructors should initialize as a rule all member objects in the initialization list.
In computer programming, initialization (or initialisation) is the assignment of an initial value for a data object or variable. The manner in which initialization is performed depends on the programming language, as well as the type, storage class, etc., of an object to be initialized.
Initialization means assigning initial value to variables while declaring. Following is the simple example of initialization in application. Instantiation means defining or creating new object for class to access all properties like methods, operators, fields, etc.
For a variable, a definition is a declaration which allocates storage for that variable. Initialization is the specification of the initial value to be stored in an object, which is not necessarily the same as the first time you explicitly assign a value to it.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With