// grades2.cc #include #include using namespace std; class ClassGrades { private: string Name; int* Grades; public: ClassGrades(string inName) { cout << "In constructor" << endl; Name = inName; Grades = new int[3]; // assume 3 assignments for (int i=0; i<3; i++) { Grades[i] = 0; } } ~ClassGrades() { cout << "In destructor" << endl; delete [] Grades; } ClassGrades(const ClassGrades& src) { // not called in this example cout << "In Copy Constructor" << endl; Name = src.Name; Grades = new int[3]; for (int i=0; i<3; i++) { Grades[i] = src.Grades[i]; } } ClassGrades& operator= (const ClassGrades& src) { cout << "In Copy Assignment Operator" << endl; if (this != &src) { Name = src.Name; if (Grades != NULL) delete[] Grades; Grades = new int[3]; for (int i=0; i<3; i++) { Grades[i] = src.Grades[i]; } } return *this; } /* replaced by [] operator below void SetGrade(int id, int grade) { Grades[id] = grade; } */ int& operator [] (int Index) { if (Index >=0 && Index < 3) { return Grades[Index]; } } void PrintGrades() { cout << "Student " << Name << " has grades: "; for (int i=0; i<3; i++) { cout << Grades[i] << " "; } cout << endl; } }; int main() { ClassGrades Student1("John Smith"); Student1[0] = 99; cout << "Student1:"; Student1.PrintGrades(); ClassGrades Student2("Jane Doe"); Student2[0] = 100; cout << "Student2:"; Student2.PrintGrades(); Student2 = Student1; cout << "Student2:"; Student2.PrintGrades(); }