dimanche 30 avril 2023

How to call the destructor for 2 objects that has each other as reference in different files?

I have 2 classes named student and course with constructors etc. in separate files as such :

//student.h
class course;
class student {
  public:
    ~Student();
  private:
    course *course_ref;
}

// student.cpp
student::~student() {delete [] course_ref ; course_ref = NULL;}

// course.h
class student;
class course {
  public:
    ~Course();
  private:
    student *student_ref;

//course.cpp
course::~course() { delete [] student_ref; student_ref = NULL;}


I guess it has to do with the undefined behavior and compiler needs to know the body of the class before destroying it but I couldn't find a way to do it. Classes have to be in different files, *.h and *.cpp, is there any way to do it?

I've tried putting course's destructor in student.cpp but then again it doesn't know the course fully yet so got an error.

Aucun commentaire:

Enregistrer un commentaire