Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

When Does Compiler Create Default and Copy Constructors in C++?

  • Difficulty Level : Medium
  • Last Updated : 06 Jan, 2022

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. 

CPP




// CPP Program to demonstrate what
// happens when we write
// only a copy constructor
#include <iostream>
using namespace std;
  
class Point {
    int x, y;
  
public:
    Point(const Point& p)
    {
        x = p.x;
        y = p.y;
    }
};
  
int main()
{
    Point p1;
    // Compiler Error
    Point p2 = p1;
    return 0;
}

Output:

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. 

CPP




// CPP Program to demonstrate what happens when we write a
// normal constructor and don't write a copy constructor
#include <iostream>
using namespace std;
  
class Point {
    int x, y;
  
public:
    Point(int i, int j)
    {
        x = 10;
        y = 20;
    }
    int getX() { return x; }
    int getY() { return y; }
};
  
int main()
{
    Point p1(10, 20);
    Point p2 = p1; // This compiles fine
    cout << "x = " << p2.getX() << " y = " << p2.getY();
    return 0;
}
Output
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.

Must Read:

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!