1.1

1.1 A Brief History of C++
In 1970 two programmers, Brian Kernighan and Dennis Ritchie, created a new language called C. (The name came about because C was preceded by the old programming language they were using called B.) C was designed with one goal in mind: writing operating systems. The language was extremely simple and flexible and soon was used for many different types of programs. It quickly became one of the most popular programming languages in the world.

C had one major problem, however. It was a procedure-oriented language. This meant that in designing a typical C program, the programmer would start by describing the data and then write procedures to manipulate that data.

Programmers eventually discovered that it made a program clearer and easier to understand if they were able to take a bunch of data and group it together with the operations that worked on that data. Such a grouping is called an object or class. Designing programs by designing classes is known as object-oriented design (OOD).

In 1980 Bjarne Stroustrup started working on a new language, called "C with Classes." This language improved on C by adding a number of new features, the most important of which was classes. This language was improved, augmented, and finally became C++.

C++ owes its success to the fact that it allows the programmer to organize and process information more effectively than most other languages. Also, it builds on the work already done with the C language. In fact, most C programs can be transformed into C++ programs with little trouble. These programs usually don't use all the new features of C++, but they do work. In this way, C++ allows programmers to build on an existing base of C code.


 

What is C++?
C++ is a generalpurpose programming language with a bias towards systems programming that
– is a better C,
– supports data abstraction,
– supports objectoriented
programming, and
– supports generic programming.
This chapter explains what this means without going into the finer details of the language definition.
Its purpose is to give you a general overview of C++ and the key techniques for using it, not
to provide you with the detailed information necessary to start programming in C++.
If you find some parts of this chapter rough going, just ignore those parts and plow on. All will
be explained in detail in later chapters. However, if you do skip part of this chapter, do yourself a
favor by returning to it later.
Detailed understanding of language features – even of all features of a language – cannot compensate
for lack of an overall view of the language and the fundamental techniques for using it.

1.2 Programming Paradigms
Objectoriented programming is a technique for programming – a paradigm for writing ‘‘good’’
programs for a set of problems. If the term ‘‘objectoriented programming language’’ means anything,
it must mean a programming language that provides mechanisms that support the objectoriented
style of programming well.
There is an important distinction here. A language is said to support a style of programming if
it provides facilities that make it convenient (reasonably easy, safe, and efficient) to use that style.
A language does not support a technique if it takes exceptional effort or skill to write such programs;
it merely enables the technique to be used. For example, you can write structured programs
in Fortran77 and objectoriented programs in C, but it is unnecessarily hard to do so because these
languages do not directly support those techniques.
Support for a paradigm comes not only in the obvious form of language facilities that allow
direct use of the paradigm, but also in the more subtle form of compiletime
and/or runtime checks against unintentional deviation from the paradigm. Type checking is the most obvious example of
this; ambiguity detection and runtime checks are also used to extend linguistic support for paradigms.
Extralinguistic facilities such as libraries and programming environments can provide further
support for paradigms.
One language is not necessarily better than another because it possesses a feature the other does
not. There are many examples to the contrary. The important issue is not so much what features a
language possesses, but that the features it does possess are sufficient to support the desired programming
styles in the desired application areas:
[1] All features must be cleanly and elegantly integrated into the language.
[2] It must be possible to use features in combination to achieve solutions that would otherwise
require extra, separate features.
[3] There should be as few spurious and ‘‘specialpurpose’’
features as possible.
[4] A feature’s implementation should not impose significant overheads on programs that do
not require it.
[5] A user should need to know only about the subset of the language explicitly used to write a
program.
The first principle is an appeal to aesthetics and logic. The next two are expressions of the ideal of
minimalism. The last two can be summarized as ‘‘what you don’t know won’t hurt you.’’
C++ was designed to support data abstraction, objectoriented
programming, and generic programming
in addition to traditional C programming techniques under these constraints. It was not
meant to force one particular programming style upon all users.
The following sections consider some programming styles and the key language mechanisms
supporting them. The presentation progresses through a series of techniques starting with procedural
programming and leading up to the use of class hierarchies in objectoriented
programming and
generic programming using templates. Each paradigm builds on its predecessors, each adds something
new to the C++ programmer’s toolbox, and each reflects a proven design approach.
The presentation of language features is not exhaustive. The emphasis is on design approaches
and ways of organizing programs rather than on language details. At this stage, it is far more
important to gain an idea of what can be done using C++ than to understand exactly how it can be
achieved.

1.2 C++ Organization
C++ is designed as a bridge between the programmer and the raw computer. The idea is to let the programmer organize a program in a way that he can easily understand. The compiler then translates the language into something the machine can use.

Computer programs consist of two main parts: data and instructions. The computer imposes little or no organization on these two parts. After all, computers are designed to be as general as possible. The idea is for the programmer to impose his or her own organization on the computer and not the other way around.

The data in a computer is stored as a series of bytes. C++ organizes those bytes into useful data. Data declarations are used by the programmer to describe the information he or she is working with. For example:

int total; // Total number accounts
tells C++ that you want to use a section of the computer's memory to store an integer named total. You can let the compiler decide what particular bytes of memory to use; that's a minor bookkeeping detail you don't need to worry about.

The variable total is a simple variable . It can hold only one integer and describe only one total. A series of integers can be organized into an array. Again, C++ will handle the details, imposing that organization on the computer's memory.

int balance[100]; // Balance (in cents) for all 100 accounts
Finally, there are more complex data types. For example, a rectangle might have a width, a height, a color, and a fill pattern. C++ lets you organize these four attributes into one group called a structure.

struct rectangle {
int width; // Width of rectangle in pixels
int height; // Height of rectangle in pixels
color_type color; // Color of the rectangle
fill_type fill; // Fill pattern
};
However, data is only one part of a program; you also need instructions. As far as the computer is concerned, it knows nothing about the layout of the instructions. It knows only what it's doing for the current instruction and where to get the next instruction.

C++ is a high-level language. It lets you write a high-level statement such as:

area = (base * height) / 2.0; // Compute area of triangle
The compiler translates this statement into a series of cryptic machine instructions. This sort of statement is called an assignment statement. It is used to compute and store the value of an arithmetic expression.

You can also use control statements to control the order of processing. Statements such as the if and switch statements enable the computer to make simple decisions. Statements can be repeated by using looping statements such as while and for.

Groups of statements can be wrapped to form functions. Thus you only need to write a general-purpose function to draw a rectangle once, and you can reuse that function whenever you want to draw a new rectangle. C++ provides a rich set of standard functions that perform common functions such as searching, sorting, input, and output. A set of related functions can be grouped together to form a module, and modules are linked to form programs.

One of the major goals of the C++ language is to organize instructions into reusable components. After all, you can write programs much faster if you "borrow" most of your code from somewhere else. Groups of reusable modules can be combined into a library. For example, if you need a sort routine, you can use the standard function qsort from the library and link it into your program.

A computer divides the world into data and instructions. For a long time, high-level languages such as C kept that dividing line in place. In C you can define data or write instructions, but you can't combine the two.

One of C++'s major innovations is the idea of combining data and instructions together in a construct called a class or object. Object-oriented programming allows you to group data with the operations that can be performed on that data. This concept is taken a step further in C++ by letting you derive new classes from existing ones.

This last feature is extremely powerful. It allows you to build complex classes on top of smaller, simpler ones. It also allows you to define a basic, abstract class and then derive specific classes from it. For example, an abstract class of shape might be used to define the shapes rectangle, triangle, and circle.

Organization is the key to writing good programs. In this book, you know that the table of contents is in the front and the index is in the back, because that's the way books are organized. Organization makes this book easier to use.

The C++ language lets you organize your programs using a simple yet powerful syntax. This book goes beyond the C++ syntax and teaches you style rules that enable you to create highly readable and reliable programs. By combining a powerful syntax with good programming style, you can create powerful programs that perform complex and wonderful operations.

2.1

Assembly language organized programs in a way that was easier for the programmers to understand. However, the program was more difficult for the machine to use. The program had to be translated before the machine could execute it. This was the start of a trend. Programming languages became more and more convenient for programmers to use and started requiring more and more computer time to translate them into something useful for computers.

Over the years a series of high-level languages has been devised. These languages are attempts to let programmers write in something that is easy for them to understand and also precise and simple enough for computers to understand.

Early high-level languages were designed to handle specific types of applications. FORTRAN was designed for number crunching; COBOL, for writing business reports; and PASCAL, for student use. (Many of these languages have far outgrown their initial uses. It is rumored that Nicklaus Wirth has said, "If I had known that PASCAL was going to be so successful, I would have been more careful in its design.")

Later on, Brian Kernighan and Dennis Ritchie developed C and Bjarne Stroustrup turned it into C++.

2.1 Programs from Conception to Execution

C++ programs are written in a high-level language using letters, numbers, and the other symbols you find on a computer keyboard. Computers actually execute a very low-level language called machine code (a series of numbers). So, before a program can be used, it must undergo several transformations.

Programs start out as an idea in a programmer's head. She writes down her thoughts in a file, called a source file or source code, using a text editor. This file is transformed by the compiler into an object file. Next a program called the linker takes the object file, combines it with predefined routines from a standard library, and produces an executable program (a set of machine-language instructions). In the following sections, you'll see how these various forms of the program work together to produce the final program.

Figure 2-2 shows the steps that must be taken to transform a program written in a high-level language into an executable program.

Figure 2-2. Transformation of a high-level language into a program
figs/C++2_0202.gif

Fortunately you don't have to run the compiler, assembler, and linker individually. Most C++ compilers use "wrapper" programs, which determine which tools need to be run and then run them.

Some programming systems go even further and provide the developer with an integrated development environment (IDE). The IDE contains an editor, compiler, linker, project manager, debugger, and more in one convenient package. Both Borland and Microsoft provide IDEs with their compilers.

2.2 Creating a Real Program

Before you can actually start creating your own programs, you need to know how to use the basic programming tools. This section will take you step by step through the process of entering, compiling, and running a simple program.

This section describes how to use two different types of compilers. The first type is the standalone or command-line compiler. This type of compiler is operated from the command line. You type a command, and the compiler turns your source code into an executable program. The other type of compiler is contained in an IDE.

Most Unix systems use command-line compilers. A few IDE-type compilers are available for Unix, but they are rare. On the other hand, almost all the compilers used with Microsoft Windows are part of an IDE. For command-line die-hards, these IDEs contain command-line compilers as well.

2.2.1 Creating a Program Using a Command-Line Compiler

In this section you'll go through the step-by-step process needed to create a program using a command-line compiler. The program you're going to create will display the message "Hello World" on the screen. Instruction is given for using a generic Unix compiler, the Free Software Foundation's g++ compiler, Borland C++, and Microsoft Visual C++.

However, if you are using a Borland or Microsoft compiler, you might want to skip ahead to Section 2.2.2.

Note that, because compilers are continually being improved, the information in this section may not be accurate by the time you read it. As new compilers come out, we'll update this section and post the update on the O'Reilly web site at http://www.oreilly.com/catalog/cplus2.

2.2.1.1 Step 1: Create a place for your program

It is easier to manage things if you create a separate directory for each program you are working on. In this case you'll create a directory called hello to hold your hello program.

In Unix, type:

% mkdir hello  % cd hello

In MS-DOS, type:

C:> MKDIR HELLO  C:> CD HELLO
2.2.1.2 Step 2: Create the program

A program starts out as a text file. Example 2-1 shows the hello program in source form.

Example 2-1. Source for the hello.cpp program
#include <iostream>    int main(  )  {      std::cout << "Hello World\n";      return (0);  }

Use your favorite text editor to enter the program. Your file should be named hello.cpp.

 

Do not use a word-processing program such as Microsoft Word or WordPerfect to write your programs. Word-processing programs add formatting codes to files that confuse the compiler. You must use a text editor, such as the notepad program, that is capable of editing ASCII files.

2.2.1.3 Step 3: Run the compiler

The compiler changes the source file you just created into an executable program. Each compiler has a different command line. The commands for the most popular compilers are listed below.

2.2.1.3.1 Unix CC Compiler (Generic Unix)

Most Unix-based compilers follow the same generic standard. The C++ compiler is named CC. To compile your hello program, you need the following command:

% CC -g -ohello hello.cpp

The -g option enables debugging. (The compiler adds extra information to the program to make it easier to debug.) The switch -ohello tells the compiler that the program is to be called hello, and the final hello.cpp is the name of the source file. See your compiler manual for details on all the possible options. There are several different C++ compilers for Unix, so your command line may be slightly different than is shown here.

2.2.1.3.2 Free Software Foundation's g++ Compiler

The Free Software Foundation, the GNU people, publishes a number of high-quality programs. (See the glossary entry "Free Software Foundation" for information on how to get their software.) Among their offerings is a C++ compiler called g++.

To compile the hello program using the g++ compiler, use the following command line:

% g++ -g -Wall -ohello hello.cpp

The additional switch -Wall turns on all the warnings. When warnings are turned on, the compiler will warn you when it sees questionable code.

2.2.1.3.3 Borland's Turbo C++

Borland International makes a free Microsoft Windows C++ compiler called Borland-C++. This compiler is ideal for learning. The command line for Borland-C++ is:

C:> bcc32 -v -N -w -tWC -ehello hello.cpp

The -v switch tells Borland-C++ to put debugging information in the program. Warnings are turned on by -w and stack checking by -N. The -tWC option tells Borland-C++ to output a "Console Application." That's a program that uses the standard C++ API (as opposed to the Windows API) and uses a MS-DOS console window for its input and output. Finally, -ehello tells Borland-C++ to create a program named hello, and hello.cpp is the name of the source file. See the Borland-C++ reference manual for a complete list of options.

2.2.1.3.4 Microsoft Visual C++ .NET

Microsoft Visual C++ .NET is another C++ compiler for Microsoft Windows. To compile the HELLO program, use the following command line:

C:> cl /FeHELLO /GZ /RTCsuc /Zi /Wall hello.cpp

The /FeHELLO option tells the program to generate a program named HELLO.exe. Runtime checking is enabled by /GZ and /RTCsuc, and debugging is turned on with the /Zi option. All warning messages are enabled by /Wall.[1]

[1] In the prerelease of Microsoft Visual Studio .NET, compilation with /Wall generated a large number of warnings caused by minor problems in Microsoft's own libraries. I expect these problems to be fixed in the production release of this code.

2.2.1.4 Step 4: Execute the program

Now, run the program by typing the following at the command prompt. (This works for both Unix and MS-DOS.)

hello

The message:

Hello World 

will appear on the screen.

2.2.2 Creating a Program Using an Integrated Development Environment

The IDE provides a one-stop shop when it comes to programming. It take a compiler, editor, and debugger and wraps them into one neat package for the programmer. This package is presented inside a unified graphical interface that allows you to perform most program development operations with a few clicks of the mouse.

Since development environments tend to change, the particular version you use may operate slightly differently than is described in this chapter.

Each IDE is a little different, so we've included separate instructions for each one. (Note that compilers change much faster than books, so the information presented in these sections may be outdated. Check this book's page at the O'Reilly web site, http://www.oreilly.com/catalog/cplus2, for the latest information on compilation environments.)

2.2.2.1 Borland C++
  1. Create a directory called HELLO to hold the files for our hello program. You can create a directory using the Windows desktop tools or by typing the following command at the MS-DOS prompt:

    mkdir \HELLO
  2. From Windows, double-click on the Borland C++ icon to start the IDE, or start the IDE using the "Start" menu. The program begins execution and displays a blank workspace, as shown in Figure 2-3.

    Figure 2-3. Borland C++ initial screen
    figs/C++2_0203.gif
  3. Select the Filefigs/U2192.gifNew item to create a project for our program. Select Console Wizard as shown in Figure 2-4 and click OK.

    Figure 2-4. New Items selector
    figs/C++2_0204.gif
  4. The Console Wizard dialog appears as shown in Figure 2-5. Select C++ for Source Type and click OK.

    Figure 2-5. Project Options dialog box
    figs/C++2_0205.gif
  5. The initial editing window appears as shown in Figure 2-6.

    Figure 2-6. Initial editing window
    figs/C++2_0206.gif
  6. Add your code to the file Unit1.cpp. The resulting code should look like:

    #include <iostream>  int main(  )  {      std::cout << "Hello World\n";      return (0);  }

    You can ignore the #pragma statements and comments that Borland-C++ has added. When you have finished, your screen will look like Figure 2-7.

    Figure 2-7. Hello program
    figs/C++2_0207.gif
  7. Compile and run the program by selecting the Debugfigs/U2192.gifRun menu item. The program will run and display "Hello World" in a window, as shown in Figure 2-8.

    Figure 2-8. Hello program
    figs/C++2_0208.gif
2.2.2.2 Microsoft Visual C++
  1. From Windows, start Microsoft Visual Studio .NET. A start screen will be displayed, as shown in Figure 2-9.

    Figure 2-9. Microsoft Visual C++ initial screen
    figs/C++2_0209.gif
  2. Click on Filefigs/U2192.gifNewfigs/U2192.gifProject to bring up the New Project dialog shown in Figure 2-10.

    Figure 2-10. New Project dialog
    figs/C++2_0210.gif

    In the Template pane, select "Manage C++ Empty Project." Fill in the Name field with hello. Change the Location field to the directory in which you wish to build the project. Click OK. The project screen now appears as shown in Figure 2-11.

    Figure 2-11. Initial project screen
    figs/C++2_0211.gif
  3. In the Solution Explorer tab, select Source Files. Now create the program using the Filefigs/U2192.gifAdd New Item menu. The Add New Item dialog appears as shown in Figure 2-12.

    Figure 2-12. Add New Item dialog
    figs/C++2_0212.gif
  4. Select C++ file as the file type and put hello.cpp in the name field. Click Done to bring up the editing window shown in Figure 2-13.

    Figure 2-13. Editing window
    figs/C++2_0213.gif
  5. Type the following lines into the hello.cpp window.

    #include <iostream>  int main(  )  {      std::cout << "Hello World\n";      return (0);  }

    Your results should look like Figure 2-14.

    Figure 2-14. Completed program
    figs/C++2_0214.gif
  6. Compile the program by selecting Buildfigs/U2192.gifBuild Hello. You may have to resize the windows to view the messages. If everything works, the screen should look something like Figure 2-15.

    Figure 2-15. Result of the build
    figs/C++2_0215.gif
  7. Run the program using the Debugfigs/U2192.gifStart Program without Debugging window menu item. An MS-DOS window appears and the program is run within it. The results are shown in Figure 2-16.

    Figure 2-16. Sample run
    figs/C++2_0216.gif
figs/pixel.gif