AppDividend
Latest Code Tutorials

C++ Copy Constructor Tutorial | Copy Constructor in C++ Example

0

C++ Copy Constructor Tutorial | Copy Constructor in C++ Example is today’s topic. A copy constructor is the member function which initializes an object using another object of the same class. A Copy constructor is the overloaded constructor used to declare and initialize an object from another object. A Copy Constructor is the type of constructor which is used to create the copy of the already existing object of the class type.

C++ Copy Constructor Tutorial

Apart from default constructor and parameterized constructor, there is a third type of constructor named as copy constructor. A copy constructor is used when member variables of one object are initialized by the values of the member variable of another object of the same class.

A prototype of the copy constructor

class_name( const class_name & old_object );  

The old object should be passed as a reference to the argument; otherwise, there will be a chain of non-terminating calls.

Also, the copy constructor argument should be const because we don’t want the values of old objects to be modified inside the body of this constructor.

So, if we don’t want an argument passed to a function to be modified in any way, we use the const keyword.

When is copy constructor called?

  1. When a function returns the object of the class.
  2. When the object of the class is passed as an argument to a function.

 

C++ Copy Constructor Tutorial

Example of Copy Constructor

See the following code.

#include <iostream>
using namespace std;

class A
{
    int x, y;

public:
    A()
    {
        cout << "Default constructor called!";
    }
    A(int a, int b)
    {
        cout << "Parametrized Constructor called!\n";
        x = a;
        y = b;
    }
    A(const A &old)
    {
        // old is the old object being passed
        x = old.x; //This object's x to old object's x
        y = old.y;

        cout << "Copy Constructor called!\n";
    }

    void print()
    {
        cout << x << " " << y << "\n";
    }
};

int main()
{
    // Sample Code to show default constructor
    A obj(10, 20); // making a object of class A   -- >Implicit
    A obj2(obj);   // Copy Constructor called old object 'obj' is passed
    obj2.print();

    return 0;
}

See the following output.

copy constructor example

 

In the above code, two objects, namely obj and obj2, are created. First object obj is using the parameterized constructor to create it. It leads to the assignment of value 10 & 20 to the member variables of object obj. Then object obj2 is created using object obj. Object obj is passed as an argument. This leads to the assignment ‘x=old.x’ and ‘y=old.y.’

Concept of deep copy and Shallow copy

Even if we don’t define copy constructor explicitly inside the class, it will still call the default copy constructor.

Shallow Copy of Constructor in C++

In default copy constructor shallow copy occurs.

In shallow copy variables of the new object gets the values of the old object but they point to the same memory as of the old object. That is for new object new memory is not allocated; they are only made to point to the actual memory location so that it gets the same value as of the old object.

So, if we have a dynamic allocation in our program, we can’t just depend on default constructor because it does the shallow copy.

Shallow copy copies references to original objects. The compiler provides a default copy constructor.

The default copy constructor provides the shallow copy, as shown in the below example. It is the bit-wise copy of an object.

The shallow copy constructor is used when class is not dealing with any dynamically allocated memory.

Concept of deep copy and Shallow copy

 

Now, see the below code.

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

class A
{
    int x,y;
public:

     A()
     {
         cout << "Default constructor called!";
     }
     A(int a,int b)
     {
         cout << "Parametrized Constructor called!\n";
         x=a;
         y=b;
     }
     // commented part below is what being done by default that is shallow copy
     // Uncomment below function to see that it performs the same function

    /* A(const A & old )
     {
         // old is the old object being passed
         // shallow copy
        x = old.x;
        y = old.y;

        cout << "Copy Constructor called!\n";
     }
     */

     void print()
     {
         cout << x << " " << y << "\n";
     }

};

int main()
{
   // Sample Code to show default constructor
      A obj(10,20); // making a object of class A   -- >Implicit
      A obj2(obj);  // Copy Constructor called old object 'obj' is passed
      obj2.print();

    return 0;
}

Now, see the below output.

Shallow Copy Example

 

In the above code, inside the class A, there is a commented function that does what is being done by default by the compiler in the case of the shallow copy. Two objects have been created here. First one by a simple parameterized constructor.

The second use copy constructor and the first object is passed to it. Function body of copy constructor assigns new ‘x=old.x’ and new ‘y=old.y.’

Deep Copy of Constructor in C++

Deep copy is different from the shallow copy as in this, we make new memory for each variable and then assign the same value as the old value of the old object.

So if there is dynamic allocation inside the program, then we have to make our user-defined copy constructor in which allocate memory first then assign the value to it.

Deep copy allocates the separate memory for copied information.

So the source and copy are different. Any changes that made in one memory location will not affect the copy in the other location.

When we allocate the dynamic memory using pointers we need user-defined copy constructor. Both objects will point to the different memory locations.

 

Deep Copy of Constructor in C++

See the below code example.

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

class A
{
    char * s;
public:

     A()
     {
         cout << "Default constructor called!";
     }
     A(char * x)
     {
         cout << "Parametrized Constructor called!\n";
         int l = strlen(x),i;
         s = new char[l+1];
         for(i=0;i<l;i++)
            s[i] = x[i];
         s[l] = '\0';
     }
     A(const A & old )
     {
         // old is the old object being passed
         int l = strlen(old.s),i;
         s = new char[l+1];   // dynamic allocation is used.
         for(i=0;i<l;i++)      // deep copy
            s[i] = old.s[i];
         s[l]= '\0';

         cout << "Copy Constructor called!\n";
     }

     void print()
     {
         cout << s << "\n";
     }

};

int main()
{
   // Sample Code to show default constructor
      A obj("codecode"); // making a object of class A   -- >Implicit
      A obj2(obj);  // Copy Constructor called old object 'obj' is passed
      obj2.print();

    return 0;
}

See the following output.

deep copy example

 

In the code mentioned below, two objects have been created obj and obj2. The parameterized constructor just initializes the first object.

The copy constructor initializes second object obj2. In the copy constructor function, a deep copy is implemented.

First, we calculate a length of the string contained in the old object then a new char array of length one more than the length of the string of the old object. Then a loop is run to assign the new string the value of another string character by character.

Difference between copy constructor and assignment operator

The assignment operator is called when an already initialized object is assigned an already created object. In copy constructor new object is assigned already initialized object.

Class_name A,B;
Class_name C = B; // Copy Constructor called. C is new object
Class_name A = C; // Assignment operator. A is already initialized object.

Finally, C++ Copy Constructor Tutorial | Copy Constructor in C++ Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.