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
- In-class initializers give
owner_andbalance_fallback values right at their declarations. Account() = defaultasks the compiler for a constructor that just uses those defaults.- The two-argument constructor overrides them via the
:initializer list, moving the string instead of copying.
Keywords and builtins used here
Accountclassconstdefaultdoubleprivatepublicreturn
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.
Step 2 of 3 in Classes & RAII, step 17 of 27 in Language basics.