I want to know which is better way for this problem:
A teacher can teach more than one subject or can take more than on lab or may be both in a institute. Lab,Subject,Teacher also have some other variables. I did not write them all here.
New lab,subject and teacher can be added individually. When a teacher is added I only input all variables of Teacher class and labCode and subCode. There are some Labs and Subjects which are predefined and others which are added later. I can view record of a teacher which shows his Lab and Subject details also if available.
My concepts in c++ are not too strong and I don’t know which one is better for this. Should I give a pointer in Teacher class to Lab and Subject class or should I inherent them, or is there any better way to do this.
class Lab{
char labCode[20];
char labName[40];
int labYear;
//here default constructor
};
class Subject{
char subCode[20];
char subName[20];
int subYear;
//here default constructor
};
//-------------------------------------
class Teacher{
char facName[30];
int teacherSubCount;
int teacherLabCount;
Subject *subject;
Lab *lab;
//here default constructor
};
//------------or should i do like this--------------
class Teacher:public Lab,public Subject{
char teacherName[30];
int teacherSubCount;
int teacherLabCount;
//here default constructor
};
If you can suggest any tutorials so I can learn the power of a pointer as my book states “pointers are very powerful c++”, but they only give some simple examples 🙂
More specific to your classes, though, first ask yourself… “Is a Teacher a type of Lab or a type of Subject?” Clearly, the answer is “no.”
In an inheritance model, the child class should itself be an instance of the parent class. Considering the Liskov Substitution Principle, that child object should be treatable as that parent object. So if there’s code that’s looking for a
Subjectyou would be able to pass it aTeacher. Intuitively, that doesn’t make much sense and is not an accurate representation of the real-world domain entities being modeled.In this case you definitely want object composition instead of class inheritance. The
Teacherhas aLaband has aSubject, not is aLabor is aSubject. Indeed, if theTeachercan have multipleLabs orSubjects then the composition would simply change from a single instance class member to an array or list of some kind. Whereas the inheritance approach would break entirely in that case.When modeling objects that represent real-world concepts like this, consider intuition of those real world concepts foremost and the technical shortcuts to implementation secondary. If it doesn’t make sense in terms of what’s being modeled, then it won’t make sense in the code either.