J.Razi J.Razi - 15 days ago 8
C++ Question

Is it ok for 2 classes to have field pointing eachother?

So I have classes

User
and
Job
:

class User {
string user_name;
Job* job;
};

class Job {
string job_type;
int salary;
User* user;
};


Are there any problems with this kind of design? I have a large number of
Job
s and
User
s and i want a fast access to a user's job or the user who is taking a job. Is it ok that these classes have fields poiting to each other?

Answer

It's fine. You need to be careful to manage the pointers carefully to avoid leaks, for example. But it's perfectly reasonable.

Comments