Reputation: 21
Basically my code has 2 classes:
class teacher {
//has object of class course
};
class course {
//has object of class teacher
};
This wasn't working, as teacher was not able to access class course because it is written after class teacher. So then I tried creating class prototypes.
class teacher;
class course;
.....
class teacher {
//object of class course
};
class course {
//object of class teacher
};
Still doesn't work. And yes i do need these classes to hold each others objects. Pleasee tell me this can work the way I want it too, and I don't have to change my code. Would really appreciate some help. Thank you.
Upvotes: 0
Views: 128
Reputation: 57708
I think you should view this as a database issue.
Let's have another table containing teachers and courses:
class Teacher_Course
{
Teacher t;
Course c;
}
The table could be represented as:
std::vector<Teacher_Course> tc_table;
The picture would be:
+---------+----------+
| Teacher | Course |
+---------+----------+
| Schults | Math 1 |
+---------+----------+
| Schults | Calculus |
+---------+----------+
| Jonez | History1 |
+---------+----------+
This schema allows your Teacher
and Course
classes to be independent. The relationship is modeled by the Teacher_Course
class.
Thus eliminating any circular dependencies between Teacher
and Course
.
Note: to be more database friendly, you may want to have record IDs and research foreign keys
Upvotes: 0
Reputation: 3902
Code that works for what you probably want to do:
teacher.h
#include <vector>
using std::vector;
class Course;
class Teacher
{
vector<Course*> courses;
...
};
course.h
#include <vector>
using std::vector;
class Teacher;
class Course
{
vector<Teachers*> teachers;
...
};
Note that in the source files, you will want to include both header files, as right now, Teacher
does not know the functionality of Course
vice versa.
I did this with raw pointers to make it easier for you to understand, but you should switch to some sort of smart pointers at some point (in this case probably weak_ptr
).
Btw, usually, one writes class names with major first letters.
Upvotes: 1