Systems CourseC/C++ · Linux · Memory
C++ CoreLesson 11 of 441 min read6 questions

Constructors

Special member that sets up a valid object; watch the free default and init lists.

Test yourself ↓

Concept core idea Watch out easy to get wrong

Concept

Key concepts

  1. Special member, same name as class, no return type, runs automatically on creation; job = valid initial state / acquire resources / enforce invariants.
  2. Compiler supplies a free default (no-arg) ctor ONLY if you write zero ctors. Write any ctor → free default is gone unless you add Entity() = default;.
  3. Member initializer list (: m_X(0)) inits before the body; required for const members, references, and member objects with no default ctor.
  4. Most vexing parse: Entity e; = object, but Entity e(); = a function declaration.
Watch out

Easily confused

init list vs assignment in body
The init list constructs members directly (once). Assigning in the body default-constructs first, then reassigns — wasteful, and impossible for const/reference members.
Entity e; vs Entity e();
Entity e; creates an object. Entity e(); DECLARES a function returning Entity (the 'most vexing parse'). Use {} to be safe.

Test yourself

6 questions on this lesson. Write your answers from memory, then compare them with the model answers side by side.