Easy C++


C++ Tutorial - Lesson 20: Copy Constructors

Copy Constructors

by John Kopp

Support this site at no cost to you

Introduction to Copy Constructors
Welcome to EasyCPlusPlus.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 {
    Employee(char *name, int id);
    char *getName(){return _name;}
    //Other Accessor methods
    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);

    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.

Previous Page       Next Page