// student6.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; } // 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 // Not safe; when Input goes out of scope the destructor will be called // but the destructor deletes our Grades array. The original objects // (Student1 and Student2 in main() below) will have their Grades pointers // pointing to invalid memory after this function is called! This is a // problem when they also go out of scope at the end of main() --- the // destructors will then try to free Grades a second time! void PrintStudentGrades(Student Input) { Input.PrintGrades(); Input.PrintCourseGrade(); } int main() { Student Student1("John Smith"); // no 2nd argument given, assumes default Student1.SetGrade(0, 80.0); Student Student2("Jane Doe", true); Student2.SetGrade(0, 100.0); PrintStudentGrades(Student1); PrintStudentGrades(Student2); }