// student6a.cc #include #include using namespace std; class Student { private: string Name; bool Auditor; double *Grades; public: // Constructor Student(string theName, bool isAuditor = false) :Name(theName), Auditor(isAuditor) { Grades = new double[3]; for (int i=0; i<3; i++) Grades[i] = 0.0; } // Copy constructor Student(const Student& Source) { cout << "In copy constructor!" << endl; Name = Source.Name; Auditor = Source.Auditor; Grades = new double[3]; for (int i=0; i<3; i++) Grades[i] = Source.Grades[i]; } // Move constructor Student(Student&& Source) { cout << "In move constructor!" << endl; Name = Source.Name; Auditor = Source.Auditor; Grades = Source.Grades; } // Destructor ~Student() { delete [] Grades; // delete the dynamically allocated array } void SetGrade(int whichGrade, double grade) { Grades[whichGrade] = grade; } void PrintGrades(void) { if (Auditor) cout << "Auditor "; else cout << "Student "; cout << Name << " grades: "; cout << Grades[0] << "," << Grades[1] << "," << Grades[2] << endl; } void PrintCourseGrade(void) { if (Auditor) cout << "Auditor "; else cout << "Student "; cout << Name << " has course grade "; cout << (Grades[0] + Grades[1] + Grades[2]) / 3.0 << endl; } }; // done defining and declaring Student class // Now safe thanks to copy constructor with deep copy void PrintStudentGrades(Student Input) { Input.PrintGrades(); Input.PrintCourseGrade(); } // If the student were to finish the rest of the semester with // perfect grades, what would their record look like? Student StudentFinishPerfectly(Student& Source, int nextGrade) { cout << "About to create copy to work on" << endl; Student NewStudent(Source); cout << "Modifying grades in copy" << endl; for (int i=nextGrade; i<3; i++) { NewStudent.SetGrade(i, 100.0); } cout << "About to return modified object" << endl; return NewStudent; } int main() { Student Student1("John Smith"); // no 2nd argument given, assumes default Student1.SetGrade(0, 80.0); cout << "About to print initial grades by passing object" << endl; PrintStudentGrades(Student1); cout << "If perfect grades for rest of semester, ..." << endl; PrintStudentGrades(StudentFinishPerfectly(Student1, 1)); }