line 121 (p = j) calls both assignment operator and copy constructor functions. is this normal?
also the destructor is called three times. I thought the function should have been called two times.
#include <iostream>
#include <string>
using namespace std;
class Student{
private:
//A string that stores the name of the student
string name;
int numCourses;
//"courseList is a pointer that points to an address of a string array"
string *courseList;
public:
//Constructor
Student(string, int, string *);
//Destructor
~Student();
//copy constructor
Student(const Student &);
Student Student:: operator = (const Student &);
void Student::outputCourses();
};
//--------------------------------------------------------------------------------------------------------------
//constructor
Student::Student(string name, int numCourses, string *courseList){
//copy contents of the array which courseList points, into newly
//allocate array
this->numCourses = numCourses;
this->courseList = new string[numCourses];
for (int i=0;i<numCourses;i++)
{
this->courseList[i]= courseList[i];//std::copy(this->courseList, this->courseList+numCourses, numCourses);
}
this->name = name;
this->outputCourses();
}
void Student::outputCourses(){
cout << endl;
//cout << this->objName <<" object content:\n";
cout << "course(s) of " << this->name << "\n";
for(int i=0 ; i<this->numCourses ; i++){
cout << "course number " << i+1 << " is " << courseList[i] << "\n";
}
getchar();
}
//operator = overloading
Student Student:: operator = (const Student &right){
if(this->numCourses != right.numCourses)
{
this;
cout << "courseList address:" << &courseList <<endl;
delete [] this->courseList;
this->courseList = new string[right.numCourses];
}
this->name = right.name;
this->numCourses = right.numCourses;
for (int i=0;i<right.numCourses;i++)
{
this->courseList[i]= right.courseList[i];//copy each array element
}
return *this;
}
//copy constructor
Student::Student(const Student &obj){
this->name = obj.name;
this->numCourses = obj.numCourses;
courseList = new string[obj.numCourses];
for (int i=0;i<obj.numCourses;i++)
{
courseList[i]= obj.courseList[i];//copy each array element
}
}
//Destructor
Student::~Student(){
cout << "destructor running....\n";
cout << "courseList address: " << &courseList << " - deleteing courseList varible\n";
delete [] courseList; //courseList points to a dynamically allocated array so [] needed to free the memory
getchar();
}
//---------------------------------------------------------------------------------------------------------------
int main(){
cout << "----------------test 2-----------------\n";
//invokes both copy constructor and assignment operator
string johnCourses[5] = { "Math", "Biology", "Science", "History", "English" };
Student j("John", 5, johnCourses);
string peterCourses[2] = { "cPlusPlus", "Calculus"};
Student p("peter", 2, peterCourses);
p = j;
cout << "-----------\n";
p.outputCourses();
return 0;
}