Question

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.

Was it helpful?

Solution

what I really don't understand is why the author uses & to redefine a function already belonging to std class

He's not redefining a function.

He's creating a new function, called read, that returns an istream&.

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.

OTHER TIPS

Because Student_info is a user-defined type and the istream operator needs to be overload it in order to know how to handle a Student_info parameter.

Think about operator overloading with mathematical operators and the same thing applies.

He uses & because he wants to return it as reference to the already created one so there is no unnecessary copy operations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top