Please consider the following three simplified files:
student.h:
#ifndef STUDENT_H
#define STUDENT_H
#include "course.h"
class Student
{
private:
Course someCourse;
};
#endif
course.h:
#ifndef COURSE_H
#define COURSE_H
#include "student.h"
class Course
{
private:
Student someStudent;
};
#endif
and main.cpp:
#include "student.h"
int main();
This wouldn’t compile giving me
error C2146: syntax error : missing ‘;’ before identifier ‘someStudent’
It would produce a lot more errors (even for the correct portions of code) in a more complicated program. I guess the design is wrong: Student includes Course and Course includes Student. What I want to represent with it is that a student takes several courses and a course has has several students (I use vectors in a full program, avoided them here for simplicity). Any advice how this would be possible?
Thanks in advance, Vlad.
UPDATE:
Thanks for fast replies. Forward declaration of Student class in Course class (and removing #include "student.h") seems to do the job.
Sorry, I thought it wouldn’t matter here, but in fact I am using vectors of const pointers in each of them (since a Student shouldn’t be able to control a Course and a Course shouldn’t be able to control a Student), as:
vector<const Student* const> students; // in Course class
This is going circular, as long as you declare
someCourseandsomeStudentas non-pointer members of classStudentandCourserespectively (as you’ve done), because the compiler sees the definition ofStudent, it needs to know its size which in turn means, it needs to know the size of its all members, includingCoursewhich is one of them. But to know the size ofCourse, it needs to know the size ofStudent. That becomes circular.So you need to break this circle, by declaring at least one of them as pointer. For example, you can do this:
Also note that when you declare
pSomeCourseas pointer of typeCourse*, you don’t need to include the header file in whichCourseis defined. Just forward declaration of the classCourseis enough, as I did in the above code.The reason why it works because the size of pointer of any class is same, and the compiler need not know the size of the class, in order to know the size of the pointer of the same class. In other words, the compile can know
sizeof(Course*)without even knowingsizeof(Course).