C++ Essentials
Sharam Hekmat
PragSoft Corporation
www.pragsoft.comContents
ContentsvPrefacex
Exercises16
Exercises29
www.pragsoft.comContentsv
Exercises44
Scope Operator50
Default Arguments60
Exercises64
Exercises80
viC++ EssentialsCopyright 2005 PragSoft
Exercises113
Type Conversion121
Overloading []129
Overloading ++ and -142
Exercises143
www.pragsoft.comContentsvii
Exercises168
Exercises187
Exercises195
viiiC++ EssentialsCopyright 2005 PragSoft Exercises217
Preface
Since its introduction less than a decade ago, C++ has experienced growingacceptance as a practical object-oriented programming language suitable forteaching, research, and commercial software development. The language has alsorapidly evolved during this period and acquired a number of new features (e.g.,templates and exception handling) which have added to its richness.
This book serves as an introduction to the C++ language. It teaches how toprogram in C++ and how to properly use its features. It does not attempt to teachobject-oriented design to any depth, which I believe is best covered in a book in itsown right.
In designing this book, I have strived to achieve three goals. First, to producea concise introductory text, free from unnecessary verbosity, so that beginners candevelop a good understanding of the language in a short period of time. Second, Ihave tried to combine a tutorial style (based on explanation of concepts throughexamples) with a reference style (based on a flat structure). As a result, eachchapter consists of a list of relatively short sections (mostly one or two pages), withno further subdivision. This, I hope, further simplifies the readers task. Finally, Ihave consciously avoided trying to present an absolutely complete description ofC++. While no important topic has been omitted, descriptions of some of the minoridiosyncrasies have been avoided for the sake of clarity and to avoidoverwhelming beginners with too much information. Experience suggests that anysmall knowledge gaps left as a result, will be easily filled over time through selfdiscovery.
Intended Audience
This book introduces C++ as an object-oriented programming language. Noprevious knowledge of C or any other programming language is assumed. Readers
xC++ EssentialsCopyright 2005 PragSoft who have already been exposed to a high-level programming language (such as Cor Pascal) will be able to skip over some of the earlier material in this book.
Although the book is primarily designed for use in undergraduate computerscience courses, it will be equally useful to professional programmers and hobbyistswho intend to learn the language on their own. The entire book can be easilycovered in 10-15 lectures, making it suitable for a one-term or one-semestercourse. It can also be used as the basis of an intensive 4-5 day industrial trainingcourse.
Structure of the Book
The book is divided into 12 chapters. Each chapter has a flat structure, consistingof an unnumbered sequence of sections, most of which are limited to one or twopages. The aim is to present each new topic in a confined space so that it can bequickly grasped. Each chapter ends with a list of exercises. Answers to all of theexercises are provided in an appendix. Readers are encouraged to attempt as manyof the exercises as feasible and to compare their solutions against the onesprovided.
For the convenience of readers, the sample programs presented in this book(including the solutions to the exercises) and provided in electronic form.
1.Preliminaries
This chapter introduces the basic elements of a C++ program. We will use simpleexamples to show the structure of C++ programs and the way they are compiled.Elementary concepts such as constants, variables, and their storage in memory willalso be discussed.
The following is a cursory description of the concept of programming for thebenefit of those who are new to the subject.
Programming
A digital computer is a useful tool for solving a great variety of problems. Asolution to a problem is called an algorithm; it describes the sequence of steps tobe performed for the problem to be solved. A simple example of a problem and analgorithm for it would be:
Problem:Sort a list of names in ascending lexicographic order.Algorithm:Call the given list list1; create an empty list, list2, to hold the sorted list.Repeatedly find the smallest name in list1, remove it from list1, andmake it the next entry of list2, until list1 is empty.
An algorithm is expressed in abstract terms. To be intelligible to a computer, itneeds to be expressed in a language understood by it. The only language reallyunderstood by a computer is its own machine language. Programs expressed inthe machine language are said to be executable. A program written in any otherlanguage needs to be first translated to the machine language before it can beexecuted.
A machine language is far too cryptic to be suitable for the direct use ofprogrammers. A further abstraction of this language is the assembly languagewhich provides mnemonic names for the instructions and a more intelligible notationfor the data. An assembly language program is translated to machine language by atranslator called an assembler.
Even assembly languages are difficult to work with. High-level languages suchas C++ provide a much more convenient notation for implementing algorithms.They liberate programmers from having to think in very low-level terms, and helpthem to focus on the algorithm instead. A program written in a high-level languageis translated to assembly language by a translator called a compiler. The assemblycode produced by the compiler is then assembled to produce an executableprogram.
A Simple C++ Program
Listing 1.1 shows our first C++ program, which when run, simply outputs themessage Hello World.
Listing 1.1 1#include
2int main (void)
3{
4cout << "Hello World\n";
5}
Annotation1This line uses the preprocessor directive#include to include the contentsof the header file iostream.h in the program. Iostream.h is a standardC++ header file and contains definitions for input and output.
2This line defines a function called main. A function may have zero or moreparameters ; these always appear after the function name, between a pair ofbrackets. The word void appearing between the brackets indicates that mainhas no parameters. A function may also have a return type ; this alwaysappears before the function name. The return type for main is int (i.e., aninteger number). All C++ programs must have exactly one main function.Program execution always begins from main.
3This brace marks the beginning of the body of main.
4This line is a statement. A statement is a computation step which mayproduce a value. The end of a statement is always marked with a semicolon(;). This statement causes the string"Hello World\n" to be sent to thecout output stream. A string is any sequence of characters enclosed indouble-quotes. The last character in this string (\n) is a newline characterwhich is similar to a carriage return on a type writer. A stream is an objectwhich performs input or output. Cout is the standard output stream in C++(standard output usually means your computer monitor screen). The symbol<output operator which takes an output stream as its left operand andan expression as its right operand, and causes the value of the latter to besent to the former. In this case, the effect is that the string "Hello World\n"is sent to cout, causing it to be printed on the computer monitor screen.