48. Prefer initialization to assignment in constructors

Summary

Set once, use everywhere: In constructors, using initialization instead of assignment to set member variables prevents needless run-time work and takes the same amount of typing.

Discussion

Constructors generate initialization code under the covers. Consider:

image

In reality, constructor’s code is generated as if you wrote:

A() : s1_(), s2_() { s1_ = "Hello, "; s2_ = "world"; }

That is, the objects not explicitly initialized by you are automatically initialized using their default constructors, and then assigned to using their assignment operators. Most often, the assignment operator ...

Get C++ Coding Standards: 101 Rules, Guidelines, and Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.