0
#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.

  • 5
    Please read about [the rules of three, five and zero](https://en.cppreference.com/w/cpp/language/rule_of_three). I recommend you follow the rule of zero, which is simply done by using `std::string`. – Some programmer dude May 15 '22 at 17:44
  • 1
    All in all you have too many pointers in that short program. There's no need for *any* of the pointers really. – Some programmer dude May 15 '22 at 17:44
  • 3
    You forgot to implement the copy assignment operator (the default one, as youve described copies the pointer itself, what you want is a 'deep copy') – Borgleader May 15 '22 at 17:48
  • 4
    This looks like a Java or C# programmer's attempt at C++, without learning C++. `Student *mystudent1 = new Student();` -- This could simply be: `Student mystudent1{};` -- there is no need to unnecessarily call `new` there. – PaulMcKenzie May 15 '22 at 18:00
  • 1
    ... and with every unnecessary `new` that you remove from your program, you have one `delete` less to worry about. – Ted Lyngmo May 15 '22 at 18:18

0 Answers0