1. Goals
Recognize when an object is created and when its existing value changes.
Choose an explicit starting value and avoid reading an uninitialized integer.
Follow independent copies of integers and a small group of related values.
2. Prerequisites
You have studied variables, types, arithmetic, and the objects/variables/memory
lesson. You can run main.cpp in C++17 mode and read output from std::cout.
This lesson does not require pointers, references, or manual memory management.
3. Explanation
Creating an object and changing its value
int count = 3; creates an integer object named count with the initial value
3. This is initialization, even though it contains =. A later line
count = 5; is assignment: the object already exists and receives a new
value. The = symbol alone does not distinguish the operations; check whether
the statement declares a variable.
For the small integer here, int count{3}; and int count = 3; both give
the starting value 3. Braces also apply rules against narrowing conversions,
explained below. You do not need to memorize every initialization form to get
started; choose an initial value that makes sense for the variable.
In int copy = count;, the current value of count initializes copy.
These are two separate integer objects. Assigning count = 5; afterward
does not automatically update copy; a copy is not a continually updated link.
A later copy = count;, however, copies the current value into the existing
copy object. Similar variable names do not create any connection between them.
What happens when you omit an initial value?
An ordinary local variable int pending; in main does not automatically
start at 0. In C++17, reading its value before assigning it causes
undefined behavior: the language gives the program no dependable result.
Do not run it and treat an accidentally printed number as a default value.
This concerns ordinary local variables; static variables follow other rules.
The C++17 draft's initialization rules
distinguish these cases.
int pending{}; does have the value 0. Initializing to zero gives a known
value, but use zero only when it fits the problem. If a price has not been
provided, zero does not automatically make it a valid price; obtain or validate
the value before using it in the calculation.
std::string name; creates a valid empty string. name.empty() returns
true, and you can assign name = "An"; later. Default initialization
depends on the type. Do not infer from std::string that every variable
without an explicit initial value is safe to read.
The C++17 string library
specifies this empty state.
Braces help catch lost information
int amount{3.5}; is invalid: converting double to int is a narrowing
conversion in list-initialization. The compiler must diagnose it.
int amount = 3.5; can compile, but keeps only 3, losing the fraction.
Even int amount{3.0}; is rejected by the same rule, despite having no
fractional part.
If you need the fraction, choose double amount{3.5};. If discarding it is
intentional, check the value's range and convert explicitly as in the types
lesson. Braces do not validate every business rule or make overflowing
arithmetic safe. See the
narrowing conversion rules.
Grouping data with struct
An order has a quantity and a unit price. The example's struct Order defines
a type with two data members, quantity and unitPrice. Defining the
type does not create an actual order. The ; after the struct's closing }
is required; Order original{2, 120}; creates an order object.
The two values inside the braces initialize the members in declaration order:
quantity receives 2, then unitPrice receives 120. A dot accesses a
member: original.quantity is that order's quantity. For this specific simple
type, Order empty{}; initializes both integers to 0.
Aggregate initialization in C++17
describes this order and members without individually supplied initializers.
Order duplicate = original; copies the two integers into a new order.
Changing duplicate.quantity does not change original.quantity. This
conclusion applies to the value-only structure here; do not infer that copying
any object duplicates every resource it might point to.
4. Runnable example
Save as main.cpp and compile with C++17. No input is needed.
#include <iostream>
#include <string>
struct Order {
int quantity;
int unitPrice;
};
int main() {
int count{3};
int copy = count;
count = 5;
int zero{};
std::string name;
Order original{2, 120};
Order duplicate = original;
duplicate.quantity = 4;
Order empty{};
std::cout << "Count: " << count << '\n';
std::cout << "Copy: " << copy << '\n';
std::cout << "Zero: " << zero << '\n';
std::cout << std::boolalpha << "Empty name: " << name.empty() << '\n';
std::cout << "Order total: " << original.quantity * original.unitPrice << '\n';
std::cout << "Copy total: " << duplicate.quantity * duplicate.unitPrice << '\n';
std::cout << "Empty order: " << empty.quantity << ", " << empty.unitPrice << '\n';
duplicate = original;
std::cout << "Assigned copy quantity: " << duplicate.quantity << '\n';
return 0;
}Exact output:
Count: 5
Copy: 3
Zero: 0
Empty name: true
Order total: 240
Copy total: 480
Empty order: 0, 0
Assigned copy quantity: 2The near-final duplicate = original; assigns to an existing order.
Both members are copied again, so the copied quantity returns to 2.
std::boolalpha only changes how bool prints, using true or false.
5. Common mistakes
Treating every
=as assignment:int copy = count;is initialization.Assuming an uninitialized local integer becomes zero or always causes a compile error.
Expecting an integer copy to update automatically when the original changes.
Writing
Order{120, 2}: it compiles but reverses the meanings of price and quantity.Writing
Order empty;without braces, then reading its uninitialized integer members.
6. Practice
Change the initial
countto8, keepingcount = 5;. Predict the first two lines:Count: 5,Copy: 8. Insertcopy = count;before printing to make both values5.Keep the original order and change
duplicate.quantity = 3;. The totals should be240and360; the final quantity is still2because of reassignment.Insert
name = "An";before printing.Empty nameshould becomefalse.In a separate scratch file, put
int amount{3.5};inmainand use it withstd::cout. Compile to inspect the narrowing error; change the type todoubleand verify that the program prints3.5.
7. Self-check
What values remain after
int a{4}; int b = a; a = 9;? Answer:ais9,bis4. Creatingbcopies the value4at that time.Why are
int value{};andstd::string text;safe to read, while an ordinary localint value;is not yet safe? Answer: the first two produce zero and an empty string under their type's rules; the last does not initialize an integer value that can be read safely.With
Order first{2, 120}; Order second = first; second.quantity = 7;, doesfirstchange? Answer: no, its quantity remains2. The two orders have separate integer members, and the assignment changes onlysecond.
Sample code
Source file
cpp98_foundation/08_initialization_assignment/main.cpp
#include <iostream>
#include <string>
struct Order {
int quantity;
int unitPrice;
};
int main() {
int count{3};
int copy = count;
count = 5;
int zero{};
std::string name;
Order original{2, 120};
Order duplicate = original;
duplicate.quantity = 4;
Order empty{};
std::cout << "Count: " << count << '\n';
std::cout << "Copy: " << copy << '\n';
std::cout << "Zero: " << zero << '\n';
std::cout << std::boolalpha << "Empty name: " << name.empty() << '\n';
std::cout << "Order total: " << original.quantity * original.unitPrice << '\n';
std::cout << "Copy total: " << duplicate.quantity * duplicate.unitPrice << '\n';
std::cout << "Empty order: " << empty.quantity << ", " << empty.unitPrice << '\n';
duplicate = original;
std::cout << "Assigned copy quantity: " << duplicate.quantity << '\n';
return 0;
}