Initializers
An object that is initialized gets the specified value at the moment it is created. The values used to initialize a variable can be arbitrarily complicated expressions. When a definition defines two or more variables, the name of each object becomes visible immediately. Thus, it is possible to initialize a variable to the value of one defined earlier in the same definition.
- // ok: price is defined and initialized before it is used to initialize discount
- double price = 109.99, discount = price * 0.16;
- // ok: call applyDiscount and use the return value to initialize salePrice
- double salePrice = applyDiscount(price, discount);
Initialization in C++(www.cppentry.com) is a surprisingly complicated topic and one we will return to again and again. Many programmers are confused by the use of the = symbol to initialize a variable. It is tempting to think of initialization as a form of assignment, but initialization and assignment are different operations in C++(www.cppentry.com). This concept is particularly confusing because in many languages the distinction is irrelevant and can be ignored. Moreover, even in C++(www.cppentry.com) the distinction often doesn’t matter. Nonetheless, it is a crucial concept and one we will reiterate throughout the text.
Initialization is not assignment. Initialization happens when a variable is given a value when it is created. Assignment obliterates an object’s current value and replaces that value with a new one.