Datasheet
Nonstandard Strings
There are several reasons why many C++ programmers don’t use C++-style strings. Some programmers
simply aren’t aware of the
string type because it was not always part of the C++ specification. Others
have discovered over the years that the C++
string doesn’t provide the behavior they need and have
developed their own string type. Perhaps the most common reason is that development frameworks and
operating systems tend to have their own way of representing strings, such as the
CString class in
Microsoft’s MFC. Often, this is for backward compatibility or legacy issues. When starting a project in
C++, it is very important to decide ahead of time how your group will represent strings.
References
The pattern for most functions is that they take in zero or more parameters, do some calculations, and
return a single result. Sometimes, however, that pattern is broken. You may be tempted to return two
values or you may want the function to be able to change the value of one of the variables that were
passed in.
In C, the primary way to accomplish such behavior is to pass in a pointer to the variable instead of the
variable itself. The only problem with this approach is that it brings the messiness of pointer syntax into
what is really a simple task. In C++, there is an explicit mechanism for “pass-by-reference.” Attaching
&
to a type indicates that the variable is a reference. It is still used as though it was a normal variable, but
behind the scenes, it is really a pointer to the original variable. Below are two implementations of an
addOne() function. The first will have no effect on the variable that is passed in because it is passed by
value. The second uses a reference and thus changes the original variable.
void addOne(int i)
{
i++; // Has no real effect because this is a copy of the original
}
void addOne(int& i)
{
i++; // Actually changes the original variable
}
The syntax for the call to the addOne() function with an integer reference is no different than if the func-
tion just took an integer.
int myInt = 7;
addOne(myInt);
Exceptions
C++ is a very flexible language, but not a particularly safe one. The compiler will let you write code
that scribbles on random memory addresses or tries to divide by zero (computers don’t deal well with
infinity). One of the language features that attempts to add a degree of safety back to the language is
exceptions.
23
A Crash Course in C++
04_574841 ch01.qxd 12/15/04 3:39 PM Page 23










