When Does Compiler Create Default and Copy Constructors in C++?
Constructor is a special type of member function of a class that initializes objects of a class. In C++, Constructor is automatically called when an object(instance of a class) is created. There are three types of constructors in C++: Default constructor, Copy constructor, and Parameterized Constructor.
- In C++, the compiler creates a default constructor if we don’t define our own constructor. In C++, compiler created default constructor has an empty body, i.e., it doesn’t assign default values to data members. However, in Java default constructors assign default values.
- The compiler also creates a copy constructor if we don’t write our own copy constructor. Unlike the default constructor, the body of the copy constructor created by the compiler is not empty, it copies all data members of the passed object to the object which is being created.
What happens when we write only a copy constructor – does the compiler create a default constructor?
The compiler doesn’t create a default constructor if we write any constructor even if it is a copy constructor. For example, the following program doesn’t compile.
Compiler Error: no matching function for call to 'Point::Point()
What happens when we write a normal constructor and don’t write a copy constructor?
The compiler creates a copy constructor if we don’t write our own. The compiler creates it even if we have written other constructors in a class. For example, the below program works fine.
x = 10 y = 20
So, we need to write a copy constructor only when we have pointers or run-time allocation of resources like filehandle, a network connection, etc.
- When should we write our own copy constructor?
- Does C++ compiler create default constructor when we write our own?
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.