classes
class Scanner {
public:
explicit Scanner(std::string name) : name_(std::move(name)) {}
virtual ~Scanner() = default;
virtual std::string describe() const { return name_; }
protected:
std::string name_;
};
constructor
Initialize members in the initializer list
explicit stops accidental implicit conversions
A constructor should leave the object valid, not half built
Access
public is the interface
private is the implementation
protected exists for inheritance and is often a smell outside class hierarchies
const
Mark methods const when they do not modify the object
A const correct class is easier to reason about in a larger system
Invariants
Decide what must always be true about an object Enforce it in the constructor Do not rely on callers to keep your invariants
Rule of zero
Prefer types that need no custom destructor, copy, or move Standard library members already do the work Ownership chapters come later
Next
Inheritance in 06 inheritance
Posted