I am going through accelerated c++ and have a question in regards to Chapter 4. We go over referencing in this section, and I believe I understand its use to manipulate objects and variables. However, what I really don't understand is why the author uses & to redefine a function already belonging to std class
Here is the code: Student_info.cpp
istream& read(istream& is, Student_info& s)
{
// read and store the student's name and midterm and final exam grades
is >> s.name >> s.midterm >> s.final;
read_hw(is, s.homework); // read and store all the student's homework grades
return is;
}
main.cpp
while (read(cin, record)) {
// find length of longest name
maxlen = max(maxlen, record.name.size());
students.push_back(record);
}
Could someone please explain why we would do this? Is it just for pedagogical reasons to show that we can? Thanks in advance.
He's not redefining a function.
He's creating a new function, called
read
, that returns anistream&
.The fact that it returns a reference is convention (matching the equivalent behaviour of standard library functions) but has very little to do with the fact that he's defining the function in the first place.
The standard library has no function with knowledge of the custom type
Student_info
.