Chapter 7. Uninitialized Variables

Various errors can occur when adding variables to complex classes and using them as arguments. This chapter shows you a simple way to avoid such errors.

Initialized Numbers (int, double, etc.)

Imagine that you have a class named MyClass with several constructors. Suppose you’ve decided to add some new data member named int_data_ to the private section of this class:

class MyClass {
 public:
  MyClass()
  : int_data_(0)
  {}

  explicit MyClass(const Apple& apple)
  : int_data_(0)
  {}

  MyClass(const string& some_text, double weight)
  : int_data_(0), some_text_(some_text)
  {}


 private:
  int int_data_;
  std::string some_text_;
};

When adding the new data member, you have a lot of work to do. Every time you add a new data member of a built-in type, do not forget to initialize it in every constructor like this: int_data_(0). But wait! If you read the Preface to this book, you probably remember that we are not supposed to say “Every time you do A, don’t forget to do B.” Indeed, this is an error-prone approach. If you forget to initialize this data member, it will most likely fill with garbage that would depend on the previous history of the computer and the application, and will create strange and hard-to-reproduce behavior. So what should we do to prevent such problems?

Before we answer this question, let’s first discuss why it’s only relevant for built-in types. Let’s take a look at the data member some_text_, which is of the type std::string. When you add a data member ...

Get Safe C++ 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.