-->

Copy constructor vs Default Copy constructor vs Deficiencies of Default Copy Constructors

Copy Constructor

A copy constructor is a special constructor that's used when a new object is made and set up with the data from another object of the same class.

E.g

Class_name obj1(12);

Class_name obj2=obj1;

For example, if Ali and Khalid share the same hostel and a room object for Ali has already been created, it makes sense to initialize Khalid's room object to a copy of Ali's. In particular, suppose we have the following class to represent hostel rooms:



When we create an object and set it up with the data from another object of the same class, a special constructor called a copy constructor is automatically called by the compiler. This copy constructor copies the data from the existing object to the new one. Sometimes, we can define our own copy constructor if needed. as we will discuss below.


First, let me differentiate both user-defined and default copy constructors


In C++, when you don't define a copy constructor explicitly, the compiler generates a default copy constructor for you. The default copy constructor performs a memberwise copy of the data from one object to another, just like a user-defined copy constructor would do if you had written it explicitly.

User-defined copy constructor: You write the copy constructor explicitly in your code to define how you want the copying process to be done.

// User-defined copy constructor

  MyClass(const MyClass &other){

data=other.data//

}

user-defined copy constructor


Default Copy Constructor

By default, objects can be copied.

You can make a new object of a class by copying another object of the same class. 

If the programmer doesn't make a copy constructor for the class, the compiler automatically makes one. This default copy constructor just copies the data from one object to another using a simple assignment.




Click here to copy code
Must watch these two lectures







Deficiencies of Default Copy Constructors

Sometimes, the default copy constructor doesn't do what we want.
click to read the below code, This code makes one object, then makes another one with the same data, and finally changes something in the second object. But what's surprising is that changing the second object also changes the first one. This can cause problems and mistakes in our program.