Write a C++ program: About Overloading the Assignment Operator #include <iostrea
ID: 3691560 • Letter: W
Question
Write a C++ program:
About Overloading the Assignment Operator
#include <iostream>
#include <string>
using namespace std;
// this class is implemented to hold the grades for an exam
class examType
{
private:
int maxNoOfStudents; // this is the max size of the dynamic list
int noOfStudents; // this is the current number of elements in the dynamic array
double *grades; // grades is a pointer the the dynamic array
public:
// constructor with parameters
examType(int maxSize)
{
noOfStudents = 0;
maxNoOfStudents = maxSize;
grades = new double[maxNoOfStudents];
}
~examType()
{
delete [] grades;
grades = NULL;
}
// overload the assignment operator = to allow deep copy of the grades pointer!
//...
int getNoOfStudents()
{
return noOfStudents;
}
int getMaxNoOfStudents()
{
return maxNoOfStudents;
}
void append(double newGrade)
{
if (noOfStudents < maxNoOfStudents)
{
grades[noOfStudents] = newGrade;
noOfStudents++;
}
else
{
cout << "Error: This list cannot get more elements. " << endl;
}
}
double getGrade(int thePosition)
{
return grades[thePosition];
}
void print()
{
cout << "Number of Students in the Exam: " << noOfStudents << endl;
for (int i=0; i < noOfStudents; i ++)
{
cout << grades[i] << " ";
}
cout << endl;
}
};
int main()
{
examType midterm(10);
examType copyOfMidterm(4);
// enter grades for midterm1
midterm.append(50);
midterm.append(100);
midterm.append(80);
// print results for midterm 1
midterm.print();
copyOfMidterm = midterm; // by default assignment operator = does shallow copy here.
// your job is to overload the assignment operator = in the class above, so that deep copying is done!
copyOfMidterm.print();
copyOfMidterm.append(55); // add a new grade to copyOf Midterm
// *****hint: if you overloaded the = operator correctly and did deep copying you
// should see that the copyOfMidterm object prints the additional grade!
midterm.print();
copyOfMidterm.print();
system("pause");
return 0;
}
_____________Thank you for the help ______________________
Explanation / Answer
Add this after print method:
void print()
{
cout << "Number of Students in the Exam: " << noOfStudents << endl;
for (int i=0; i < noOfStudents; i ++)
{
cout << grades[i] << " ";
}
cout << endl;
}
void operator=(const examType &ex )
{
maxNoOfStudents=ex.maxNoOfStudents;
noOfStudents=ex.noOfStudents;
grades=ex.grades;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.