Create a class named Student that has three member variables:
name – A string that stores the name of the student
numClasses – An integer that tracks how many courses the student is currently
enrolled in
classList – A dynamic array of strings used to store the names of the
classes that the student is enrolled in
Write appropriate constructor(s), mutator, and accessor functions for the class along with the following:
• A function that inputs all values from the user, including the list of class
names. This function will have to support input for an arbitrary number of classes.
• A function that outputs the name and list of all courses.
• A function that resets the number of classes to 0 and the classList to an
empty list.
• An overloaded assignment operator that correctly makes a new copy of the list of courses.
• A destructor that releases all memory that has been allocated.
Write a main function that tests all of your functions.
#include <cstdlib>
#include <string>
using namespace std;
class Student
{
public: Student();
~Student();
void InputData();
void OutputData();
void ResetClasses();
Student& operator =(const Student& rightSide);
private:
string name;
int numClasses;
string *classList;
};
#include <iostream>
#include <iomanip>
using namespace std;
Student::Student() : name(""), numClasses(0), classList(NULL)
{
}
Student::~Student()
{
numClasses = 0;
ResetClasses();
name = "";
}
void Student::ResetClasses()
{
if (classList) {
delete[] classList;
classList = NULL;
numClasses = 0;
}
}
void Student::InputData()
{
ResetClasses();
cout << "Enter student name > ";
getline(cin, name);
cout << "Enter number of classes > ";
cin >> numClasses;
cin.ignore(2, '\n');
if (numClasses > 0) {
classList = new string[numClasses];
for (int i = 0; i<numClasses; i++) {
cout << "Enter name of class " << (i + 1) << " > ";
getline(cin, classList[i]);
}
}
cout << endl;
}
void Student::OutputData()
{
cout << "Class List: " << endl;
for (int i = 0; i < numClasses; i++) {
cout << setw(2) << right << i + 1 << ") " << classList[i] << endl;
}
}
Student& Student::operator =(const Student& rightSide)
{
ResetClasses();
numClasses = rightSide.numClasses;
if (numClasses > 0) {
classList = new string[numClasses];
for (int i = 0; i < numClasses; i++) {
classList[i] = rightSide.classList[i];
}
}
return *this;
}
int main()
{
Student s1, s2;
s1.InputData();
cout << "Student 1's data:" << endl;
s1.OutputData();
cout << endl;
s2 = s1;
cout << "Student 2's data after assignment from student 1:" << endl;
s2.OutputData();
s1.ResetClasses();
cout << endl;
cout << "Student 1's data after reset:" << endl;
s1.OutputData();
cout << endl;
cout << "Student 2's data, should still have original classes:" << endl;
s2.OutputData();
cout << endl;
system("pause");
return 0;
}