Another question from reading "Accelerated C++" by Andrew Koenig and Barbara E. Moo, and I'm at the chapter about constructors (5.1), using the example as before.
They write
we'll want to define two constructors: the first constructor takes no arguments and creates an empty
Student_info
object; the second takes a reference to an input stream and initializes the object by reading a student record from that stream.
leading to the example of using Student_info::Student_info(istream& is) {read(is);}
as the second constructor which
delegates the real work to the read function. [...] read immediately gives these variables new values.
The Student_info
class is
class Student_info {
public:
std::string name() const (return n;}
bool valid() const {return !homework.empty();}
std::istream& read(std::istream&);
double grade() const;
private:
std::string n;
double midterm, final;
std::vector<double> homework;
};
Since read
is already defined as a function under the Student_info
class, why is there a need to use a second constructor - isn't this double work? Why not just use the default constructor, and then the function since both are already defined?