typestar

Constructors & member init in C++

Members initialize before the constructor body ever runs: the initializer list is the real assignment.

#include <string>

class Account {
  public:
    Account() = default;  // keeps the in-class defaults below
    Account(std::string owner, double opening)
        : owner_(std::move(owner)), balance_(opening) {}
    const std::string& owner() const { return owner_; }
    double balance() const { return balance_; }

  private:
    std::string owner_ = "unclaimed";
    double balance_ = 0.0;
};

How it works

  1. In-class initializers give owner_ and balance_ fallback values right at their declarations.
  2. Account() = default asks the compiler for a constructor that just uses those defaults.
  3. The two-argument constructor overrides them via the : initializer list, moving the string instead of copying.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
359
Tokens
88
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 70 seconds.

Type this snippet

Step 2 of 3 in Classes & RAII, step 17 of 27 in Language basics.

← Previous Next →