Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: initialize vs assignment?

Tags:

c++

c++11

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";
}
like image 515
notaorb Avatar asked Jun 02 '20 20:06

notaorb


People also ask

Should my constructors use initialization lists or assignment?

Initialization lists. In fact, constructors should initialize as a rule all member objects in the initialization list.

What does it mean to initialize in C?

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.

What is the difference between initialization and instantiation?

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.

What is the difference between initialization and definition?

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.


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.

like image 197
Some programmer dude Avatar answered Oct 25 '22 03:10

Some programmer dude


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

like image 1
Abdo Mostafa Avatar answered Oct 25 '22 02:10

Abdo Mostafa