Computer Programming

Which class methods does the compiler generate automatically if you don't provide them explicitly?

Answer

Wiki User
04/29/2018
  • Default constructor: X()
  • Copy constructor: X(const X&)
  • Copy assignment operator: X& operator=(const X&)
  • Move constructor: X(X&&)
  • Move assignment operator: X& operator=(XX&)
  • Destructor: ~X()

By default, the compiler will generate each of these operations if a program uses it. However, if the programmer declares any constructor for a class, the default constructor for that class is not generated. If the programmer declares a copy or move operation, no copy, move or destructor is generated. If the programmer declares a destructor, no move operation is generated (a copy constructor is generated for backward compatibility).

We can also suppress generation of specific operations with the =delete pseudo-initialiser:

class X {

public:

X (const X&) =delete; // suppress the compiler-generated copy operations

X& operator=(const X&) =delete;

// ...

};

Wiki User
02/08/2015

Unless you define your own, the compiler generates a default constructor, a copy constructor, a move constructor, a copy assignment operator, a move assignment operator and a destructor.