Construction of objects

C++ allows you to define special methods to perform the initialization of the object. These are called constructors. In C++11, you will get three such functions generated for you by default, but you can provide your own versions if you wish. These three constructors, along with three other related functions, are as follows:

  • Default constructor: This is called to create an object with the default value.
  • Copy constructor: This is used to create a new object based on the value of an existing object.
  • Move constructor: This is used to create a new object using the data moved from an existing object.
  • Destructor: This is called to clean up the resources used by an object.
  • Copy assignment: This copies the data from one existing object into another existing object.
  • Move assignment: This moves the data from one existing object into another existing object.

The compiler-created versions of these functions will be implicitly public; however, you may decide to prevent copying or assigning by defining your own versions, and making them private, or you can delete them using the =delete syntax.

You can also provide your own constructors that will take any parameters you decide you need to initialize a new object.

A constructor is a member function that has the same name as the type, but does not return a value, so you cannot return a value if the construction fails, which potentially means that the caller will receive a partially constructed object. The only way to handle this situation is to throw an exception (explained in Chapter 7, Diagnostics and Debugging).