by John
Kopp
Introduction Welcome to About.com's
free tutorial on C++ programming. This lesson is covers copy
constructors. In previous
lessons we saw how to write and use constructors for
objects. A copy constructor is a special constructor that
takes as its argument a reference to an object of the same
class and creates a new object that is a copy. By default, the
compiler provides a copy constructor that performs a
member-by-member copy from the original object to the one
being created. This is called a member wise or shallow copy.
Although it may seem to be the desired behavior, in many cases
a shallow copy is not satisfactory. To see why let's look at
the Employee class introduced in an earlier lesson with one
change. We will store the name in a C-style character string rather than store the employee name
using the string class from the standard C++ library. Here is
a simple program with a bare bones version of the Employee
class.
#include <iostream> using namespace
std;
class Employee
{ public: Employee(char
*name, int
id); ~Employee(); char
*getName(){return
_name;} //Other Accessor
methods private: int
_id; char
*_name; };
Employee::Employee(char *name, int
id) { _id =
id;
_name = new
char[strlen(name) + 1];
//Allocates
an character array
object strcpy(_name,
name); }
Employee::~Employee() { delete[]
_name; }
int
main() { Employee
programmer("John",22); cout
<< programmer.getName() <<
endl; return 0; }
|
The function strlen returns the length of the string passed
into the constructor. Notice that the Employee name is now
stored in a dynamically allocated character array. It is of
"string length + 1" to allow for the null terminator used with
C-style
strings, '\0'. The strcpy
function automatically adds the null
terminator to the destination string. Also, notice that
the destructor frees the memory used to hold the employee
name. This is needed to avoid a memory leak, which was
described in the last lesson. Please see C
Tutorial - Lesson 10: Strings for more detail on C-style
strings. They are used in C++, particularly for command-line
arguments. This will be covered in a later lesson.
Next
page > Copy
Constructors, Continued > Page 1,
2
|