liveBook · Manning

Zero value

As explained in 100 C++ Mistakes and How to Avoid Them

A zero value is the type-dependent zero-initialized value assigned to an object or variable by a relevant initialization operation.

A zero value is the type-dependent value assigned during a relevant initialization operation. In C++, a compiler-generated default constructor can initialize instance variables to their type’s zero value, but the constructor is not called in every variable-definition form. An uninitialized value may instead contain unpredictable data and produce undefined behavior. section 7.3

Use zero values carefully when maintaining object state:

  • Initialize every instance variable when the class invariant requires a valid state. section 7.3
  • Represent an absent exclusive resource with a clear, detectable zero or invalid value. section 8.6
  • Use nullptr rather than NULL for pointer zero values in modern C++. section 8.6
  • Do not choose zero when zero is a legitimate value; select another representation that preserves the invariant. section 8.6

The initialization form changes the result

Given `Person { int age; std::string name; };`, `Person p1;` can leave `age` indeterminate, while `Person p2 = Person();` value-initializes the object and supplies type-dependent zero values. A safer design requires constructor arguments or provides an explicit constructor such as `Person() : name("Joey"), age(21) {}` when those values satisfy the invariant. section 7.3

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains initialization forms, undefined behavior, class invariants, and sentinel selection, but does not formalize language-standard rules.
Examples
Demonstrates Person initialization, explicit member constructors, invalid ages, and resetting pointers or value resources after transfer.
What it assumes
Assumes basic C++ objects and constructors while teaching initialization differences and class-invariant validation from concrete examples.
What you can do after
Diagnose uninitialized members and choose zero or invalid values that preserve class invariants during resource transfer.
How it connects
Connects zero values with default constructors, initialization semantics, undefined behavior, class invariants, and resource ownership.

Also explained in

Compare how 5 books explain zero value →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.