Help with composition A has B and B has A

Hi, I am creating a hospital management system program.
While coding I encountered some problems for Patient Class and Doctor class.

I would like the Doctor class have list of Patients and Patients class have list of Doctors. But it is giving me errors like

'Doctor' does not name a type; did you mean 'wtcob'?

1
2
3
4
5
6
7
8
9
10
11
//Patient class
#include <iostream>
#include "Doctor.h"

class Patient{
private:
  Doctor *doctor;
 //...

};



1
2
3
4
5
6
7
8
9
10
11
12
//Doctor class
#include <iostream>
#include "Patient.h"

class Doctor{

private:
  Patient *patient;
 //...

};
The problem you're not aware of yet is that if Doctor.h includes Patient.h and Patient.h includes Doctor.h.....you see where THAT is going, right?

Choose.

They simply can't be dependent upon including each other. That will never work out.

Second, you can declare a class is a class without defining that class.

1
2
3
4
5
6
7
8
9
class Patient;

class Doctor{

private:
  Patient *patient;
 //...

};


This declares that Patient is a class without defining it. The code in the HEADER for Doctor can't USE the Patient class, but it can declare a pointer to it.

What you need is not to include these headers for each other, but simply to forward declare the related class (declare Doctor in the Patient.h as I did here), then include both headers in your CPP file.
Last edited on
I am creating a hospital management system program.

... that real lives of real people will depend on? I hope not. I hope it is just a homework.


A Doctor dies. She must inform all her Patients. The Patients must remove that Doctor from their lists. The Patients may request new Doctor from the hospital. Again an update to Patients' lists and other Doctors' lists. Complex, but doable.

Think of an alternative:
* Doctor has no list (Does not depend on Patient)
* Patient has no list (Does not depend on Doctor)
* Hospital has a list of Patient-Doctor pairs
* Hospital manages that list


1
2
3
4
5
class Doctor{
private:
  Patient *patient; // Is this "a list"?
 //...
};

That pointer can either point to one Patient or to an array of Patients.
One Patient is ok (as long as you manage pointer invalidation), but not "a list".

If it points to an array, then how many elements does that array have?
An element of an array is a Patient object. That sounds like a copy. You should not clone people; troublesome.
Topic archived. No new replies allowed.