11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

240Part 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 aconstructor to create an object, even a copy of an existing object. C++ couldcopy the object into the new object one byte at a time. That’s what older languageslike C would have done. But what if you don’t want a simple copy ofthe object? What if something else is required? (Ignore the “why?” for a littlewhile.) 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 acopy of the object ms on the stack during the call of function fn(). This particularcopy constructor would be Student::Student(Student&) — saythat three times quickly.Using the copy constructorThe best way to understand how the copy constructor works is to see one inaction. Consider the following CopyConstructor program://// CopyConstructor - demonstrate an example copy constructor//#include #include #include using namespace std;const int MAXNAMESIZE = 40;class Student{public:// conventional constructorStudent(char *pName = “no name”, int ssId = 0){strcpy(name, pName);id = ssId;cout

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!