Chapter 10. Copy Constructors and Assignment Operators

Suppose you have a class MyClass that looks something like this:

class MyClass {
 public:
  // Constructors

  // Copy-constructor
  MyClass(const MyClass& that)
  : int_data_(that.int_data_),
    dbl_data_(that.dbl_data_),
    str_data_(that.str_data_) {
  }

  // Assignment operator
  MyClass& operator = (const MyClass& that) {
    if(this != &that) {
      int_data_ = that.int_data_;
      dbl_data_ = that.dbl_data_;
      str_data_ = that.str_data_;
    }
    return *this;
 }

 // Some other methods here
private:
  Int int_data_;
  Double dbl_data_;
  string str_data_;
  // Each time you add a new data member in here,
  // do not forget to add corresponding code to the
  // copy-constructor and assignment operators!
};

What is wrong with this class? It is summarized in the comment at the end of the private section. You’ll remember from the Preface that if we find ourselves saying this, we open up the code to errors and should consider alternatives. And indeed, if you don’t write a copy-constructor or assignment operator, C++ will write a “default version” for you. The default version of the copy-constructor of your class will call copy-constructors for all data members (or simply copy the built-in types), and the default version of an assignment operator will call assignment operators for each data member or simply copy the built-in types.

Because of that, the copy constructor and the assignment operator in the previous example are totally unnecessary. Even worse, they are a potential ...

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.