I get a Segmentation fault error and I cant find what's wrong with the program.
programs fails when it tries to execute this line "delete [] this->courseList"
in operator = overloading function.
#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){
this->name = name;
this->numCourses = numCourses;
//"courseList is a pointer that points to an address of a string array"
this->courseList = new string[numCourses];
this->courseList = courseList;
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;
}