Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>My question is 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?</p> </blockquote> <p>The second constructor takes an argument from the caller and passes it on to the <code>read</code> function. This allows you to directly instantiate a <code>Student_info</code> with an <code>std::istream</code>.</p> <pre><code>std::istream is = ....; Student_info si(is); // internally calls read(is) </code></pre> <p>as opposed to</p> <pre><code>std::istream is = ....; Student_info si; si.read(is); // how could we use is if this call isn't made? Now we have to read some docs... </code></pre> <blockquote> <p>Why not just use the default constructor, and then the function since both are already defined?</p> </blockquote> <p>Because it is better to construct objects such that they are in a coherent, useful state, rather than construct them first and then initialize them. This means users of the objects do not have to worry about whether the thing can be used or must first be initialized. For example, this function takes a reference to a <code>Student_info</code>:</p> <pre><code>void foo(const Student_into&amp; si) { // we want to use si in a way that might require that it has been // initialized with an istream si.doSomethingInvolvingInputStream(); // Wait, what if the stream hasn't been read in? // Now we need a means to check that! } </code></pre> <p>Ideally, <code>foo</code> should not have to worry about the object has been "initialized" or made valid.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload