    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: A Code Critique</title>
        <link>https://members.accu.org/index.php/articles/858</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Student Code Critiques from CVu journal. + CVu Journal Vol 11, #3 - Apr 1999</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c184/">Journal Columns</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c183/">Code Critique</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c132/">113</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c183-132/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c183+132/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;A Code Critique</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 03 April 1999 13:15:30 +01:00 or Sat, 03 April 1999 13:15:30 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e16" id="d0e16"></a>Introduction by
Francis Glassborow</h2>
</div>
<p>Not infrequently appeals from students for help appear in the
better quality newsgroups. We have a general policy that we will
not do a student's homework. However, where a student is making a
genuine attempt and either post's their code or asks a specific
question the resident gurus are more lenient.</p>
<p>In mid-January I noted such an appeal and as it was actually
posted to an inappropriate NG I contacted the student directly.
What I then learned disgusted me. This was not a first time student
struggling with a C++ 101 course but a student who already had
rather more relevant experience than the course required. The
course was a pre-requisite for starting an MSIS course.</p>
<p>In the sidebars I provide two lightly edited emails from the
student. Do you feel as angry as I do that any academic
establishment should tolerate the work of such a clearly inadequate
employee?</p>
<p>By the way does anyone know how to provide some cursor control
in a console application? Using combinations of various control
characters (\b, \t, \v and \n) allows forward navigation and moving
backwards along a line but is there any way to move up a line? If
you know, please tell me. Even better if you know of a library that
provides cursor control in a console app window please pass it on.
I asked the student concerned to let me see her source code so that
I could pass it on to the Harpist for a code review. She kindly did
so though I have removed anything that would identify the author or
university.</p>
<p>Over to 'The Harpist.'</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e29" id="d0e29"></a>A Code
Review</h2>
</div>
<p>I am going to do a complete critique on the code provided, but
do so in stages. As always, I would welcome comments from readers
(just send them to Francis). I am going to tackle this in an
unexpected order. First I am going to look at the application
code.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e34" id="d0e34"></a>The
Application</h3>
</div>
<pre class="programlisting">
#include &lt;iostream&gt;               //for cin and cout
#include &quot;student.h&quot;             //for class student

using namespace std;

int main(){
  int counter;                      //counts number of entries
  counter = 0;                    //initialize counter to zero
  
  char go;                          //to control looping
  char crap[30];              //to clear the buffer???

  do  {                                 //Start loop so can repeat entry of 5 students 

  Student s1;                        //instantiate object
    s1.GetSID();                  //call member functions
    s1.GetName();
    s1.GetPhone();
    s1.GetAddress();
  Student s2;                           //instantiate object
    s2.GetSID();                 //call member functions
    s2.GetName();
    s2.GetPhone();
    s2.GetAddress();
</pre>
<p>&lt; 3 more identical blocks for s3, s4 and s5 snipped&gt;</p>
<pre class="programlisting">
    s1.Show();                       //show the student info for each object
    s2.Show();
  &lt;snipped&gt;
  cout &lt;&lt; &quot;Do you wish to continue? (Y) or (N)o &quot;;  //prompt for end of data entry
  cin.get (go);                                         //read input, compare to see if stop
  cin.getline (crap, 35);                       //I dunno, but it makes it work!!!

  }
  while ((go == 'y') ||(go == 'Y'));                  //test for quitting value
  return 0;  
}
</pre>
<p>Now here is my version to do substantially the same thing. I
will assume that among all the other things the instructor has not
introduced are arrays and references. I know that some of the
identifiers are poorly chosen but I want to focus on simply
improving what the student can already do.</p>
<pre class="programlisting">
#include &lt;iostream&gt;             
#include &quot;student.h&quot;
       
using namespace std;
void initialiseStudent(Student * s_ptr){
    s_ptr-&gt;GetSID();               
    s_ptr-&gt;GetName();
    s_ptr-&gt;GetPhone();
    s_ptr-&gt;GetAddress();
}

int main(){
  char go;                    //to control looping
  do  {                          //Start loop so can repeat entry of 5 students 
    Student s1;                    //instantiate student
    initialiseStudent(&amp;s1)   // and initialise
    Student s2;                    // likewise for 4 more
    initialiseStudent(&amp;s2) 
    Student s3;                    
    initialiseStudent(&amp;s3)   
    Student s4;                    
    initialiseStudent(&amp;s4)
    Student s5;                    
    initialiseStudent(&amp;s5)
    s1.Show();                       //show the student info for each one
    s2.Show();
    s3.Show();
    s4.Show();
    s5.Show();
    cout &lt;&lt; &quot;Do you wish to continue? (Y) or (N)o &quot;;  //prompt for end of data entry
    cin &gt;&gt; go;                                         //read input, compare to see if stop
    while(cin.get()!=  '\n');         // flush input buffer
  }   while ((go == 'y') ||(go == 'Y'));              //test for quitting value
  return 0;
}
</pre>
<p>Note that I have removed the unused counter. Much more
important, I have factored out the process of initialising student
data. When I come to deal with the class <tt class=
"classname">Student</tt> I will think about changing that function
to a member function of <tt class="classname">Student</tt>. I will
also give consideration to naming conventions.</p>
<p>Look at the way I flush the input buffer. I think that is well
worth remembering, but please do not turn it into a macro. However
using an inline function has advantages. Perhaps:</p>
<pre class="programlisting">
inline void flushInput(istream &amp; input) { while(input.get() != ''\n';}
</pre>
<p>meets the need. It documents the activity and makes it available
for all <tt class="classname">istream</tt> objects.</p>
<p>Next let me redo <tt class="function">main()</tt> assuming the
student has now learnt about arrays.</p>
<pre class="programlisting">
int main(){
  do  {                                //Start loop to get data in blocks of 5 students
    Student s[5];                 //instantiate array of five students
for(int i = 0; i&lt;5; ++i) initialiseStudent(s+i);
for(int i = 0; i&lt;5; ++i) s[i].show();
    cout &lt;&lt; &quot;Do you have another five to do? (Y)es or (N)o &quot;;
    char getMore;                    // moved to point of first use
    cin &gt;&gt; getMore;                                   
    flushInput(cin);            
  }   while ((getMore== 'y') ||(getMore== 'Y'));            
  return 0;  
}
</pre>
<p>The only thing that makes me uncomfortable with this code is the
pointer arithmetic for the argument to <tt class=
"function">initialiseStudent</tt>. Contrast that with the call of
the <tt class="function">show()</tt> function and we begin to see
how member functions can clean up code.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e79" id="d0e79"></a>A Header for
Student</h2>
</div>
<p>Now let me have a look at the header file. In working on this I
will want to limit the changes to the application code. Here is the
original:</p>
<pre class="programlisting">
class Student
// a class for organizing student information
{
public:
  Student();                        //constructor
  void GetSID();                //allows entry of student ID  
  void GetName();             //allows user to enter student name  
  void GetPhone();            //allows user to enter phone number  
  void GetAddress();         //allows user to enter address  
  void Show();                    //displays student info
private:
  char number[7];              //for student ID
  char phone[13];              //for student phone number
  char name[30];               //for student name
  char address1[30];         //for student's street address
  char address2[35];         //for city, state and zip
};
</pre>
<p>One problem with this code is that it is non-idiomatic. C
programmers use get-functions in this way, C++ programmers do not.
I am going to skip over whether this class should be value based
(have publicly available copy constructor and copy assignment). In
addition my design is going to be simplistic. In other words I am
not trying to write production code nor the kind of code that and
experienced programmer might.</p>
<pre class="programlisting">
#ifndef STUDENT_H
#define STUDENT_H      // standard sentinel to prevent multiple inclusion 
// class for acquiring student information
class Student {
public:
  Student();
  Student &amp; initialiseStudent();
  Student const &amp; displayStudentData(ostream &amp; output) const;
  void Show() const { displayStudentData(cin); }
protected:
  Student &amp; id()
  Student &amp; phone()
  Student &amp; name()
  Student &amp; address()
private:
  enum MaxLengths { id_len = 7, phone_len = 13, name_len =30, addr1_len =30, addr2_len =35};
  char id_m[id_len];
  char phone_m[phone_len];
  char name_m[name_len];
  char address1_m[addr1_len];
  char address2_m[addr2_len];
};
#endif     // end of conditional inclusion
</pre>
<p>The first thing you will notice is that I have added an industry
standard sentinel to ensure that this file is not multiply included
into some other file. Multiple inclusion would cause redefinition
errors.</p>
<p>I guess the instructor has never said anything about <tt class=
"literal">const</tt> member functions. However he should have done
because it is important to develop the correct habits right from
the start. Even if the explanation is very brief. Any member
function that does not conceptually modify the state of an object
should be qualified as <tt class="literal">const</tt> (by placing
<tt class="literal">const</tt> after the closing parenthesis for
the parameter list.</p>
<p>This is not the place to explain the return type for member
functions, but there are good reasons for replacing <tt class=
"type">void</tt> returns with references or <tt class=
"literal">const</tt> references to the class type.</p>
<p>I do not want applications to rely on being able to change
individual pieces of data so I have made those functions <tt class=
"literal">protected</tt> (that will make more sense when the course
moves on to inheritance)</p>
<p>I have provided a new function to write the data for a student
from an <tt class="classname">istream</tt>, and then defined
<tt class="function">show()</tt> to call that function with
<tt class="classname">cin</tt>. The advantage of the new function
is that you now have something that can be used when you want to
write the data to a file, send it to a printer etc.</p>
<p>Now why do you think I have provided that <tt class=
"literal">enum</tt>? It follows the rule that information should
only be provided once. If, at some later stage, you decide you need
to provide more space for the telephone number you only need to
change the value provided in that <tt class="literal">enum</tt> for
<tt class="varname">phone_len</tt>. Again, this kind of idiom can
be introduced early with a full explanation to follow later. You do
not need to know about enumerated types to use this idiom
correctly. It is <tt class="literal">private</tt> because I do not
want other code to rely on these values.</p>
<p>Now I can go back to the application and remove <tt class=
"function">initialiseStudent()</tt> and change the line that uses
it in <tt class="function">main()</tt> to: <tt class=
"literal">for(int i = 0; i&lt;5; ++i)
s[i].initialiseStudent();</tt></p>
<p>When the course has covered default parameters <tt class=
"function">initialiseStudent()</tt> can be enhanced to work from
other streams while still retaining the same default behaviour we
are supplying here.</p>
<p>My definition of class <tt class="classname">Student</tt> is a
bit longer than the original but it has more potential for
development and is closer to the way good programmers write.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e161" id="d0e161"></a>Student
Implementation</h2>
</div>
<p>Here is the original:</p>
<pre class="programlisting">
#include &lt;iostream&gt;
#include &lt;string&gt;
#include &quot;student.h&quot;
using namespace std;
//definitions of member functions for class Student
Student::Student()         //Constructor
{   }
void Student::GetSID()    //Get student number
{
  char num[7];
  cout &lt;&lt; &quot;Enter six digit student number &quot;;     //prompt for student number
  cin.getline (num, 7);                            //read the input
  strcpy (number, num);                            //copy input to data member
}  
</pre>
<p>&lt;3 Similar functions snipped&gt;</p>
<pre class="programlisting">
void Student::Show()    //display the student info 
{
  cout &lt;&lt;&quot;\n\n&quot;;
  cout &lt;&lt; &quot;Student number        &quot; &lt;&lt; number &lt;&lt;&quot;\n&quot;;   //show the student number
  cout &lt;&lt; &quot;Name:                 &quot; &lt;&lt; name &lt;&lt;&quot;\n&quot;;                   //show the name  
  cout &lt;&lt; &quot;Phone number          &quot; &lt;&lt; phone &lt;&lt;&quot;\n&quot;;      //show the phone number  
  cout &lt;&lt; &quot;Street address        &quot; &lt;&lt; address1 &lt;&lt;&quot;\n&quot;;   //show street address  
  cout &lt;&lt; &quot;City, state, and zip  &quot; &lt;&lt; address2 &lt;&lt; &quot;\n&quot;;  //show city, state. etc
  cout &lt;&lt; endl;
}
</pre>
<p>Again we have a chance to factor out common code. Look at the
following function. I have declared it as static so that it is
limited to the current file. I am well aware that using such things
as unnamed namespaces are preferred but if students are being
taught by instructors that are half as bad as the one in question
here, we need to keep to as little new material as we can while
doing a reasonable job.</p>
<pre class="programlisting">
static void init_array_of_char (char const * prompt,  char * destination,  size_t length) {
  cout &lt;&lt; prompt;
  cin.getline(destination, length);
  while (cin.get() != '\n');   // flush input buffer
}
</pre>
<p>Now my four protected functions can be written as:</p>
<pre class="programlisting">
Student &amp; Student::id(){
  init_array_of_char(&quot;What is the student number?&quot;, id_m, id_len);
  return *this;
}
Student &amp; Student::phone(){
  init_array_of_char(&quot;What is the student's telephone number?&quot;, phone_m, phone_len);
  return *this;
}
Student &amp; Student::name(){
  init_array_of_char(&quot;What is the student's name&quot;, name_m, name_len);
  return *this;
}
Student &amp; Student::address(){
  init_array_of_char(&quot;What is the student's street address&quot;, address1_m, addr1_len);
  init_array_of_char(&quot;What is the student's City, State and zip-code&quot;, address2_m, addr2_len);
  return *this;
}
</pre>
<p>Now let me show how easy it is to use these to provide
<tt class="function">initialiseStudent()</tt></p>
<pre class="programlisting">
Student &amp; Student::initialiseStudent(){
  return id(), phone(), name(),  address();
}
</pre>
<p>That is a comma separated list so each function is evaluated in
sequence and the return value of the last one is returned as the
value of the function.</p>
<p>The next thing to consider is that constructor. The problem is
that it leaves the object in an uninitialised state. If the
<tt class="function">show()</tt> function is ever called on an
uninitialised <tt class="classname">Student</tt> object you may get
bizarre output as the arrays will hold garbage (and may not even be
zero terminated. It would be much better to use the following
definition:</p>
<pre class="programlisting">
Student::Student():id_m(&quot;&quot;), phone_m(&quot;&quot;), name_m(&quot;&quot;), address1_m(&quot;&quot;), address2_m(&quot;&quot;) {}
</pre>
<p>to ensure that all the arrays have been set as empty
strings.</p>
<p>And finally let me deal with my <tt class=
"function">displayStudentData()</tt>:</p>
<pre class="programlisting">
Student const &amp; Student::displayStudentData(istream &amp; input)  {
  input    &lt;&lt;&quot;\n\n&quot;
         &lt;&lt; &quot;Student number :      &quot; &lt;&lt; number &lt;&lt;&quot;\n&quot;
        &lt;&lt; &quot;Name:                 &quot; &lt;&lt; name &lt;&lt;&quot;\n&quot;           
        &lt;&lt; &quot;Phone number          &quot; &lt;&lt; phone &lt;&lt;&quot;\n&quot;  
         &lt;&lt; &quot;Street address        &quot; &lt;&lt; address1 &lt;&lt;&quot;\n&quot; 
        &lt;&lt; &quot;City, state, and zip  &quot; &lt;&lt; address2 &lt;&lt; &quot;\n&quot;
        &lt;&lt; endl;
}
</pre>
<p>Note that the way I have developed my <tt class=
"classname">Student</tt> class means that all the data, its capture
and display have been encapsulated. The application neither knows,
nor has any need to know, exactly what data is used and how it is
structured. If I were teaching this course I would want to strongly
emphasise this (perhaps by asking the student to add a datum, or
separate city from state and zip code.</p>
<p>I think that just about wraps it up.</p>
<p>I am going to ask Francis to send this column to the original
code writer and invite her questions and comments. If she sends
those back to Francis in time I will try to add a response to this
column.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e216" id="d0e216"></a>Addendum</h2>
</div>
<p>Francis forwarded the student's first response to the above. Her
comments are in italic Times Roman while mine are in Arial. I first
added the following injunction:</p>
<p>OK. I hope this helps a little. Though as Steve Heller says in
'Whose Afraid of C++' programming has to be studied, you cannot
expect to learn by simply reading once.</p>
<p>Now on with my comments on your response.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e225" id="d0e225"></a>Annotated
Response</h3>
</div>
<div class="variablelist">
<dl>
<dt><span class="term">Student</span></dt>
<dd>
<p>I do appreciate the critique of my admittedly inferior code. I
suspect that advice from people as kind as you will be my best
educational resource in this class.</p>
</dd>
<dt><span class="term">The Harpist</span></dt>
<dd>
<p>Thanks. But it isn't all one way. The problems faced by people
such as you can help to enlighten others because it helps me and
people like me answer the real problems you have.</p>
</dd>
<dt><span class="term">Student</span></dt>
<dd>
<p>You are correct; we have not yet had strings, arrays, pointers,
functions other than the function signature, const as anything
other than a simple data type, references, or any explanation of
naming conventions. I used my old Pascal naming conventions as my
guide. Please, where might I reference the naming conventions?
Also, all data members were required to be private in this
assignment.</p>
</dd>
<dt><span class="term">The Harpist</span></dt>
<dd>
<p>I find this information deeply shocking. Perhaps the instructor
expects experienced students to find out for themselves. But I do
not find this reasonable in a course that does not require any
prior programming experience.</p>
<p>You know more about functions than you think you do because you
have been writing member functions. Member functions have a special
characteristic in that they are called by using the dot operator on
an object of the correct type (and that object becomes an argument
to the function that does not appear in the argument list - because
we sometimes want to refer to that argument, C++ has a keyword
<tt class="literal">this</tt>. Using it generates the address of
the object in question. Prefixing a pointer (address) value with an
asterisk results in the object itself. So <tt class=
"literal">this</tt> is a pointer to the object calling the member
function on itself and <tt class="literal">*this</tt> will be the
object itself (which can be bound to a reference.)</p>
<p>When an identifier is <tt class="literal">const</tt> qualified
it means that the object identified cannot be changed through use
of this identifier (it might be changed through some other route,
if there is one). If we want to <tt class="literal">const</tt>
qualify <tt class="literal">*this</tt> (in other words the member
function is guaranteed not to change the state of the object
calling it) the <tt class="literal">const</tt> is placed after the
closing parenthesis of the function declaration/definition.</p>
<p>Naming conventions are hard to come by. To the best of my
knowledge there is no definitive source for these. Many writers use
the conventions they learnt as C programmers. These are not really
appropriate to C++. For example 'get' functions in C were always
functions that got their values from some form of input. In C++
they are generally member functions that make the value of some
attribute of an object available. Even this usage is beginning to
die out in C++ as other idioms are being developed.</p>
<p>If you look at my code you will see (I hope) that my data is
<tt class="literal">private</tt>. This is one absolute guideline
(in other words there is no reason for ever breaking it) when
writing Object-Oriented code, data is always <tt class=
"literal">private</tt>. What I did was tighten the access to that
data further by making my write access functions <tt class=
"literal">protected</tt>. Until you study inheritance there is no
difference between <tt class="literal">private</tt> and <tt class=
"literal">protected</tt>, but when you get into inheritance you
will appreciate the difference. Unfortunately you will also come
across an evil habit of some writers to advocate making data
<tt class="literal">protected</tt> rather than <tt class=
"literal">private</tt>. However good the rest of their advice this
piece should be rigidly ignored.</p>
</dd>
<dt><span class="term">Student</span></dt>
<dd>
<p>The counter was inadvertently not deleted. I originally wanted
to use the counter to help instantiate the student objects and call
the member functions so I could write it once and loop it. C++
wouldn't let me use a variable in an object name or function call,
i.e. <tt class="literal">student s(counter); s(counter)
.GetSID;</tt> . I didn't have the tools to use a better method,
like yours with pointers and references. Pointers are the last
thing we will learn this term.</p>
</dd>
<dt><span class="term">The Harpist</span></dt>
<dd>
<p>Your intent was right on the mark. What you were missing was how
to declare an array in C++. What you needed was to know that:</p>
<pre class="programlisting">
Student s[5];
</pre>
<p>declares an array of five <tt class="classname">Student</tt>
objects that are accessible as <tt class="literal">s[0], s[1], ...,
s[4]</tt>. C/C++ always indexes arrays from 0. Armed with that you
would have enough to generate and initialise data objects. However
you do have to decide how many you want before you start (when you
learn about (probably have to teach yourself about) C++ vectors,
deques and lists you will find that you can have collections that
grow as needed.</p>
<p>On the subject of pointers, if your course was making use of the
modern C++ components such as <tt class="classname">string</tt> and
<tt class="classname">vector</tt> I think leaving discussion of
pointers till late makes good sense. However if you have to use
arrays in general and specifically arrays of <tt class=
"type">char</tt> (to provide string behaviour) you must be given
some early information. Not doing so is asking you to write code
with one hand tied behind your back.</p>
</dd>
<dt><span class="term">Student</span></dt>
<dd>
<pre class="programlisting">
[ void initialiseStudent(Student * s_ptr){   ]
</pre>
<p>In the above line you have declared a function <tt class=
"function">initialiseStudent</tt>, with a type of data I don't
understand, but I'm certain it's a pointer. What is the &quot;*&quot; for? If
a &quot;&amp;&quot; is a reference to a memory location, as I heard in my
last lecture, then how does a pointer differ from a reference?</p>
</dd>
<dt><span class="term">The Harpist</span></dt>
<dd>
<p><tt class="function">initialiseStudent</tt> returns a <tt class=
"type">void</tt> (which effectively means it is like a Pascal
procedure) and takes a single argument of type pointer to
<tt class="classname">Student</tt>. That is what that asterisk
means. Denis Ritchie when he invented C experimented with a
declaration syntax which Bjarne Stroustrup has described as a
failure (Bjarne can say things like this because Denis is a
colleague). C++ for various pragmatic reasons adopted C as its base
and changed as little as possible. One of Denis Ritchie's
principles was that declarations should look like uses so the
parameter declaration can be read in two ways:</p>
<p><tt class="varname">s_ptr</tt> is a pointer to a <tt class=
"classname">Student</tt> (and so stores the address of a <tt class=
"classname">Student</tt> object)</p>
<p><tt class="varname">*s_ptr</tt> is a <tt class=
"classname">Student</tt> object whose address is found in
<tt class="varname">s_ptr</tt>.</p>
<p>C had no reference types but it was clearly inefficient to pass
arrays by value so pointers were used together with syntax rules to
provide a reference like mechanism for arrays. A pointer differs
from a reference largely through some syntactic sugar (when you
gain more experience you will find that to be something of a
simplification).</p>
</dd>
<dt><span class="term">Student</span></dt>
<dd>
<p>Other assorted questions: What is &quot;static&quot;, and what does it do?
&quot;Enum&quot; sounds and looks like what I learned in Pascal as an
enumerated data type. It is, then, a data type? Our instructor has
not mentioned it yet.</p>
</dd>
<dt><span class="term">The Harpist</span></dt>
<dd>
<p>The keyword <tt class="literal">static</tt> in C++ has far too
many meanings. However in the context of a file scope declaration
it means that the name being declared is only available for use in
the same file and will not cause problems at link time because
other files use an identical name with a different definition.
&quot;<tt class="literal">enum</tt>&quot; is a user-defined type (so are
<tt class="literal">class</tt>, <tt class="literal">struct</tt> and
<tt class="literal">union</tt>) that will be based on an underlying
integer type. Within the braces that provide the definition you
place a list of identifiers and the values assigned to them (the
full rule is more complicated, but this will do for now). You can
create variables of an enum type and you can use the enumerated
identifiers to provide values. These values will implicitly convert
to the underlying type if necessary but the conversion the other
way must be explicit. So:</p>
<pre class="programlisting">
enum Colour { red =1, green = 2, blue = 4};
int main (){
  Colour c = red; // OK
  int i = blue;   // OK
  Colour c = 1;  // error
  Colour c = Colour(3); // OK
  i = blue + red;  //OK
  c = blue + red; // error, no operators available for enum Colour
  c = Colour(blue+red); // OK, convert to ints, add and convert back 
}
</pre></dd>
<dt><span class="term">Student</span></dt>
<dd>
<pre class="programlisting">
[Student const &amp; displayStudentData(ostream &amp; output) const;]
</pre>
<p>Could you repeat the above line in English? I have no clue (well
one clue, it's a function).</p>
</dd>
<dt><span class="term">The Harpist</span></dt>
<dd>
<p><tt class="function">displayStudentData</tt> is a <tt class=
"type">const Student</tt> (it only has read access to the
<tt class="classname">Student</tt> object) member function that
takes an argument (by reference) of type <tt class=
"classname">ostream</tt> and returns a read only reference to an
object of type <tt class="classname">Student</tt></p>
</dd>
<dt><span class="term">Student</span></dt>
<dd>
<pre class="programlisting">
[static void init_array_of_char (char const * prompt,  char * destination,  size_t length)]
</pre>
<p>Okay, in this line you are declaring an array. But, again, I
don't recognise the parameter data types again. All stuff I haven't
had yet.</p>
</dd>
<dt><span class="term">The Harpist</span></dt>
<dd>
<p>Not quite. <tt class="function">init_array_of_char</tt> is a
function returning nothing (i.e. it is a procedure) that is local
to the file in which it is declared/defined (hence the <tt class=
"literal">static</tt> qualifier) that takes three parameters. The
first (<i class="parameter"><tt>prompt</tt></i>) is a pointer to a
non-modifiable <tt class="type">char</tt> (at call time this will
be bound to the start of an array of <tt class="type">char</tt>,
that is a C-style string). The second parameter (<i class=
"parameter"><tt>destination</tt></i>) is a pointer to a modifiable
<tt class="type">char</tt> (at call time this is bound to the start
of an array of <tt class="type">char</tt> that can be modified
-written to). The third parameter (<i class=
"parameter"><tt>length</tt></i>) is of an opaque type (in this case
some form of integer) that the implementation uses to measure the
sizes of objects. In this case we will use it to tell the function
how big the array is that is pointed to by the second
parameter.</p>
</dd>
<dt><span class="term">Student</span></dt>
<dd>
<p>Thank you for a better way of flushing the buffer. Four days
after I emailed the instructor asking about that problem he replied
and said it was a bug and shouldn't be in Visual C++6, and was I
sure I bought version 6? He also said to use <tt class=
"function">strcpy</tt> to assign the keyboard input to the data
member. I'm pretty sure it's not a bug since CodeWarrior does the
same thing, but I'd like to know why it does what it does.</p>
</dd>
<dt><span class="term">The Harpist</span></dt>
<dd>
<p>As we see, there is no need to use <tt class=
"function">strcpy()</tt> as we can use <tt class=
"function">getline()</tt> to read the data straight to its
destination. <tt class="function">getline()</tt> should read the
delimiter (by default, the end of line character) and discard it.
If VC++ is not doing that, it is wrong. I must admit that I am
surprised by this bug. CodeWarrior may be doing the same as VC++
for compatibility reasons. Francis tells me that MetroWerks plans
to provide a VC++ compatibility switch in the next release (Pro 5)
so that programmers can choose between coding the right way and
coding the MSVC++ way&#9786;.</p>
</dd>
</dl>
</div>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
