#include <iostream>
using namespace std;
class Student {
private:
char *stdName;
int stdID;
double CGPA;
public:
Student() {
stdName = new char[100];
strcpy(stdName, "Not provided");
stdID = 0;
CGPA = 0;
cout << "Student() has been called!" << endl;
}
Student(const char *sName, int sID, double sCGPA) {
this->stdName = new char[100];
strcpy(stdName, sName);
stdID = sID;
CGPA = sCGPA;
cout << "Student(char *sName, int sID, double sCGPA) has been called!" << endl;
}
//copy constractor
Student(const Student& std) {
this->stdName = new char[100];
strcpy(stdName, std.stdName);
stdID = std.stdID;
CGPA = std.CGPA;
cout << "Student(const Student& std) has been called!" << endl;
}
~Student() {
delete [] stdName;
cout << "~Student() has been called!" << endl;
}
void printer(){
cout << "Name " << stdName << " ID " << stdID << " CGPA " << CGPA << endl;
}
};
int main(){
Student *mystudent1 = new Student();
mystudent1->printer();
Student *mystudent2 = new Student("Snake", 100, 4.00);
mystudent2->printer();
Student *mystudent3 = new Student(*mystudent1);
mystudent3->printer();
*mystudent3 = *mystudent2;
delete mystudent1;
delete mystudent2;
delete mystudent3;
return 0;
}
I have a problem with this code as when I try to copy the information from mystudent2 to mystudent3, the name is kept in the same memory slot and the new memory for mystudent3 is not allocated. How can I fix this ? However in all other places the memory allocation is done normally without any issues.