Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C++ For Dummies (2004) [eng].pdf
Скачиваний:
84
Добавлен:
16.08.2013
Размер:
8.09 Mб
Скачать

Chapter 18

Copying the Copy Copy Copy

Constructor

In This Chapter

Introducing the copy constructor

Making copies

Having copies made for you automatically

Creating shallow copies versus deep copies

Avoiding all those copies

The constructor is a special function that C++ invokes automatically when an object is created to allow the object to initialize itself. Chapter 16

introduces the concept of the constructor, whereas Chapter 17 describes other types of constructors. This chapter examines a particular variation of the constructor known as the copy constructor.

Copying an Object

A copy constructor is the constructor that C++ uses to make copies of objects. It carries the name X::X(X&), where X is the name of the class. That is, it’s the constructor of class X, which takes as its argument a reference to an object of class X. Now, I know that this sounds really useless, but just give me a chance to explain why C++ needs such a beastie.

Why you need the copy constructor

Think for a moment about what happens when you call a function like the following:

void fn(Student fs)

{

// ...same scenario; different argument...

240 Part III: Introduction to Classes

}

int main(int argcs, char* pArgs[])

{

Student ms; fn(ms); return 0;

}

In the call to fn(), C++ passes a copy of the object ms and not the object itself.

C++ passes arguments to functions by value.

Now consider what it means to create a copy of an object. First, it takes a constructor to create an object, even a copy of an existing object. C++ could copy the object into the new object one byte at a time. That’s what older lan­ guages like C would have done. But what if you don’t want a simple copy of the object? What if something else is required? (Ignore the “why?” for a little while.) You need to be able to specify how the copy should be constructed.

Thus, the copy constructor is necessary in the preceding example to create a copy of the object ms on the stack during the call of function fn(). This par­ ticular copy constructor would be Student::Student(Student&) — say that three times quickly.

Using the copy constructor

The best way to understand how the copy constructor works is to see one in action. Consider the following CopyConstructor program:

//

// CopyConstructor - demonstrate an example copy constructor

//

#include <cstdio> #include <cstdlib> #include <iostream> using namespace std;

const int MAXNAMESIZE = 40; class Student

{

public:

// conventional constructor

Student(char *pName = “no name”, int ssId = 0)

{

strcpy(name, pName); id = ssId;

cout << “constructed “ << name << endl;

}

Chapter 18: Copying the Copy Copy Copy Constructor 241

// copy constructor Student(Student& s)

{

strcpy(name, “Copy of “); strcat(name, s.name);

id = s.id;

cout << “constructed “ << name << endl;

}

~Student()

{

cout << “destructing “ << name << endl;

}

protected:

char name[MAXNAMESIZE]; int id;

};

// fn - receives its argument by value void fn(Student copy)

{

cout << “In function fn()” << endl;

}

int main(int nNumberofArgs, char* pszArgs[])

{

Student chester(“Chester”, 1234); cout << “Calling fn()” << endl; fn(chester);

cout << “Returned from fn()” << endl;

//wait until user is ready before terminating program

//to allow the user to see the program results system(“PAUSE”);

return 0;

}

The output from executing this program follows:

constructed Chester Calling fn()

constructed Copy of Chester In function fn() destructing Copy of Chester Returned from fn()

Press any key to continue . . .

The normal constructor generates the first message from the declaration on the first line of main(). main() then ouputs the calling... message before calling fn(). As part of the function call process, C++ invokes the copy con­ structor to make a copy of chester to pass to fn(). The function fn() outputs