In C++, compiler creates a default constructor if we don’t define our own constructor (See this). Compiler created default constructor has empty body, i.e., it doesn’t assign default values to data members (In java, default constructors assign default values).
Compiler also creates a copy constructor if we don’t write our own copy constructor. Unlike default constructor, body of copy constructor created by compiler is not empty, it copies all data members of passed object to the object which is being created.
What happens when we write only a copy constructor – does compiler create default constructor?
Compiler doesn’t create a default constructor if we write any constructor even if it is copy constructor. For example, the following program doesn’t compile.
COMPILER ERROR: no matching function for call to 'Point::Point()
What about reverse – what happens when we write a normal constructor and don’t write a copy constructor?
Reverse is not true. Compiler creates a copy constructor if we don’t write our own. Compiler creates it even if we have written other constructors in class. For example, the below program works fine.
x = 10 y = 20
So we need to write copy constructor only when we have pointers or run time allocation of resource like file handle, a network connection, etc (See this)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
This article is attributed to GeeksforGeeks.org