Copy Constructors
Whenever an object
obj2 is assigned to
an object
obj3 being newly declared:
Person obj3 = obj2;
a bit by bit copy of
obj2 is created
by calling
Person’s constructor and
setting the new object's member values accordingly. This might not
always be desirable, for example when an object's constructor performs
actions that are not supposed to be repeated when the object is copied
(like sending an initialization message to another object, for example,
or allocating some memory space, registering with another object, etc.)
For such a reason copy constructors were introduced. A copy constructor allows
you to define a constructor that will be used when an object is created and
assigned another one.
In the following example, the class
Person
has a two-parameter constructor that performs an action which should take place
only once: it saves the name of the person in a global array called
arrayOfPersons. To prevent such an action from
happening also when an object is copied, the copy constructor:
Person(const Person &o)
is defined, which simply copies
name and
number in the new object without saving
name into the array. So no object's
name will
be written twice in the array. (For sake of simplicity, it is assumed that every
object will receive a different name by the user, otherwise a name-checking
routine should be written).
Example
#include <iostream>
#include <string>
using namespace std;
string arrayOfPersons[30]; // contains names of all people
void printArrayOfPersons()
{
for(int i=0; i<30 && arrayOfPersons[i] != ""; i++)
cout << arrayOfPersons[i] << endl;
}
class Person
{
string name;
int number;
void save(string aName) // saves a person's name in arrayOfPersons
{
for(int i=0; i<30; i++)
if(arrayOfPersons[i] == "")
{
arrayOfPersons[i] = aName;
break;
}
}
public:
Person(string aName, int aNumber) // overloaded two-parameter constructor
{
name = aName;
number = aNumber;
save(aName);
}
string getName()
{
return name;
}
int getNumber()
{
return number;
}
// COPY CONSTRUCTOR: o is a reference
// to the object being assigned
Person(const Person &o)
{
name = o.name;
number = o.number; // NB: name is not saved in arrayOfPersons
}
};
int main()
{
Person obj1("Jack", 22222222);
Person obj2("Lisa", 11111111);
Person obj3 = obj2; // here the copy constructor is called
// verify the copy took place
cout << obj3.getName() << " " << obj3.getNumber() << endl;
cout << "Array of persons:" << endl;
printArrayOfPersons(); // show that the name has no duplicate in the array
}
Output
Lisa 11111111
Array of persons:
Jack
Lisa