When Does Compiler Create Default and Copy Constructors in C++?
A 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 3 types of constructors in C++
- Default Constructor
- Copy constructor
- 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.
It is possible to pass arguments to constructors in the form of a parameterized constructor. Typically, these arguments help initialize an object when it is created. To create a parameterized constructor, add parameters to it the way you would to any other function. When you define the constructor’s body, use the parameters to initialize the object
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.
Class_name(const Class_name& object)
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 the C++ compiler create a default constructor when we write our own?