Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It isn't double work on the contrary it simplifies the object initialization for the caller who instantiates the class</p> <p>If you create the class with a single constructor every time you have to do</p> <pre><code>std::istream is = std::cin; Student_info si(); si.read(is); // si.foo(); // si.bar(); // si.baz(); </code></pre> <p>Maybe some other operations can be added that can be done in constructor. So you don't have to write them again when you need to instantiate the class. If you create 10 instances you will have to write </p> <p>( 10 -1 = ) 9 more lines and this isn't a good approach for OOP</p> <pre><code>Student_info::Student_info(istream&amp; is) { read(is); //foo(); //bar(); //baz(); } </code></pre> <p>But when you define two constructors like above, you can use the class like</p> <pre><code>std::istream is = std::cin; Student_info si(is); </code></pre> <p>One of the main goals of OOP is writing reusable and not self repeating code and another goal is <a href="http://en.wikipedia.org/wiki/Separation_of_concerns" rel="nofollow">seperation of concerns</a>. In many cases person who instantiates the object doesn't need to know implementation details of the class. </p> <p>On your example <code>read</code> function can be private when its called inside constructor. This reaches us another concept of OOP <a href="http://en.wikipedia.org/wiki/Information_hiding" rel="nofollow">Encapsulation</a></p> <p>Finally this isn't double work and its a good approach for software design</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