What is a copy constructor

A copy constructor is a special type of constructor which creates a new object as a copy of an existing object. An analog to understand copy constructors could be the scenario of creating T shirts. For example, if you wanted to create a new t shirt with a black colour and but change the logo on the shirt, you could copy another T-shirt of the same colour.

Three major things which copy constructors are applied are in

  • Initialize one object from another of the same type
  • Copy an object to return it from a function
  • Copy an object to pass it as an argument to a function

The sample copy constructor code below will show the three example above

</pre>
<pre>//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
// Copy constructor example code
//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
#include <iostream>
using namespace std;
class MyClass
{
int val, copynumber;

public:
MyClass(int i); // Normal constructor
MyClass(const MyClass &o); // Copy constructor
~MyClass(); // Destructor
int getval() { return val; }
void setval(int i) { val = i; }

MyClass twice(); // Return an object
};
//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
// Normal constructor
//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
MyClass::MyClass(int i)
{
val = i;
copynumber = 0;
cout << "Inside normal constructor\n";
}

//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
// Copy constructor
//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
MyClass::MyClass(const MyClass &o)
{
val = o.val;
copynumber = o.copynumber + 1;
cout << "Inside copy constructor.\n";
}

//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
// Destructor
//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
MyClass::~MyClass()
{
if(copynumber == 0)
cout << "Destructing original.\n";
else
cout << "Destructing copy " << copynumber << "\n";
}

//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
// Member that will return an object
//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
MyClass MyClass::twice()
{
MyClass d(val * 2);
return d;
}

//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
// pass object by reference
//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
void display(MyClass &ob) // no copy made
{
cout << ob.getval() << '\n';
}

//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
// pass object by value
//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
void change(MyClass ob) // copy created here
{
ob.setval(100); // no effect
cout << "val in change(): ";
display(ob);
}

int main()
{
MyClass ob1(10);
cout << "val in main: ";
display(ob1);

// pass by value example
change(ob1);
cout << "val after change(): ";
display(ob1);

// return object and assignment example
ob1 = ob1.twice(); // returns an object
cout << "val after ob1.twice(): ";
display(ob1);

return 0;
}
</pre>
<pre>
Share this post