This page is a follow-up of solution discussed in the forward list solution page where studentNode is implemented with inheritance (the is-a relationship). Here, we will implement the studentNode with composition (i.e. has-a relationship) It is highly recommended that you get to know the other page first.
The student (aka studentGrade in code) class remains unchanged. We just add studentNode class as follows:
class studentGrade
{
friend ostream& operator<< (ostream&, const studentGrade&);
friend istream& operator>> (istream&, studentGrade&);
public:
string name;
int grade;
};
class studentNode
{
studentGrade sg;
studentNode *next; // link to next
};
Building the link list from file now use dynamic allocations.
bool studentGradeDB::load(string fn)
{
ifstream fin(fn.c_str());
if (fin.fail()) return false;
while(!fin.eof()){
studentNode *sgp = new studentNode;
// fin >> *sgp; this is replaced because it is composition now
fin >> (sgp->sg);
sgp->next = head; // add it to the beginning of linklist
head = sgp;
}
fin.close();
return true;
}
Note that because it is NOT inheritance any more, studentNode is NOT a student. studentGrade operators will not work with studentNode. That's why we can NOT directly use fin >> *sgp; But, since studentNode has a studentGrade member, we can use fin >> (sgp->sg); to read in a studentGrade object directly.