Search code examples
c++delete-operator

How to use delete function for a class object?


This program is a student Database with add and delete functions for both students and courses. I have an issue successfully deleting a specific student from the database. Also, when I attempt to add more than one student to the database with a new student ID,it states that the student is already in the database when they aren't supposed to be. I've attached code snippets of the object class and the add and remove functions for the student. Any help would be GREATLY appreciated. Cheers .

class student {
public:
    int studentid;
    course * head;
    student (int id){ studentid = id; head = nullptr;}
    student () {head = nullptr;}
};

void add_student(student DB[], int &num_students)
{ 
    int ID;
    cout << "Please enter the id of the student you wish to enter " << endl;
    cin >> ID;
    for(int x = 0; x <num_students; x++)
    { 
        if (DB[x].studentid == ID);
    {  
    cout << "the student is already in the Database" << endl; return; } }
    student numberone(ID);
    DB[num_students] = numberone;
    num_students++; 
}

void remove_student(student DB[], int &num_students)
{ 
    int ID;
    cout << "Enter the student id you wish to delete from the Database " << endl;
    cin >> ID;
    // This is where I have the error
    // student * pointer2 = student(ID);
    //   delete pointer2; 
}

Solution

  • You cannot use 'delete' operator, unless you use the 'new' operator to create an object

    student * pointer2 = student(ID); //wrong 
    delete pointer2; 
    

    1st option is

     student pointer2(ID) //no need to use delete operator here
    

    In this option '.'operator is used for accessing class members. Example

    pointer2.studentId
    

    2nd Option

    'delete' operator is used to deallocate the memory that allocated using 'new' operator

    student * pointer2 = new student(ID);
    delete pointer2; 
    

    here '->' operator is used for accessing class members. Example

    pointer2->studentId