// CopyStudent - demonstrate a copy constructor by // passing an object by value #include #include #include class Student { public: // create an initialization function void init(char* pszName, int nId, char* pszPreamble = "\0") { int nLength = strlen(pszName) + strlen(pszPreamble) + 1; this->pszName = new char[nLength]; strcpy(this->pszName, pszPreamble); strcat(this->pszName, pszName); this->nId = nId; } //conventional constructor Student(char* pszName = "no name", int nId = 0) { cout << "Constructing new student " << pszName << "\n"; init(pszName, nId); } //copy constructor Student(Student &s) { cout << "Constructing Copy of " << s.pszName << "\n"; init(s.pszName, s.nId, "Copy of "); } ~Student() { cout << "Destructing " << pszName << "\n"; delete pszName; } protected: char* pszName; int nId; }; //fn - receives its argument by value void fn(Student s) { cout << "In function fn()\n"; } int main(int nArgs, char* pszArgs[]) { // create a student object Student randy("Randy", 1234); // now pass it by value to fn() cout << "Calling fn()\n"; fn(randy); cout << "Returned from fn()\n"; // done return 0; }