c++ language tutorial

117
C++ Language Tutorial C++ LANGUAGE TUTORIAL This tutorial teaches the C++ programming language but assumes that the student has already attained a reasonable proficiency in C programming. It is composed of 12 chapters which should be studied in order since topics are introduced in a logical order and build upon topics introduced in previous chapters. It is to the students benefit to download the source code for the example programs, then compile and execute each program as it is studied. The diligent student will modify the example program in some way, then recompile and execute it to see if he understands the material studied for that program. This will provide the student with valuable experience using his compiler. The recommended method of study is to print the text for one or two chapters, download the example programs, and study the material by loading the example programs in the compiler's editor for viewing. Following successful completion of each chapter, additional chapters can be downloaded. Version 2.61 - September 22, 1996 (Files restructured on March 15, 1997) This tutorial is distributed as shareware which means that you do not have to pay to use it. However, the author spent a good deal of time and financial resources to develop this tutorial and requests that you share in the financial burden in a very small way, but only if you felt the tutorial was valuable to you as an aid in learning to program in C++. If you wish to remit a small payment to the author, full instructions for doing so will be given by clicking the link below. If you do not wish to remit any payment, please feel free to use the tutorial anyway. In either case, I hope you find programming in C++ to be rewarding and profitable. I personally think it is an excellent extension to C programming and is well worth the effort needed to master it. Introduction - What is C++ and why study it? Chapter 1 - Simple Things Chapter 2 - Compound Types Chapter 3 - Pointers Chapter 4 - Functions Chapter 5 - Encapsulation Chapter 6 - More Encapsulation Chapter 7 - Inheritance Chapter 8 - More Inheritance Chapter 9 - Multiple Inheritance Chapter 10 - Virtual Functions Chapter 11 - More Virtual Functions Chapter 12- Flyaway Adventure Game http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/02.03.2005 09:09:44

Upload: others

Post on 12-Sep-2021

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C++ Language Tutorial

C++ Language Tutorial

C++ LANGUAGE TUTORIAL

This tutorial teaches the C++ programming language but assumes that the student has already attained a reasonable proficiency in C programming. It is composed of 12 chapters which should be studied in order since topics are introduced in a logical order and build upon topics introduced in previous chapters. It is to the students benefit to download the source code for the example programs, then compile and execute each program as it is studied. The diligent student will modify the example program in some way, then recompile and execute it to see if he understands the material studied for that program. This will provide the student with valuable experience using his compiler.

The recommended method of study is to print the text for one or two chapters, download the example programs, and study the material by loading the example programs in the compiler's editor for viewing. Following successful completion of each chapter, additional chapters can be downloaded.

Version 2.61 - September 22, 1996 (Files restructured on March 15, 1997)

This tutorial is distributed as shareware which means that you do not have to pay to use it. However, the author spent a good deal of time and financial resources to develop this tutorial and requests that you share in the financial burden in a very small way, but only if you felt the tutorial was valuable to you as an aid in learning to program in C++. If you wish to remit a small payment to the author, full instructions for doing so will be given by clicking the link below. If you do not wish to remit any payment, please feel free to use the tutorial anyway. In either case, I hope you find programming in C++ to be rewarding and profitable. I personally think it is an excellent extension to C programming and is well worth the effort needed to master it.

Introduction - What is C++ and why study it?Chapter 1 - Simple ThingsChapter 2 - Compound TypesChapter 3 - PointersChapter 4 - FunctionsChapter 5 - EncapsulationChapter 6 - More EncapsulationChapter 7 - InheritanceChapter 8 - More InheritanceChapter 9 - Multiple InheritanceChapter 10 - Virtual FunctionsChapter 11 - More Virtual Functions Chapter 12- Flyaway Adventure Game

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/02.03.2005 09:09:44

Page 2: C++ Language Tutorial

C++ Tutorial - Introduction

C++ Tutorial - Introduction

WHAT IS C++

THE ORIGIN OF C++

The C programming language was developed at AT&T for the purpose of writing the operating system for the PDP-11 series of computers which ultimately became the UNIX operating system. C was developed with the primary goal of operating efficiency. Bjarne Stroustrup, also of AT&T, developed C++ in order to add object oriented constructs to the C language. Because object oriented technology was new at the time and all existing implementations of object oriented languages were very slow and inefficient, the primary goal of C++ was to maintain the efficiency of C.

C++ can be viewed as a traditional procedural language with some additional constructs. Beginning with C, some constructs are added for object oriented programming and some for improved procedural syntax. A well written C++ program will reflect elements of both object oriented programming style and classic procedural programming. C++ is actually an extendible language since we can define new types in such a way that they act just like the predefined types which are part of the standard language. C++ is designed for large scale software development.

HOW TO GET STARTED IN C++

The C programming language was originally defined by the classic text authored by Kernigan and Ritchie, "The C Programming language", and was the standard used by all C programmers until a few years ago. The ANSI standard for C was finally approved in December of 1989 and has become the official standard for programming in C. The ANSI-C standard adds many things to the language which were not a part of the Kernigan and Ritchie definition, and changes a few. The two definitions are not absolutely compatible and some experienced C programmers may not have studied the newer constructs added to the language by the ANSI-C standard.

This tutorial will assume a thorough knowledge of the C programming language and little time will be spent on the fundamental aspects of the language. However, as a aid to those programmers that have learned the dialect of C as defined by Kernigan & Ritchie, some sections will be devoted to explaining the newer additions included in the ANSI-C standard. As the ANSI-C standard was in development, many of the newer constructs from C++ were included as parts of C itself, so even though C++ is a derivation and extension of C, it would be fair to say that ANSI-C has some of its roots in C++. An example is prototyping which was developed for C++ and later added to C.

The best way to learn C++ is by using it. Almost any valid C program is also a valid C++ program and, in fact, the addition of about 12 keywords is the only reason that some C programs will not compile and execute as a C++ program. There are a few other subtle differences, but we will save the discussion of

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/intro.htm (1 of 4)02.03.2005 09:09:46

Page 3: C++ Language Tutorial

C++ Tutorial - Introduction

them until later. Since this is true, the best way to learn C++ is to simply add to your present knowledge and use a few new constructs as you need them for each new project. It would be a tremendous mistake to try to use all of the new constructs in your first C++ program. You would probably end up with an incomprehensive mixture of code that would be more inefficient than the same program written purely in C. It would be far better to add a few new constructs to your toolkit occasionally, and use them as needed while you gain experience with their use.

As an illustration of the portability of C to C++, all of the example programs included in the Coronado Enterprises C tutorial compiled and executed correctly when compiled as C++ programs with no changes. Note that this was version 2.6 which was released in 1994. The updates in the C++ compilers since then may have made this statement false for newer versions. None of the C++ programs will compile and execute correctly with any C compiler however, if for no other reason than the use of the new style of C++ comments.

HOW TO USE THIS TUTORIAL

This tutorial is best used while sitting in front of your computer. It is designed to help you gain experience with your own C++ compiler in addition to teaching you the proper use of C++. Display an example program on the monitor, using whatever text editor you usually use, and read the accompanying text which will describe each new construct introduced in the example program. After you study the program, and understand the new constructs, compile and execute the program with your C++ compiler.

After you successfully compile and execute the example program, introduce a few errors into the program to see what kind of error messages are issued. If you have done much programming, you will not be surprised if your compiler gives you an error message that seems to have nothing to do with the error introduced. This is because error message analysis is a very difficult problem with any modern programming language. The most important result of these error introduction exercises is the experience you will gain using your compiler and understanding its nuances. You should then attempt to extend the program using the techniques introduced with the program to gain experience.

The way this tutorial is written, you will not find it necessary to compile and execute every program. At the end of each example program, listed in comments, you will find the result of execution of that program. Some of the constructs are simple and easy for you to understand, so you may choose to ignore compilation and execution of that example program, depending upon the result of execution to give you the output. Some students have used these results of execution to study several chapters of this tutorial on an airplane by referring to a hardcopy of the example programs.

In the text of this tutorial, keywords, variable names, and function names will be written in bold type as an aid when you are studying the example programs.

DIFFERENT C++ IMPLEMENTATIONS

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/intro.htm (2 of 4)02.03.2005 09:09:46

Page 4: C++ Language Tutorial

C++ Tutorial - Introduction

There are primarily two standards for naming C++ files, one using the extension CPP and the other using the extension CXX. All files in this tutorial use the CPP extension for naming files. If your compiler requires the CXX extension it will be up to you to rename the files. When C++ was in its infancy, header files generally used the extension .HPP, but there is a definite trend to use .H for all header files. For that reason all header files in this tutorial will use that convention.

Even though we have tried to use the most generic form of all constructs, it is possible that some constructs will not actually compile and run with some C++ compilers. As we find new implementations of C++, and acquire copies of them, we will compile and execute all files in an attempt to make all example programs as universal as possible.

A committee is currently meeting to produce an ANSI-C++ standard, but the standard is not expected to be available for general use until 1998 at the earliest. Until then we must expect a few changes to the language. In fact, there have been many changes in the last two years as compiler writers are trying to catch up with the language changes.

PROGRAMMING EXERCISES

There are programming exercises given at the end of each chapter to enable you to try a few of the constructs given in the chapter. These are for your benefit and you will benefit greatly if you attempt to solve each programming problem. If you merely read this entire tutorial, you will have a good working knowledge of C++, but you will only become a C++ programmer if you write C++ programs. The programming exercises are given as suggestions to get you started programming.

An answer for each programming exercise is given in the cppans.zip file available for download in the same manner as the source files. The answers are all given in compilable C++ source files named in the format CHnn_m.CPP, where nn is the chapter number and m is the exercise number. If more than one answer is required, an A, B, or C, is included following the exercise number.

RECOMMENDED ADDITIONAL READING

Margaret Ellis & Bjarne Stroustrup. "The Annotated C++ Reference Manual". Addison-Wesley, 1990. This is the base document for the ANSI-C++ standard. Even though it is the definitive book on C++, it would be difficult for a beginner to learn the language from this book alone.

Scott Meyers. "Effective C++, 50 Specific Ways to Improve Your Programs and Designs". Addison-Wesley, 1992. This book is excellent for the advanced C++ programmer, but it is definitely not for the beginner.

Scott Meyers. "More Effective C++, 35 New Ways to Improve Your Programs and Designs". Addison-Wesley, 1996. This book is excellent for the advanced C++ programmer, following completion of the above reference.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/intro.htm (3 of 4)02.03.2005 09:09:46

Page 5: C++ Language Tutorial

C++ Tutorial - Introduction

Note that the C++ culture is in rapid change and by the time you read this, there will be additional well written texts available as aids to your learning the syntax and proper use of the C++ programming language.

Advance to Chapter 1

Return to the Table of Contents

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/intro.htm (4 of 4)02.03.2005 09:09:46

Page 6: C++ Language Tutorial

C++ Tutorial - Chapter 1

C++ Tutorial - Chapter 1

SIMPLE THINGS

As we begin the study of C++ and object oriented programming, a few comments are in order to help you get started. Since the field of object oriented programming is probably new to you, you will find that there is a significant amount of new terminology for you to grasp. This is true of any new endeavor and you should be warned not to be intimidated by all of the new concepts. We will add a few new topics in each chapter and you will slowly grasp the entire language.

Chapters one through four of this tutorial will concentrate on the non object oriented additions to C++. We will not begin the discussion of any object oriented programming techniques until chapter five.

EVEN COMMENTS ARE IMPROVED IN C++

Example program ------> CONCOM.CPP

Examine the file named CONCOM.CPP for an example of several new things in C++. We will take the new constructs one at a time beginning with the comments.

A C++ comment begins with the double slash "//", starts anywhere on a line, and runs to the end of that line where it is automatically terminated. The old method of comment definition used with ANSI-C can also be used with C++ as illustrated in lines 11 through 14, among other places in this program. The new method is the preferred method of comment definition because it is impossible to inadvertently comment out several lines of code. This can be done by forgetting to include the end of comment notation when using the older C method of comment notation. Good programming practice would be to use the new method for all comments and reserve the old method for use in commenting out a section of code during debugging since the two methods can be nested.

It would be well to caution you at this point however, that you should not use comments when the same sense of program definition can be obtained by using meaningful names for variables, constants, and functions. The careful selection of variable and function names can make nearly any code self documenting and you should strive to achieve this in your code.

THE KEYWORDS const AND volatile

There are two new keywords used in lines 9 through 11 which were not part of the original K&R definition of C, but are part of the ANSI-C standard. The keyword const is used to define a constant. In line 9 the constant is of type int, it is named START, and is initialized to the value 3. The compiler will not allow you to accidentally or purposefully change the value of START because it has been declared a constant. If you had a variable named STARTS in this program, the system would not allow you to

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap01.htm (1 of 9)02.03.2005 09:09:51

Page 7: C++ Language Tutorial

C++ Tutorial - Chapter 1

slightly misspell STARTS as START and accidentally change it. The compiler would give you an error message so you could fix the error. Since it is not permissible to change the value of a constant, it is imperative that you initialize it when it is declared so it will have a useful value.

You will note that the keyword const is also used in the function header in line 23 to indicate that the formal parameter named data_value is a constant throughout the function. Any attempt to assign a new value to this variable will result in a compile error. This is a small thing you can add to your programs to improve the compiler's ability to detect errors for you.

The keyword volatile is also part of the ANSI-C standard but was not included in the original K&R definition of C. Even though the value of a volatile variable can be changed by you, the programmer, there may be another mechanism by which the value could be changed, such as by a hardware interrupt timer causing the value to be incremented. The compiler needs to know that this value may be changed by some external force when it optimizes the code. A study of code optimization methods is very interesting, but beyond the scope of this tutorial. Note that a constant can also be volatile, which means that you cannot change it, but the system can modify it through some hardware function.

Ignore the output statement given in line 25 for a few minutes. We will study it in some detail later in this chapter. If you are experienced in the K&R style of programming, you may find line 5 and 23 a little strange. This illustrates prototyping and the modern method of function definition as defined by the ANSI-C standard. Prototyping is optional in C but absolutely required in C++. For that reason, chapter 4 of this tutorial is devoted entirely to prototyping.

It would be advantageous for you to compile and execute this program with your C++ compiler to see if you get the same result as given in the comments at the end of the listing. One of the primary purposes of compiling it is to prove that your compiler is loaded and executing properly.

THE SCOPE OPERATOR

Example program ------> SCOPEOP.CPP

The example program named SCOPEOP.CPP illustrates another construct that is new to C++. There is no corresponding construct in either K&R or ANSI-C. This allows access to the global variable named index even though there is a local variable of the same name within the main() function. The use of the double colon in front of the variable name, in lines 11, 13, and 16, instructs the system that we are interested in using the global variable named index, defined in line 4, rather than the local variable defined in line 8.

The use of this technique allows access to the global variable for any use. It could be used in calculations, as a function parameter, or for any other purpose. It is not really good programming practice to abuse this construct, because it could make the code difficult to read. It would be best to use a different variable name instead of reusing this name, but the construct is available to you if you find that

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap01.htm (2 of 9)02.03.2005 09:09:51

Page 8: C++ Language Tutorial

C++ Tutorial - Chapter 1

you need it sometime.

Be sure to compile and execute this program before proceeding on to the next example program where we will discuss the cout operator used in lines 10, 11, 15, and 16.

THE iostream LIBRARY

Example program ------> MESSAGE.CPP

Examine the example program named MESSAGE.CPP for our first hint of object oriented programming, even though it is a very simple one. In this program, we define a few variables and assign values to them for use in the output statements illustrated in lines 17 through 20, and in lines 23 through 26. cout is used to output data to the standard device, the monitor, but it works a little differently from our old familiar printf() function, because we do not have to tell the system what type we are outputting. Note that cout is not actually an output function, but we can sort of think of it as one until we fully define it later in this tutorial. For the time being, we will simply state that cout is an object used to send output data to the monitor.

C++, like the C language, has no input or output operations as part of the language itself, but defines the stream library to add input and output functions in a very elegant manner. A portion of the stream library is included in this program in line 2.

The operator <<, sometimes called the "put to" operator but more properly called the insertion operator, tells the system to output the variable or constant following it, but lets the system decide how to output the data. In line 17, we first tell the system to output the string, which it does by copying characters to the monitor, then we tell it to output the value of index. Notice however, that we fail to tell it what the type is or how to output the value. Since we don't tell the system what the type is, it is up to the system to determine what the type is and to output the value accordingly. After the system finds the correct type, we also leave it up to the system to use the built in default as to how many characters should be used for this output. In this case, we find that the system uses exactly as many characters as needed to output the data, with no leading or trailing blanks, which is fine for this output. Finally, the newline character is output as a single character string, and the line of code is terminated with a semicolon.

When we told the cout object to output some data in line 17, we actually called two different functions because we used it to output two strings and a variable of type int. This is the first hint at object oriented programming because we simply broadcast a message to the system to print out a value, and let the system find an appropriate function to do so. We are not required to tell the system exactly how to output the data, we only tell it to output it. This is a very weak example of object oriented programming, and we will study it in much more depth later in this tutorial.

In line 18, we tell the system to output a different string, followed by a floating point number, and another string of one character, the newline character. In this case, we told it to output a floating point

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap01.htm (3 of 9)02.03.2005 09:09:51

Page 9: C++ Language Tutorial

C++ Tutorial - Chapter 1

number without telling it that it was a floating point number, once again letting the system choose the appropriate output means based on its type. We did lose a bit of control in the transaction, however, because we had no control over how many significant digits to print before or after the decimal point. We chose to let the system decide how to format the output data.

The variable named letter is of type char, and is assigned the value of the uppercase X in line 14, then printed as a letter in line 19 because the cout object knows it is a character and outputs it accordingly.

Because C++ has several other operators and functions available with streams, you have complete flexibility in the use of the stream output functions. You should refer to your compiler documentation for details of other available formatting commands. Because it is expected to be mandated by the upcoming ANSI-C++ standard, the cout and printf() statements can be mixed in any way you desire. However all compilers do not yet conform to this standard and some use different forms of buffering for the two kinds of output. This could result in scrambled output, but it should be easy for the student to repair the output in such a way that only one form is used, either the cout or the printf().

MORE ABOUT THE stream LIBRARY

The stream library was defined for use with C++ in order to add to the execution efficiency of the language. The printf() function was developed early in the life of the C language and is meant to be all things to all programmers. As a result, it became a huge function with lots of extra baggage, most of which is used by only a few programmers. By defining the special purpose stream library, the design of C++ allows the programmer to use full formatting capabilities, but only load what is needed for the current programming job. Although it is not all illustrated here, there is a full set of formatting functions available in the C++ stream library. Check your compiler documentation for the complete list.

Lines 23 through 26 illustrate some of the additional features of the stream library which can be used to output data in a very flexible yet controlled format. The value of index is printed out in decimal, octal, and hexadecimal format in lines 23 through 25. When one of the special stream operators, dec, oct, or hex, is output, all successive output will be in that number base. Looking ahead to line 30, we find the value of index printed in hex format due to the selection of the hexadecimal base in line 25. If none of these special stream operators are output, the system defaults to decimal format.

THE cin OPERATOR

In addition to the predefined stream object, named cout, there is a predefined cin stream object which is used to read data from the standard input device, usually the keyboard. The cin stream uses the >> operator, usually called the "get from" operator but properly called the extraction operator. It has most of the flexibility of the cout stream. A brief example of the use of the cin stream is given in lines 28 through 30. The special stream operators, dec, oct, and hex, also select the number base for the cin stream separately from the cout stream. If none is specified, the input stream also defaults to decimal.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap01.htm (4 of 9)02.03.2005 09:09:51

Page 10: C++ Language Tutorial

C++ Tutorial - Chapter 1

In addition to the cout stream object and the cin stream object there is one more standard stream object, cerr, which is used to output to the error handling device. This device cannot be redirected to a file on some systems, like the output to the cout stream object can be. The three streams, cout, cin, and cerr, correspond to the stdout, the stdin, and the stderr stream pointers of the C programming language. Their use will be illustrated throughout the remainder of this tutorial.

The stream library also has file I/O capability which will be briefly illustrated in the next example program.

Be sure to compile and execute this program before going on to the next one. Remember that the system will ask you to enter an integer value which will be echoed back to the monitor, but changed to the hexadecimal base.

FILE STREAM OPERATIONS

Example program ------> FSTREAM.CPP

Examine the example program named FSTREAM.CPP for examples of the use of streams with files. We will be using a few C++ objects in this program but we hAve not yet studied them, so you will not understand them at this point. Don't spend too much time trying to understand them yet.

In this program a file is opened for reading, another for writing, and a third stream is opened to the printer to illustrate the semantics of stream operations on a file. Both input and output files are of type FILE in C programs, but the ifstream type is used for file input and the ofstream is used for output files. This is illustrated in lines 8 through 10 of this example program. Actually ifstream is a C++ class and infile is an object of that class as we will see later in this tutorial.

The only difference between the streams in the last program and the streams in this program is the fact that in the last program, the streams were already opened for us by the system. You will note that the stream object named printer is used in the same way we used the cout stream object in the last program. Finally, because we wish to exercise good programming practice, we close all of the files we have opened prior to ending the program.

This is our first example of object oriented programming because we are actually using objects in this program. The object named infile is told to open itself in line 17, then it is told to get one character at a time in line 44, and finally it is told to close itself in line 52. The "dot" notation is used with objects in a similar manner that structures are used in C. The name of the object is mentioned, followed by a "dot", and followed by the name of the action that the object is to execute. This terminology will be used in great profusion later in this tutorial, so don't worry about it at this time. The objects outfile and printer are manipulated in exactly the same manner.

For more information on the stream file I/O library, see Bjarne Stroustrup's book which is listed in the

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap01.htm (5 of 9)02.03.2005 09:09:51

Page 11: C++ Language Tutorial

C++ Tutorial - Chapter 1

introduction to this tutorial, or refer to your compiler documentation. Don't worry too much about it yet, after you learn the terminology by studying the rest of this tutorial, you will be able to return to a personal study of the stream library, and profit greatly from the study.

Be sure to compile and execute this program. When you execute it, it will request a file to be copied. You can enter the name of any ASCII file that resides in the current directory.

VARIABLE DEFINITIONS

Example program ------> VARDEF.CPP

Examine the file named VARDEF.CPP for a few more additions to the C++ language which aid in writing a clear and easy to understand program. In C++, as in ANSI-C, global and static variables are automatically initialized to zero when they are declared. The variables named index in line 4, and goofy in line 27 are therefore automatically initialized to zero. Of course, you can still initialize either to some other value if you so desire. Global variables are sometimes called external since they are external to any functions.

Automatic variables, those declared inside of any function, are not automatically initialized but will contain the value that happens to be in the location where they are defined, which must be considered a garbage value. The variable named stuff in line 8, therefore does not contain a valid value, but some garbage value which should not be used for any meaningful purpose. In line 11, it is assigned a value based on the initialized value of index and it is then displayed on the monitor for your examination.

THE C++ REFERENCE

Notice the ampersand in line 9. This defines another_stuff as a reference which is a new addition to C++. The reference should not be used very often, if ever, in this context, but this is a very simple example used to introduce the reference and discuss its use and operation. The reference is not the same as any other entity used in C because it operates like a self dereferencing pointer. Following its initialization, the reference becomes a synonym for the variable stuff, and changing the value of stuff will change the value of another_stuff because they are both actually referring to the same variable. The synonym can be used to access the value of the variable stuff for any legal purpose in the language. It should be pointed out that a reference must be initialized to reference some variable when it is defined or the compiler will respond with an error. Following initialization, the reference cannot be changed to refer to a different variable. The reference is difficult to discuss because we want to call it a reference variable, but it is not a variable since it cannot be changed. Whether we like the name or not it is simply called a reference.

The use of the reference in this way can lead to very confusing code, but it has another use where it can make the code very clear and easy to understand. We will study the proper use of the reference in chapter 4 of this tutorial.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap01.htm (6 of 9)02.03.2005 09:09:51

Page 12: C++ Language Tutorial

C++ Tutorial - Chapter 1

DEFINITIONS ARE EXECUTABLE STATEMENTS

Coming from your background of C, you will find the statement in line 16 very strange, but this is legal in C++. Anyplace it is legal to put an executable statement, it is also legal to define a new variable because a data definition is an executable statement according to the definition of C++. In this case, we define the new variable named more_stuff and initialize it to the value of 13. It has a scope from the point where it is defined to the end of the block in which it is defined, so it is valid throughout the remainder of the main() program. The variable named goofy is defined even later in line 27.

It is significant that the variable is declared near its point of usage. This makes it easier to see just what the variable is used for, since it has a much more restricted scope of validity. When you are debugging a program, it is convenient if the variable declaration is located in close proximity to where you are debugging the code.

WHAT ABOUT definition AND declaration?

The words definition and declaration refer to two different things in C++, and in ANSI-C also for that matter. They really are different and have different meanings, so we should spend a little time defining exactly what the words mean in C++. A declaration provides information to the compiler about the characteristics of something such as a type or a function but it doesn't actually define any code to be used in the executable program. A definition, on the other hand, actually defines something that will exist in the executable program, either some useful variables, or some executable code. You are required to have one and only one definition of each entity in the program. In short, a declaration introduces a name into the program and a definition introduces some code and requires memory space to store something.

If we declare a struct, we are only declaring a pattern to tell the compiler how to store data later when we define one or more variables of that type. But when we define some variables of that type, we are actually declaring their names for use by the compiler, and defining a storage location to store the values of the variables. Therefore, when we define a variable, we are actually declaring it and defining it at the same time.

C permits multiple definitions of a variable in any given namespace, provided the definitions are the same and it generates only a single variable for the multiple definitions. C++, however, does not permit redefinition of a variable or any other entity for a very definite reason that we will discuss later.

We will refer to these definitions many times throughout the course of this tutorial so if this is not clear now, it will clear up later.

A BETTER for LOOP

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap01.htm (7 of 9)02.03.2005 09:09:51

Page 13: C++ Language Tutorial

C++ Tutorial - Chapter 1

Take careful notice of the for loop defined in line 20. This loop is a little clearer than the for loop that is available in ANSI-C, because the loop index is defined in the for loop itself. The scope of this loop index depends on how new your compiler is.

If your compiler is a little old, the scope of the loop index is from its definition to the end of the enclosing block. In this case its scope extends to line 32 since the closing brace in line 32 corresponds to the most recent opening brace prior to the definition of the variable. Since the variable is still available, it can be used for another loop index or for any other purpose which an integer type variable can legally be used for.

If your compiler is relatively new, the scope of the loop index is from its definition to the end of the loop. In this case its scope extends to line 25 because that is where the loop ends. This is a very new extension to the C++ language by the standards committee, and will only be available with the newest compilers.

Regardless of the age of your compiler, the variable named count2 is defined and initialized during each pass through the loop because it is defined within the block controlled by the for loop. Its scope is only the extent of the loop, lines 23 to 25, so that it is automatically deallocated each time the loop is completed. It is therefore defined, initialized, used and deallocated five times, once for each pass through the loop.

You will notice that the variable count2 is assigned a numerical value in line 23 but when it is printed out, a character value is actually output. This is because C++ is careful to use the correct type for output. If you have a very old compiler, it may output a numerical value here.

Finally, as mentioned earlier, the static variable named goofy is defined and automatically initialized to zero in line 27. Its scope is from the point of its definition to the end of the block in which it is defined, line 32.

Be sure to compile and execute this program.

OPERATOR PRECEDENCE

Operator precedence is identical to that defined for ANSI-C so no attempt will be made here to define it. There is a small difference when some operators are overloaded which we will study later in this tutorial. Some of the operators act slightly different when overloaded than the way they operate with elements of the predefined language.

Do not worry about the previous paragraph, it will make sense later in this tutorial after we have studied a few more topics.

PROGRAMMING EXERCISES

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap01.htm (8 of 9)02.03.2005 09:09:51

Page 14: C++ Language Tutorial

C++ Tutorial - Chapter 1

1. Write a program that displays your name and date of birth on the monitor three times using the cout stream object. Define any variables you use as near as possible to their point of usage.

2. Write a program with a few const values and volatile variables and attempt to change the value of the constants to see what kind of error message your compiler gives you.

3. Write a program that uses stream objects to interactively read in your birthday with three different cin statements. Print your birthday in octal, decimal, and hexadecimal notation just for the practice.

Advance to Chapter 2

Return to the Table of Contents

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap01.htm (9 of 9)02.03.2005 09:09:51

Page 15: C++ Language Tutorial

C++ Tutorial - Chapter 2

C++ Tutorial - Chapter 2

COMPOUND TYPES

ENUMERATED TYPES

Example program ------> ENUM.CPP

Examine the file named ENUM.CPP for an example that uses an enumerated type variable. The enumerated type is used in C++ in a similar way that it was used in ANSI-C, but there are a lot of differences. The keyword enum is not required to be used again when defining a variable of that type, but it can be used if desired. The name game_result is defined as an enumerated type making the use of the keyword enum optional. However, it may be clearer for you to use the keyword when defining a variable in the same manner that it is required to be used in C, and you may choose to do so.

The example program uses the keyword enum in line 9, but omits it in line 8 to illustrate to you that it is indeed optional, but that is a trivial difference. There is a bigger difference in the way an enumerated type is used in C++. In C, the enumerated type is simply an int type variable, but in C++ it is not an int, but its own type. Mathematical operations can not be performed on it, nor can an integer be assigned to it. It cannot be incremented or decremented as it can be in C. In the example program, an integer is used as the loop index for the for loop because it can be incremented, then the value of the loop index named count is assigned to the enumerated variable by using a cast. The cast is required or a compile error is reported. The mathematical operations and the increment and decrement operators can be defined for the enumerated type, but they are not automatically available. Operator overloading will be studied later, and the last sentence will make much more sense at that time.

If you have an older compiler, the enumerated variable game_result can be used for the loop variable but your code would not be portable to a newer compiler.

The remainder of this program should be no problem for you to understand. After studying it, be sure to compile and execute it and examine the output.

A SIMPLE STRUCTURE

Example program ------> STRUCTUR.CPP

Examine the example program named STRUCTUR.CPP for an illustration using a very simple structure. This structure is no different from that used in ANSI-C except for the fact that the keyword struct is not required to be used again when defining a variable of that type. Lines 12 and 13 illustrate the definition of variables without the keyword, and line 14 indicates that the keyword struct can be included if desired. It is up to you to choose which style you prefer to use in your C++ programs.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap02.htm (1 of 4)02.03.2005 09:09:53

Page 16: C++ Language Tutorial

C++ Tutorial - Chapter 2

Once again, be sure to compile and execute this program after studying it carefully, because the next example program is very similar but it introduces a brand new construct not available in standard C, the class.

A VERY SIMPLE CLASS

Example program ------> CLASS1.CPP

Examine the example program named CLASS1.CPP for our first example of a class in C++. This is the first class example, but it will not be the last, since the class is the major reason for using C++ over ANSI-C or some other programming language. You will notice the keyword class used in line 4, in exactly the same way that the keyword struct was used in the last program, and they are in fact very similar constructs. There is a definite difference, as we will see, but for the present time we will be concerned more with their similarities.

The word animal in line 4 is the name of the class, and when we define variables of this type in lines 13 through 15, we can either omit the keyword class or include it if desired as illustrated in line 15. In the last program, we declared 5 variables of a structure type, but in this program we declare 5 objects. They are called objects because they are of a class type. The differences are subtle, and as we proceed through this tutorial, we will see that the class construct is indeed very important and valuable. The class was introduced here only to give you a glimpse of what is to come later in this tutorial.

The class is a type which can be used to define objects in much the same way that a structure is a type that can be used to define variables. Your dog named King is a specific instance of the general class of dogs, and in a similar manner, an object is a specific instance of a class. It would be well to take note of the fact that the class is such a generalized concept that there are libraries of prewritten classes available in the marketplace. You can purchase classes which perform some generalized operations such as managing stacks, queues, or lists, sorting data, managing windows, etc. This is because of the generality and flexibility of the class construct.

The new keyword public in line 6, followed by a colon, is necessary in this case because the variables in a class are defaulted to a private type and we could not access them at all without making them public. Don't worry about this program yet, we will cover all of this in great detail later in this tutorial. Be sure to compile and run this example program to see that it does what we say it does with your compiler. Keep in mind that this is your first example of a class and it illustrates essentially nothing concerning the use of this powerful C++ construct.

THE FREE UNION OF C++

Example program ------> UNIONEX.CPP

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap02.htm (2 of 4)02.03.2005 09:09:53

Page 17: C++ Language Tutorial

C++ Tutorial - Chapter 2

Examine the program named UNIONEX.CPP for an example of a free union. In ANSI-C, all unions must be named in order to be used, but this is not true in C++. When using C++ we can use a free union, a union without a name. The union is embedded within a simple structure and you will notice that there is not a variable name following the declaration of the union in line 13. In ANSI-C, we would have to name the union and give a triple name (three names dotted together) to access the members. Since it is a free union, there is no union name, and the variables are accessed with only a doubly dotted name as illustrated in lines 20, 24, 28, and others.

You will recall that a union causes all the data contained within the union to be stored in the same physical memory locations, such that only one variable is actually available at a time. This is exactly what is happening here. The variable named fuel_load, bomb_load, and pallets are stored in the same physical memory locations and it is up to the programmer to keep track of which variable is stored there at any given time. You will notice that the transport is assigned a value for pallets in line 28, then a value for fuel_load in line 30. When the value for fuel_load is assigned, the value for pallets is corrupted and is no longer available since it was stored where fuel_load is currently stored. The observant student will notice that this is exactly the way the union is used in ANSI-C except for the way components are named.

The remainder of the program should be easy for you to understand, so after you study and understand it, compile and execute it.

C++ TYPE CONVERSIONS

Example program ------> TYPECONV.CPP

Examine the program named TYPECONV.CPP for a few examples of type conversions in C++. The type conversions are done in C++ in exactly the same manner as they are done in ANSI-C, but C++ gives you another form for doing the conversions.

Lines 10 through 17 of this program use the familiar "cast" form of type conversions used in ANSI-C, and there is nothing new to the experienced C programmer. You will notice that lines 10 through 13 are all the same. The only difference is that we are coercing the compiler to do the indicated type conversions prior to doing the addition and the assignment in some of the statements. In line 13, the int type variable will be converted to type float prior to the addition, then the resulting float will be converted to type char prior to being assigned to the variable c.

Additional examples of type coercion are given in lines 15 through 17 and all three of these lines are essentially the same.

The examples given in lines 19 through 26 are unique to C++ and are not valid in ANSI-C. In these lines the type coercions are written as though they are function calls instead of the more familiar "cast" method as illustrated earlier. Lines 19 through 26 are identical to lines 10 through 17.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap02.htm (3 of 4)02.03.2005 09:09:53

Page 18: C++ Language Tutorial

C++ Tutorial - Chapter 2

You may find this method of type coercion to be clearer and easier to understand than the "cast" method and in C++ you are free to use either, or to mix them if you so desire, but your code could be very difficult to read if you indescriminantly mix them.

Be sure to compile and execute this example program.

PROGRAMMING EXERCISES

1. Starting with the program ENUM.CPP, add the enumerated value of FORFEIT to the enumerated type game_result, and add a suitable message and logic to get the message printed in some way.

2. Add the variable height of type float to the class of CLASS1.CPP and store some values in the new variable. Print some of the values out. Move the new variable ahead of the keyword public: and see what kind of error message results. We will cover this error in chapter 5 of this tutorial.

Advance to Chapter 3

Return to the Table of Contents

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap02.htm (4 of 4)02.03.2005 09:09:53

Page 19: C++ Language Tutorial

C++ Tutorial - Chapter 3

C++ Tutorial - Chapter 3

POINTERS

Because pointers are so important in C and C++, this chapter will review some of the more important topics concerning pointers. Even if you are extremely conversant in the use of pointers, you should not completely ignore this chapter because some new material unique to C++ is presented here.

POINTER REVIEW

Example program ------> POINTERS.CPP

Examine the program named POINTERS.CPP for a simple example of the use of pointers. This is a pointer review and if you are comfortable with the use of pointers, you can skip this example program completely.

A pointer in either ANSI-C or C++ is declared with an asterisk preceding the variable name. The pointer is then a pointer to a variable of that one specific type and should not be used with variables of other types. Thus pt_int is a pointer to an integer type variable and should not be used with any other type. Of course, an experienced C programmer knows that it is simple to coerce the pointer to be used with some other type by using a cast, but he must then assume the responsibility for its correct usage.

In line 12 the pointer named pt_int is assigned the address of the variable named pig and line 13 uses the pointer named pt_int to add the value of dog to the value of pig because the asterisk dereferences the pointer in exactly the same manner as standard C. Figure 3-1 is a graphical representation of the data space following execution of line 13. Note that a box containing a dot represents a pointer. The address is used to print out the value of the variable pig in line 14 illustrating the use of a pointer with the output stream object cout. Likewise, the pointer to float named pt_float is assigned the address of x, then used

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap03.htm (1 of 5)02.03.2005 09:09:56

Page 20: C++ Language Tutorial

C++ Tutorial - Chapter 3

in a trivial calculation in line 18.

CONSTANT POINTERS AND POINTERS TO CONSTANTS

The definition of C++ allows a pointer to a constant to be defined such that the value to which the pointer points cannot be changed but the pointer itself can be moved to another variable or constant. The method of defining a pointer to a constant is illustrated in line 22. In addition to a pointer to a constant, you can also declare a constant pointer, one that cannot be changed. Line 23 illustrates this. Note that neither of these pointers are used in illustrative code.

Either of these constructs can be used to provide additional compile time checking and improve the quality of your code. If you know a pointer will never be moved due to its nature, you should define it as a constant pointer. If you know that a value will not be changed, it can be defined as a constant and the compiler will tell you if you ever inadvertently attempt to change it.

A POINTER TO VOID

The pointer to void is actually a part of the ANSI-C standard but is relatively new so it is commented upon here. A pointer to void can be assigned the value of any other pointer type. You will notice that the pointer to void named general is assigned an address of an int type in line 15 and the address of a float type in line 20 with no cast and no complaints from the compiler. This is a relatively new concept in C and C++. It allows a programmer to define a pointer that can be used to point to many different kinds of things to transfer information around within a program. A good example is the malloc() function which returns a pointer to void. This pointer can be assigned to point to any entity, thus transferring the returned pointer to the correct type.

A pointer to void is aligned in memory in such a way that it can be used with any of the simple predefined types available in C++, or in ANSI-C for that matter. They will also align with any compound types the user can define since compound types are composed of the simpler types.

If you are not completely comfortable with this trivial program using pointers, you should review the use of pointers in any good C programming book or Coronado Enterprises C tutorial before proceeding on because we will assume that you have a thorough knowledge of pointers throughout the remainder of this tutorial. It is not possible to write a C program of any significant size or complexity without the use of pointers.

Be sure to compile and execute this program.

DYNAMIC ALLOCATION AND DEALLOCATION

Example program ------> NEWDEL.CPP

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap03.htm (2 of 5)02.03.2005 09:09:56

Page 21: C++ Language Tutorial

C++ Tutorial - Chapter 3

Examine the program named NEWDEL.CPP for our first example of the new and delete operators. The new and delete operators do dynamic allocation and deallocation in much the same manner that the malloc() and free() functions do in your old favorite C implementation.

During the design of C++, it was felt that since dynamic allocation and deallocation are such a heavily used part of the C programming language and would also be heavily used in C++, it should be a part of the language, rather than a library add-on. The new and delete operators are actually a part of the C++ language and are operators, much like the addition operator or the assignment operator. They are therefore very efficient, and are very easy to use as we will see in this example program.

Lines 15 and 16 illustrate the use of pointers in the tradition of C and line 17 illustrates the use of the new operator. This operator requires one modifier which must be a type as illustrated here. The pointer named point2 is now pointing at the dynamically allocated integer variable which exists on the heap, and can be used in the same way that any dynamically allocated variable is used in ANSI-C. Lines 19 and 20 illustrate displaying the value on the monitor which was assigned in line 18.

Line 21 allocates another new variable and line 22 causes point2 to refer to the same dynamically allocated variable as point1 is pointing to. In this case, the reference to the variable that point2 was previously pointing to has been lost and it can never be used or deallocated. It is lost on the heap until we return to the operating system when it will be reclaimed for further use, so this is obviously not good practice. Note that point1 is deallocated with the delete operator in line 26, and point2 can not be deleted since it is now pointing to nothing. Since the pointer point1 itself is not changed, it is probably still pointing to the original data on the heap. This data could probably be referred to again using point1, but it would be terrible programming practice since you have no guarantee what the system will do with the pointer or the data. The data storage is returned to the free list to be allocated in a subsequent call, and will soon be reused in any practical program.

Since the delete operator is defined to do nothing if it is passed a NULL value, it is legal to ask the system to delete the data pointed to by a pointer with the value of NULL, but nothing will actually happen. It is actually wasted code. The delete operator can only be used to delete data allocated by a new operator. If the delete is used with any other kind of data, the operation is undefined and anything can happen. According to the ANSI standard, even a system crash is a legal result of this illegal operation, and can be defined as such by the compiler writer.

In line 28, we declare some floating point variables. You will remember that in C++ the variables do not have to be declared at the beginning of a block. A declaration is an executable statement and can therefore appear anywhere in a list of executable statements. One of the float variables is allocated within the declaration to illustrate that this can be done. Some of the same operations are performed on these float type variables as were done on the int types earlier.

Some examples of the use of a structure are given in lines 36 through 44 and should be self explanatory.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap03.htm (3 of 5)02.03.2005 09:09:56

Page 22: C++ Language Tutorial

C++ Tutorial - Chapter 3

Finally, since the new operator requires a type to determine the size of the dynamically allocated block, you may wonder how you can allocate a block of arbitrary size. This is possible by using the construct illustrated in line 48 where a block of 37 char sized entities, which will be 37 bytes, is allocated. A block of 133 bytes greater than the size of the date structure is allocated in line 50. It is therefore clear that the new operator can be used with all of the flexibility of the malloc() function which you are familiar with. The brackets are required in lines 49 and 51 to tell the compiler that it is deallocating an array.

The standard functions which you have been using in C for dynamic memory management, malloc(), calloc(), and free(), are also available for use in C++ and can be used in the same manner they were used in C. If you are updating code with the older function calls, continue to use them for any additions to the code. If you are designing and coding a new program you should use the newer constructs because they are a built in part of the language rather than an add on and are therefore more efficient. It is an error to delete a variable that has been malloc'ed and it is an error to free a variable that was allocated with new.

Be sure to compile and execute this program.

POINTERS TO FUNCTIONS

Example program ------> FUNCPNT.CPP

Examine the program named FUNCPNT.CPP for an example of using a pointer to a function. It must be pointed out that there is nothing new here, the pointer to a function is available in ANSI-C as well as in C++ and works in the manner described here for both languages. It is not regularly used by most C programmers, so it is briefly discussed here as a refresher. If you are comfortable with the use of pointers to functions, you can skip this discussion entirely.

There is nothing unusual about this program except for the pointer to a function declared in line 7. This declares a pointer to a function which returns nothing (void) and requires a single formal parameter, a float type variable. You will notice that all three of the functions declared in lines 4 through 6 fit this profile and are therefore candidates to be called with this pointer. If you have not used prototyping in C, these lines will look strange to you. Don't worry about them at this point since we will study prototyping in the next chapter of this tutorial.

Observe that in line 14 we call the function print_stuff() with the parameter pi and in line 15 we assign the function pointer named function_pointer the value of print_stuff and use the function pointer to call the same function again in line 16. Lines 14 and 16 are therefore identical in what is accomplished because of the pointer assignment in line 15. In lines 17 through 22, a few more illustrations of the use of the function pointer are given. You will be left to study these on your own.

Since we assigned the name of a function to a function pointer, and did not get an assignment error, the

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap03.htm (4 of 5)02.03.2005 09:09:56

Page 23: C++ Language Tutorial

C++ Tutorial - Chapter 3

name of a function must be a pointer to that function. This is exactly the case. A function name is a pointer to that function, but it is a pointer constant and cannot be changed. This is exactly the case we found when we studied arrays in ANSI-C at some point in our C programming background. An array name is a constant pointer to the first element of the array.

Since the name of the function is a constant pointer to that function, we can assign the name of the function to a function pointer and use the function pointer to call the function. The only caveat is that the return value and the number and types of parameters must be identical. Most C and C++ compilers will not, and in fact, can not warn you of type mismatches between the parameter lists when the assignments are made. This is because the assignments are done at runtime when no type information is available to the system, rather than at compile time when all type information is available.

The use and operation of pointers must be thoroughly understood when we get to the material on dynamic binding and polymorphism later in this tutorial. It will be discussed in detail at that time.

Be sure to compile and execute this program.

PROGRAMMING EXERCISES

1. When dynamically allocated data is deleted, it is still actually in memory, stored on the heap. Repeat the output statement from lines 24 and 25 of NEWDEL.CPP immediately following the delete in line 26 to see if the values are really still there. Repeat it once again just prior to the end of the program when the data spaces should have been written over to see if you get garbage out. Even if your compiler reports the correct data, it is terrible practice to count on this data still being there because in a large dynamic program, the heap space will be used repeatedly.

2. Add a function to FUNCPNT.CPP which uses a single integer for a parameter and attempt to call it by using the function pointer to see if you get the correct data into the function.

Advance to Chapter 4

Return to the Table of Contents

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap03.htm (5 of 5)02.03.2005 09:09:56

Page 24: C++ Language Tutorial

C++ Tutorial - Chapter 4

C++ Tutorial - Chapter 4

FUNCTIONS

This chapter discusses enhancements in the capabilities of functions that have been made to C++. These changes make programming more convenient and permit the compiler to do further checking for errors. A fair amount of time is also spent in this chapter teaching the modern form of function definition and prototyping.

Prototyping allows the compiler to do additional type checking for your function calls which can detect some programming errors. The first two example programs in this chapter are designed to teach prototyping and what it will do for you. Prototyping is a relatively new addition to C, so even some experienced C programmers are not familiar with it. If you have experience with prototyping you can skip directly to the section named PASS BY REFERENCE later in this chapter.

PROTOTYPES

Example program ------> PROTYPE1.CPP

Examine the file named PROTYPE1.CPP for our first look at a prototype and an illustration of how it is used. The prototyping used in C++ is no different than that used in ANSI-C. Actually, many C programmers take a rather dim view of prototyping and seem reluctant to use it, but with C++ it is considerably more important and is in much heavier use. In fact, prototyping is required to be used in some situations in C++.

A prototype is a limited model of a more complete entity to come later. In this case, the full function is the complete entity to come later and the prototype is illustrated in line 4. The prototype gives a model of the interface to the function that can be used to check the calls to the function for the proper number of parameters and the correct types of parameters. Each call to the function named do_stuff() must have exactly three parameters or the compiler will issue an error message. In addition to the correct number of parameters, the types must be compatible or the compiler will issue an error message. Notice that when the compiler is working on lines 12 and 13, the type checking can be done based on the prototype in line 4 even though the function itself is not yet defined. If the prototype is not given, the number of parameters will not be checked, nor will the types of the parameters be checked. Without a prototype, if you have the wrong number of parameters, you will get an apparently good compile and link, but the program may do some very strange things when it is executed.

To write the prototype, simply copy the header from the function to the beginning of the program and append a semicolon to the end as a signal to the compiler that this is not a function but a prototype. The variable names given in the prototype are optional and act merely as comments to the human reader since they are completely ignored by the compiler. You could replace the variable name wings in line 4

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap04.htm (1 of 8)02.03.2005 09:10:00

Page 25: C++ Language Tutorial

C++ Tutorial - Chapter 4

with your first name and there would be no difference in compilation. Of course, the next person that had to read your program would be somewhat baffled with your choice of variable names.

In this case, the two function calls to this function, given in lines 12 and 13, are correct so no error will be listed during compilation.

Even though we wish to use the char type for eyes in the function, we wish to use it as a number rather than as a character. The cast to int in line 22 is required to force the printout of the numerical value rather than an ASCII character. The next example program is similar but omits the cast to int in order to illustrate the difference.

COMPATIBLE TYPES

We mentioned compatible types earlier so we should review them just a bit in order to make our discussion of prototyping complete. Compatible types are any simple types that can be converted from one to another in a meaningful way. For example, if you used an integer as the actual parameter and the function was expecting a float type as the formal parameter, the system would do the conversion automatically, without mentioning it to you. This is also true of a float changing to a char, or a char changing to an int. There are definite conversion rules which would be followed. These rules are given in great detail in section 3.2 of the ANSI-C standard and are also given on page 198 of the second edition of the K&R reference.

If we supplied a pointer to an integer as the actual parameter and expected an integer as the formal parameter in the function, the conversion would not be made because they are two entirely different kinds of values. Likewise, a structure would not be converted automatically to a long float, an array, or even to a different kind of structure, because they are all incompatible and cannot be converted in any meaningful manner. The entire issue of type compatibility as discussed in chapter 2 of this tutorial applies equally well to the compatibility of types when calling a function. Likewise, the type specified as the return type, in this case void, must be compatible with the expected return type in the calling statement, or the compiler will issue a warning.

HOW DOES PROTOTYPING WORK?

This is your chance to try prototyping for yourself and see how well it works and what kinds of error messages you get when you do certain wrong things. Change the actual parameters in line 12 to read (12.2, 13, 12345) and see what the compiler says about that change. It will probably say nothing because they are all type compatible. If you change it to read (12.0, 13), it will issue a warning or error because there are not enough arguments given. Likewise you should receive an error message if you change one of the parameters in line 13 to an address by putting an ampersand in front of one of the variable names. Finally, change the first word in line 4 from void to int and see what kind of error message is given. You will first be required to make the function header in line 18 agree with the prototype, then you will find that there is no value returned from the function. You should have a good feeling that prototyping is

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap04.htm (2 of 8)02.03.2005 09:10:00

Page 26: C++ Language Tutorial

C++ Tutorial - Chapter 4

doing something worthwhile for you after making these changes.

Be sure to compile and execute this program then make the changes recommended above, attempting to compile it after each change.

A LITTLE MORE PROTOTYPING

Example program ------> PROTYPE2.CPP

Examine the next example program named PROTYPE2.CPP for a little more information on prototyping. This program is identical to the last one except for a few small changes. The variable names have been omitted from the prototype in line 4 as an illustration that they are interpreted only as comments by the C++ compiler. The function header is formatted differently to allow for a comment alongside each of the actual parameters. This should make the function header a little more self explanatory. However, you should remember that comments should not be used to replace careful selection of variable names. In this particular case, the comments add essentially nothing to the clarity of the program.

WHAT DOES PROTOTYPING COST?

Prototyping is essentially free because it costs absolutely nothing concerning the run time size or speed of execution. Prototyping is a compile time check only, and slows down the compile time a negligible amount because of the extra checking that the compiler must do. If prototyping finds one error for you that you would have had to find with a debugger, it has more than paid for itself for use in an entire project. I once spent 12 hours of debugging time to find that I forgot to pass the address of a variable to a function. Prototyping would have found the error on the first compilation of that 2000 line program.

The only price you pay to use prototyping is the extra size of the source files because of the prototypes, and the extra time for the compiler to read the prototypes during the compilation process, but both costs are negligible.

Be sure to compile and execute this example program. You will find that it is identical to the last example program, except for the changes in the prototype and the removal of the cast from the last line of the function.

PASS BY REFERENCE

Example program ------> PASSREF.CPP

Examine the program named PASSREF.CPP for an example of a pass by reference, a construct which is not available in ANSI-C. The reference variable was mentioned in chapter 1 and it was recommended

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap04.htm (3 of 8)02.03.2005 09:10:00

Page 27: C++ Language Tutorial

C++ Tutorial - Chapter 4

there that you don't use it in the manner illustrated there. This example program illustrates a situation where it can be used to your advantage. The pass by reference allows the passing of a variable to a function and returning the changes made in the function to the main program. In ANSI-C the same effect can be seen when a pointer to a variable is passed to a function, but use of a reference variable is a little cleaner.

Observe the prototype in line 4 where the second variable has an ampersand in front of the variable name. The ampersand instructs the compiler to treat this variable as a reference to the actual variable passed from the calling function. It acts like the actual variable from the main program is used in the function. In the function itself, in lines 24 through 27, the variable in2 is used just like any other variable but it acts like we are using the variable passed to this function from the main program not a copy of it. The other variable named in1 is treated just like any other normal variable in ANSI-C. The name in2 is a synonym for the variable named index in the main program, but the name in1 refers to a copy of the variable count from the main program. In actual practice, a pointer is passed to the function and it is automatically dereferenced when used in the function. This is transparent to you, the programmer.

If you prefer to omit the variable names in the prototypes, you would write the prototype as follows;

void fiddle(int, int&);

If you are a Pascal programmer, you will recognize that the variable named in1 is treated just like a normal parameter in a Pascal call, a call by value. The variable named in2 however, is treated like a variable with the reserved word VAR used in front of it, usually referred to as a call by reference. As mentioned earlier, the reference variable used in C++ is actually a self dereferencing pointer which refers to, or points to, the original value.

When you compile and execute this program, you will find that the first variable got changed in the function but the change was not reflected in the original value when we returned to the main program. The second variable however, was changed in the function and the new value was reflected back into the variable in the main program which we can see when the values are listed on the monitor. It should be clear that the reference allows you to pass a parameter by reference to a function. After you gain experience with the reference, you will use it to improve efficiency of some programs. This is because passing a large structure can be done very efficiently if it is passed by reference.

DEFAULT PARAMETERS

Example program ------> DEFAULT.CPP

Examine the file named DEFAULT.CPP for an example of the use of default parameters in C++. This program really looks strange since it contains default values for some of the parameters in the prototype, but these default values are very useful as we will see shortly.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap04.htm (4 of 8)02.03.2005 09:10:00

Page 28: C++ Language Tutorial

C++ Tutorial - Chapter 4

This prototype says that the first parameter named length must be given for each call of this function because a default value is not supplied. The second parameter named width, however, is not required to be specified for each call, and if it is not specified, the value 2 will be used for the variable width within the function. Likewise, the third parameter is optional, and if it is not specified, the value of 3 will be used for height within the function.

In line 11 of this program, all three parameters are specified so there is nothing unusual about this call from any other function call we have made. Only two values are specified in line 12 however, so we will use the default value for the third parameter and the system acts as if we called it with get_volume(x,y,3) since the default value for the third value is 3. In line 13, we only specified one parameter which will be used for the first formal parameter, and the other two will be defaulted. The system will act as if we had called the function with get_volume(x,2,3). Note that the output from these three lines is reversed. This will be explained shortly.

There are a few rules which should be obvious but will be stated anyway. Once a parameter is given a default value in the list of formal parameters, all of the remaining must have default values also. It is not possible to leave a hole in the middle of the list, only the trailing values can be defaulted. Of course, the defaulted values must be of the correct types or a compiler error will be issued. The default values can be given in either the prototype or the function header, but not in both. If they were given in both places, the compiler must not only use the default value, but it must carefully check to see that both values are identical. This could further complicate an already very complicated problem, that of writing a C++ compiler, so this rule was instituted for the benefit of the compiler writer.

As a matter of style, it is highly recommended that the default values be given in the prototype rather than in the function. The reason will be obvious when we begin using object oriented programming techniques.

WHY IS THE OUTPUT SCRAMBLED?

When the compiler finds a cout statement, the complete line of code is initially scanned from right to left to evaluate any functions, then the data is output field by field from left to right. Therefore in line 11, get_volume() is evaluated with its internal output displayed first. Then the fields of the cout are displayed from left to right with "Some box data is" displayed next. Finally, the result of the return from get_volume() is output in int format, the type of the returned value. The end result is that the output is not in the expected order when lines 11 through 13 are executed. (The output is not what you would intuitively expect to happen so appears to be a deficiency in the language. A call to Borland International, the writers of Turbo C++ and Borland C++, verified that this code is operating correctly.) Your compiler may not execute this program correctly. You may need to find a compiler switch to permit mixing printf() and cout outputs, or you may need to convert the printf() statements to cout outputs to get the program to operate properly.

We still have the problem of mixing cout and printf() output as discussed in chapter 1 while studying

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap04.htm (5 of 8)02.03.2005 09:10:00

Page 29: C++ Language Tutorial

C++ Tutorial - Chapter 4

the program named MESSAGE.CPP. Eventually, all conforming compilers will overcome this problem.

Lines 15 through 18 are similar to any two of the lines of code in lines 11 through 13, but are each separated into two lines so the output is in the expected order.

Be sure to compile and execute DEFAULT.CPP after you understand it. Note that the funny output order will appear again later in this tutorial.

VARIABLE NUMBER OF ARGUMENTS

Example program ------> VARARGS.CPP

Examine the program named VARARGS.CPP for an illustration of the use of a variable number of arguments in a function call.

We have gone to a lot of trouble to get the compiler to help us by carefully checking how many parameters we use in the function calls and checking the types of the parameters. On rare occasion, we may wish to write a function that uses a variable number of parameters. The printf() function is a good example of this. ANSI-C has a series of three macros available in the "stdarg.h" header file to allow the use of a variable number of arguments. These are available for use with C++ also, but we need a way to eliminate the stronger type checking that is done with all C++ functions. The three dots illustrated in line 6 will do this for us. This prototype says that a single argument of type int is required as the first parameter, then no further type checking will be done by the compiler.

You will note that the main program consists of three calls to the function, each with a different number of parameters, and the system does not balk at the differences in the function calls. In fact, you could put as many different types as you desire in the calls. As long as the first one is an int type variable, the system will do its best to compile and run it for you. Of course the compiler is ignoring all type checking beyond the first parameter so it is up to you to make sure you use the correct parameter types in this call.

In this case, the first parameter gives the system the number of additional parameters to look for and handle. In this simple program, we simply display the numbers on the monitor to illustrate that they really did get handled properly.

Of course, you realize that using a variable number of arguments in a function call can lead to very obscure code and should be used very little in a production program, but the capability exists if you need it. Be sure to compile and execute this program.

FUNCTION NAME OVERLOADING

Example program ------> OVERLOAD.CPP

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap04.htm (6 of 8)02.03.2005 09:10:00

Page 30: C++ Language Tutorial

C++ Tutorial - Chapter 4

Examine the file named OVERLOAD.CPP for an example of a program with a few function names overloaded. This is not possible in ANSI-C, but is perfectly legal and in fact used quite regularly in C++. At first this will seem a bit strange, but it is one of the keystones of object oriented programming. You will see its utility and purpose very clearly in later chapters of this tutorial.

You will notice in this example program that there are three functions, in addition to the main function, and all three have the same name. Your first question is likely to be, "Which function do you call when you call do_stuff()?" That is a valid question and the answer is, the function that has the correct number of formal parameters of the correct types. If do_stuff() is called with an integer value or variable as its actual parameter, the function beginning in line 25 will be called and executed. If the single actual parameter is of type float, the function beginning in line 30 will be called, and if two floats are specified, the function beginning in line 36 will be called.

It should be noted that the return type is not used to determine which function will be called. Only the types of the formal parameters are used to determine which overloaded function will be called.

The keyword overload used in line 4 tells the system that you really do intend to overload the name do_stuff, and the overloading is not merely an oversight. This is only required in very early versions of C++. Newer versions of C++ do not require the keyword overload but, at least for the time being, allows it to be used to prevent breaking the existing body of C++ code. It is not necessary to use this keyword because, when overloading is used in C++, it is generally used in a context in which it is obvious that the function name is overloaded.

When the final ANSI-C++ standard is completed, the use of this word may not be permitted. As was mentioned earlier, the C++ language is changing and we must be willing to change with it.

The actual selection of which function to call is done at compile time, not at execution time, so the program is not slowed down. If each of the overloaded function names were changed to different names, each being unique, there would be no difference in execution size or speed of the resulting program.

Overloading of function names may seem very strange to you, and it is strange if you are used to the rules of K&R or ANSI-C programming. As you gain experience with C++, you will feel very comfortable with this, and you will use it a lot in your C++ programming.

Note the use of the keyword const used in some of the function prototypes and headers. Once again, this prevents the programmer from accidentally changing the formal parameter within the function. In a function as short as these, there is no real problem with an accidental assignment. In a real function that you occasionally modify, you could easily forget the original intention of the use of a variable and attempt to change it during an extended debugging session.

PROGRAMMING EXERCISES

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap04.htm (7 of 8)02.03.2005 09:10:00

Page 31: C++ Language Tutorial

C++ Tutorial - Chapter 4

1. Change the type of wings in the prototype of PROTYPE1.CPP to float so that it disagrees with the function definition to see if you get a compilation error.

2. Change the function definition in PROTYPE1.CPP to agree with the changed prototype. Compile and execute the program without changing the calls in lines 12 and 13. Explain the results.

3. In DEFAULT.CPP, remove the default value from the prototype for height only to see what kind of compiler error you get. Only the last values of the list can be defaulted.

4. In OVERLOAD.CPP, change the names of the three functions so that each is a unique name and compare the size of the resulting executable file with that given for the present program.

Advance to Chapter 5

Return to the Table of Contents

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap04.htm (8 of 8)02.03.2005 09:10:00

Page 32: C++ Language Tutorial

C++ Tutorial - Chapter 5

C++ Tutorial - Chapter 5

ENCAPSULATION

As mentioned in Chapter 1, object oriented programming will seem very unnatural to a programmer with a lot of procedural programming experience. This chapter is the beginning of the definition of object oriented programming, and we will study the topic of encapsulation which is a "divide and conquer" technique. As we stated earlier, there are a lot of new terms used with object oriented programming. Don't be intimidated by the new terminology, we will study the terms one at a time in a meaningful order.

Encapsulation is the process of forming objects which we will discuss throughout this chapter. An encapsulated object is often called an abstract data type and it is what object oriented programming is all about. Without encapsulation, which involves the use of one or more classes, there is no object oriented programming. Of course there are other topics concerning object oriented programming, but this is the cornerstone.

WHY BOTHER WITH ENCAPSULATION?

We need encapsulation because we are human, and humans make errors. When we properly encapsulate some code, we actually build an impenetrable wall to protect the contained code from accidental corruption due to the silly little errors that we are all prone to make. We also tend to isolate errors to small sections of code to make them easier to find and fix. We will have a lot more to say about the benefits of encapsulation as we progress through the tutorial.

NO INFORMATION HIDING

Example program ------> OPEN.CPP

The program named OPEN.CPP is a really stupid program because it does next to nothing, but it will be the beginning point for our discussion of encapsulation, otherwise known as information hiding. Information hiding is an important part of object oriented programming and you should have a good grasp of what it is by the time we finish this chapter.

A very simple structure is defined in lines 4 through 7 which contains a single int type variable within the structure. This is sort of a silly thing to do, but it will illustrate the problem we wish to overcome in this chapter. Three variables are declared in line 11, each of which contains a single int type variable and each of the three variables are available for use anywhere within the main() function. Each variable can be assigned, incremented, read, modified, or have any number of operations performed on it. A few of the operations are illustrated in lines 14 through 22 and should be self explanatory to anyone with a little experience with the C programming language.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap05.htm (1 of 17)02.03.2005 09:10:06

Page 33: C++ Language Tutorial

C++ Tutorial - Chapter 5

An isolated local variable named piggy is declared and used in the same section of code to illustrate that there is nothing magic about this code. Figure 5-1 is a graphical representation of the data space after execution of line 17.

Study this simple program carefully because it is the basis for beginning our study of encapsulation. Be sure to compile and execute this program, then we will go on to the next example program where we will see our first example of real information hiding.

INFORMATION HIDING

Example program ------> CLAS.CPP

Examine the program named CLAS.CPP for our first example of a program with a little information hiding contained in it. This program is identical to the last one except for the way it does a few of its operations. We will take the differences one at a time and explain what is happening. Keep in mind that this is a trivial program and the safeguards built into it are not needed for such a simple program but are used here to illustrate how to use these techniques in a larger much more complicated program.

The first difference is that we have a class instead of a structure beginning in line 4 of this program. The only difference between a class and a structure is that a class begins with a private section whereas a structure begins with a public section. The keyword class is used to declare a class as illustrated here.

The class named one_datum is composed of the single variable named data_store and two functions, one named set() and the other named get_value(). A more complete definition of a class is a group of variables, and one or more functions that can operate on that data. Stay with us, we will tie this all together in a meaningful and useful way very soon.

WHAT IS A PRIVATE SECTION?

All data at the beginning of a class defaults to private. Therefore, the data at the beginning of the class

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap05.htm (2 of 17)02.03.2005 09:10:06

Page 34: C++ Language Tutorial

C++ Tutorial - Chapter 5

cannot be accessed outside of the class, it is hidden from any outside access. Therefore, the variable named data_store which is a part of the object (an object will be defined completely later) named dog1 defined in line 24, is not available for use anywhere in the main() program. It is as if we have built a "brick wall" around the variables to protect them from accidental corruption by outside programming influences. It seems a little dumb to define a variable in the main() program that we cannot use, but that is exactly what we did.

Figure 5-2 is a graphical representation of the class with its "brick wall" built around the data to protect it. You will notice the small peep holes we have opened up to allow the user to gain access to the functions get() and get_value(). The peep holes were opened by declaring the functions in the public section of the class.

WHAT IS A PUBLIC SECTION?

A new keyword, public, is introduced in line 7 which states that anything following this keyword can be accessed from outside of this class. Because the two functions are declared following the keyword public, they are both public and available for use by any calling program that is within the scope of this object. This essentially opens two small peepholes in the solid wall of protection that we built around the class. You should keep in mind that the private variable is not available to the calling program. Thus, we can only use the variable by calling one of the two functions defined within the public part of the class. These are called member functions because they are members of the class.

Since we have declared two functions, we need to define them by saying what each function will actually do. This is done in lines 12 through 20 where they are each defined in the normal way, except that the class name is prepended onto the function name and separated from it by a double colon. These two function definitions are called the implementation of the functions. The class name is required because we can use the same function name in other classes and the compiler must know with which class to associate each function implementation.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap05.htm (3 of 17)02.03.2005 09:10:06

Page 35: C++ Language Tutorial

C++ Tutorial - Chapter 5

One of the key points to be made here is that the private data contained within the class is available within the implementation of the member functions of the class for modification or reading in the normal manner. You can do anything with the private data within the function implementations which are a part of that class, but the private data of other classes is hidden and not available within the member functions of this class. This is the reason we must prepend the class name to the function names of this class when defining them. Figure 5-3 depicts the data space following execution of line 30.

It would be well to mention at this point that it is legal to declare variables and functions in the private part, and additional variables and functions in the public part also. In most practical situations, variables are declared in only the private part and functions are declared in only the public part of a class definition. Occasionally, variables or functions are declared in the other part. This sometimes leads to a very practical solution to a particular problem, but in general, the entities are used only in the places mentioned.

In C++ we have four scopes of variables, global, local, file, and class. Global variables are available anywhere in the defining file and in other files. Local variables are localized to a single function. File variables, those that are defined outside of any function, are available anywhere in a file following their definition. A variable with class scope is available anywhere within the scope of a class, including the implementation code, and nowhere else. The variable named data_store has a class scope.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap05.htm (4 of 17)02.03.2005 09:10:06

Page 36: C++ Language Tutorial

C++ Tutorial - Chapter 5

You must be very confused by this point since we have given a lot of rules but few reasons for doing all of this. Stay with us and you will soon see that there are very practical reasons for doing all of this.

MORE NEW TERMINOLOGY

As with most new technologies, developers seem to delight in making up new names for all aspects of their new pet. Object oriented programming is no different, so we must learn new names for some of our old familiar friends if we are going to learn how to effectively use it. To help you learn this new programming terminology, we will list a few of them here and begin using them in the text to get you used to seeing and using them. You will not understand them all yet, but we need to introduce them early.

● A class is a grouping of data and methods (functions). A class is very much like a structure type as used in ANSI-C, it is only a pattern to be used to create a variable which can be manipulated in a program.

● An object is an instance of a class, which is similar to a variable defined as an instance of a type. An object is what you actually use in a program since it contains values and can be changed.

● A method is a function contained within the class. You will find the functions used within a class often referred to as methods in programming literature.

● A message is the same thing as a function call. In object oriented programming, we send messages instead of calling functions. For the time being, you can think of them as identical. Later in this tutorial we will see that they are in fact slightly different.

With all the new terminology, we will continue our study of the program named CLAS.CPP and show you how to use the class. We can now say that we have a class composed of one variable and two methods. The methods operate on the variable contained in the class when they receive messages to do so. In this tutorial we will use the terms object and variable interchangeably because both names are very descriptive of what the object really is.

This is a small point but it could be easily overlooked. Lines 8 and 9 of this program are actually the prototypes for the two methods, and is our first example of the use of a prototype within a class. This is the reason we spent extra time studying prototypes in the last chapter. You will notice line 8 which says that the method named set() requires one parameter of type int and returns nothing, hence the return type is void. The method named get_value() however, according to line 9, has no input parameters but returns an int type value to the caller.

SENDING A MESSAGE

Following all of the definitions in lines 1 through 20, we finally come to the program where we actually use the class. In line 24 we define three objects of the class one_datum and name the objects dog1, dog2, and dog3. You will notice that the keyword class is not included in this line because it is not needed. Each object contains a single data point which we can set through use of the method set() or

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap05.htm (5 of 17)02.03.2005 09:10:06

Page 37: C++ Language Tutorial

C++ Tutorial - Chapter 5

read through use of the method get_value(), but we cannot directly set or read the value of the data point because it is hidden within the "block wall" around the class. In line 27, we send a message to the object named dog1 instructing it to set its internal value to 12, and even though this looks like a function call, it is properly called sending a message to a method. Remember that the object named dog1 has a method associated with it called set() that sets its internal value to the actual parameter included within the message. You will notice that the form is very much like the means of accessing the elements of a structure. You mention the name of the object with a dot connecting it to the name of the method. In a similar manner, we send a message to each of the other two objects, dog2 and dog3, to set their values to those indicated.

Lines 32 and 33 have been commented out because the operations are illegal. The variable named data_store is private and therefore not available to the code outside of the object itself. It should be obvious, but it will be pointed out that the data contained within the object named dog1 is not available within the methods of dog2 or dog3 because they are different objects. These rules are all devised to help you develop better code more quickly and you will soon see how they help.

The other method defined for each object is used in lines 35 through 37 to illustrate how it can be used. In each case, another message is sent to each object and the returned result is output to the monitor via the stream library.

USING A NORMAL VARIABLE

There is another variable named piggy declared and used throughout this example program that illustrates that a normal variable can be intermixed with the objects and used in the normal manner. The use of this variable should pose no problem to you, so after you understand the program, be sure to compile and execute it. It would be a good exercise for you to remove the comments from lines 32 and 33 to see what kind of error message your compiler issues.

This program illustrates information hiding but it will not be clear to you that it really does anything worthwhile until we study the next two programs. Be sure to compile and execute this program, then remove the comments from lines 32 and 33 as suggested, to see the error messages issued.

A PROGRAM WITH PROBLEMS

Example program ------> OPENPOLE.CPP

Examine the program named OPENPOLE.CPP for an example of a program with a few serious problems that will be overcome in the next example program by using the principles of encapsulation.

We have two structures declared, one being a rectangle and the other a pole. The data fields should be self explanatory with the exception of the depth of the flagpole which is the depth it is buried in the ground, the overall length of the pole is therefore the sum of the length and the depth.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap05.htm (6 of 17)02.03.2005 09:10:06

Page 38: C++ Language Tutorial

C++ Tutorial - Chapter 5

Figure 5-4 depicts the data space for this program after execution of line 34. Based on your experience with ANSI-C, you should have no problem understanding exactly what this program is doing, but you may be a bit confused at the meaning of the result found in line 40 where we multiply the height of the square with the width of the box. This is perfectly legal to do in ANSI-C or C++, but the result has no earthly meaning because the data are for two different entities. Likewise, the result calculated in line 42 is even sillier because the product of the height of the square and the depth of the flagpole has absolutely no meaning in any physical system we can think up. The error is obvious in a program as simple as this, but in a large production program it is very easy for such problems to be inadvertently introduced into the code and the errors can be very difficult to find.

Wouldn't it be neat if we had a way to prevent such stupid things from happening in a large production program. If we had a good program that defined all of the things we can do with a square and another program that defined everything we could do with a pole, and if the data could be kept mutually exclusive, we could prevent these silly things from happening. If these entities must interact, they cannot be put into separate programs, but they can be put into separate classes to achieve the desired goal.

It should come as no real surprise to you that the next program will do just those things for us and do it in a very elegant way. Before proceeding on to the next example program, you should compile and execute this one even though it displays some silly results.

OBJECTS PROTECT DATA

Example program ------> CLASPOLE.CPP

Examine the program named CLASPOLE.CPP as an example of data protection in a very simple program.

In this program, the rectangle is changed to a class with the same two variables which are now private,

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap05.htm (7 of 17)02.03.2005 09:10:06

Page 39: C++ Language Tutorial

C++ Tutorial - Chapter 5

and two methods which can manipulate the private data. One method is used to initialize the values of the objects created and the other method returns the area of the object. The two methods are defined in lines 13 through 22 in the manner described earlier in this chapter. The pole is left as a structure to illustrate that the two can be used together and that C++ is truly an extension of ANSI-C.

In line 35 we define two objects, once again named box and square, but this time we cannot assign values directly to their individual components because they are private elements of the class. Figure 5-5 is a graphical illustration of the two objects available for use within the calling program. Lines 38 through 40 are commented out for that reason and the messages are sent to the objects in lines 42 and 43 to tell them to initialize themselves to the values input as parameters. The flag_pole is initialized in the same manner as in the previous program. Using the class in this way prevents us from making the silly calculations we did in the last program, because we can only calculate the area of an object by using the data stored within that object. The compiler is now being used to prevent the erroneous calculations. The end result is that the stupid calculations we did in the last program are not possible in this program, so lines 52 through 55 have been commented out. Once again, it is difficult to see the utility of this in such a simple program. In a large program, using the compiler to enforce the rules can pay off in a big way.

Even though the square and the box are both objects of class rectangle, their private data is hidden from each other such that neither can purposefully or accidentally change the other's data.

This is the abstract data type mentioned earlier in this chapter, a model with a set of private variables for data storage and a set of operations that can be performed on that stored data. The only operations that can be performed on the data are those defined by the methods, which prevents many kinds of erroneous or silly operations. Encapsulation and data hiding bind the data and procedures, or methods, tightly together and limit the scope and visibility of each. Once again, we have the divide and conquer technique in which an object is separated from the rest of the code and carefully developed in complete

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap05.htm (8 of 17)02.03.2005 09:10:06

Page 40: C++ Language Tutorial

C++ Tutorial - Chapter 5

isolation from it. Only then is it integrated into the rest of the code with a few very simple interfaces.

Someone did a study several years ago in which they determined that programmers accidentally corrupted data much more often than they accidentally corrupted code. So it was determined that if the data could be protected from accidental corruption, the quality of the software could be improved. This is where the idea of information hiding originated and it has proven itself to be very valuable over the years.

HAVE YOU EVER USED THIS TECHNIQUE BEFORE?

A good example of the use of this technique is in the file commands you have been using with ANSI-C. The data in the file is only available through the predefined functions provided by your compiler writer. You have no direct access to the actual data because it is impossible for you to address the actual data stored on the disk. The data is therefore private data, as far as you are concerned, but the available functions are very much like methods in C++.

There are two aspects of this technique that really count when you are developing software. First, you can get all of the data you really need from the file system because the interface is complete, but secondly, you cannot get any data that you do not need. You are prevented from getting into the file handling system and accidentally corrupting some data stored within it. You are also prevented from using the wrong data because the functions available demand a serial access to the data. I should mention that this is a very weak example because it is very easy for a knowlegeable C programmer to break the encapsulation provided by the file system.

Another example of weak encapsulation is the monitor and keyboard handling routines. You are prevented from getting into the workings of them and corrupting them accidentally, but you are provided with all of the data interfaces that you really need to effectively use them.

Suppose you are developing a program to analyze some characteristics of flagpoles. You would not wish to accidentally use some data referring to where the flagpole program was stored on your hard disk as the height of the flagpole, nor would you wish to use the cursor position as the flagpole thickness or color. All code for the flagpole is developed alone, and only when it is finished, is it available for external use. When using it, you have a very limited number of operations which you can do with the class. The fact that the data is hidden from you protects you from accidentally doing such a thing when you are working at midnight to try to meet a schedule. Once again, this is referred to as information hiding and is one of the primary advantages of object oriented programming over procedural techniques.

Based on the discussion given above you can see that object oriented programming is not really new, since it has been used in a small measure for as long as computers have been popular. The newest development, however, is in allowing the programmer to partition his programs in such a way that he too can practice information hiding to reduce the debugging time and improve the quality of his software.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap05.htm (9 of 17)02.03.2005 09:10:06

Page 41: C++ Language Tutorial

C++ Tutorial - Chapter 5

WHAT DOES THIS COST?

It should be clear that this technique will cost you something in efficiency because every access to the elements of the object will require the time and inefficiency of a call to a function, or perhaps I should be more proper and refer to it as a method. The time saved in building a large program, however, could easily be saved in debug time when it comes time to iron out the last few bugs. This is because a program made up of objects that closely match the application are much easier to understand than a program that does not.

This is obviously such a small program that it is silly to try to see any gain with this technique. In a real project however, it could be a great savings if one person developed all of the details of the rectangle, programmed it, and made it available to you to simply use. This is exactly what has been done for you if you consider the video monitor an object. There is a complete set of preprogrammed and debugged routines you can use to make the monitor do anything you wish it to do, all you have to do is study the interface to the routines and use them, expecting them to work. You have no need to study the implementation, nor are you required to understand it, provided that it works. As we mentioned earlier, it is impossible for you to multiply the size of your monitor screen by the depth of the flag pole because that information is not available to you to use in a corruptible way.

After you understand some of the advantages of this style of programming, be sure to compile and execute this program.

CONSTRUCTORS AND DESTRUCTORS

Example program ------> CONSPOLE.CPP

The file named CONSPOLE.CPP introduces constructors and destructors and should be examined at this time.

This example program is identical to the last example except that a constructor has been added as well as a destructor. The constructor always has the same name as the class itself and is declared in line 9, then defined in lines 15 through 19. The constructor is called automatically by the C++ system when the object is declared and prevents the use of an uninitialized variable. When the object named box is defined in line 48, the constructor is called automatically by the system. The constructor sets the values of height and width each to 6 in the object named box. This is printed out for reference in lines 51 and 52. Likewise, when the square is defined in line 48, the values of the height and the width of the square are each initialized to 6 when the constructor is called automatically.

A constructor is defined as having the same name as the class itself. In this case both are named rectangle. The constructor cannot have a return type associated with it because of the definition of C++. It actually has a predefined return type, a pointer to the object itself, but we will not be concerned about this until much later in this tutorial. Even though both objects are assigned values by the constructor,

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap05.htm (10 of 17)02.03.2005 09:10:06

Page 42: C++ Language Tutorial

C++ Tutorial - Chapter 5

they are initialized in lines 60 and 61 to new values and processing continues. Since we have a constructor that does the initialization, we should probably rename the method named initialize() something else but it illustrates the concept involved here.

The destructor is very similar to the constructor except that it is called automatically when each of the objects goes out of scope. You will recall that automatic variables have a limited lifetime because they cease to exist when the enclosing block in which they were declared is exited. When an object is about to be automatically deallocated, its destructor, if one exists, is called automatically. A destructor is characterized as having the same name as the class but with a tilde prepended to the class name. A destructor has no return type.

A destructor is declared in line 12 and defined in lines 32 through 36. In this case the destructor only assigns zeros to the variables prior to their being deallocated, so nothing is really accomplished. The destructor is only included for illustration of how it is used. If some blocks of memory were dynamically allocated within an object, the destructor should contains code to deallocate them prior to losing the pointers to them. This would return their memory to the free store for further use later in the program.

It is interesting to note that if a constructor is used for an object that is declared prior to the main() program, a global variable, the constructor will actually be executed prior to the execution of the main() program. In like manner, if a destructor is defined for such a variable, it will execute following the completion of execution of the main() program. This will not adversely affect your programs, but it is interesting to make note of.

OBJECT PACKAGING

Example program ------> BOXES1.CPP

Examine the file named BOXES1.CPP for an example of how not to package an object for universal use. This packaging is actually fine for a very small program, but is meant to illustrate to you how to split your program up into smaller, more manageable files when you are developing a large program or when you are part of a team developing a large system. The next three example files in this chapter will illustrate the proper method of packaging a class.

This program is very similar to the last one with the pole structure dropped and the class named box. The class is declared in lines 4 through 13, the implementation of the class is given in lines 16 through 35, and the use of the class is given in lines 38 through 52. With the explanation we gave about the last example program, the diligent student should have no problem understanding this program in detail.

INLINE IMPLEMENTATION

The method in line 11 contains the implementation for the method as a part of the declaration because it is very simple, and because it introduces another new topic which you will use often in C++

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap05.htm (11 of 17)02.03.2005 09:10:06

Page 43: C++ Language Tutorial

C++ Tutorial - Chapter 5

programming. When the implementation is included in the declaration, it will be assembled inline wherever this function is called leading to much faster code. This is because there is no function call overhead when making a call to the method. In some cases this will lead to code that is both smaller and faster. This is yet another illustration of the efficiency built into the C++ programming language. Inline code implementation in C++ accomplishes the same efficiency that the macro accomplishes in C, and is the constuct of choice for small functions.

Compile and execute this program in preparation for our study of the next three examples which are a repeat of this program in a slightly different form.

THE CLASS HEADER FILE

Example program ------> BOX.H

If you examine BOX.H carefully, you will see that it is only the class definition. No details are given of how the various methods are implemented except of course for the inline method named get_area(). This gives the complete definition of how to use the class with no implementation details. You would be advised to keep a hardcopy of this file available as we study the next two files. You will notice that it contains lines 4 through 13 of the previous example program named BOXES1.CPP. This is called the class header file and cannot be compiled or executed.

THE CLASS IMPLEMENTATION FILE

Example program ------> BOX.CPP

Examine the file named BOX.CPP for the implementation of the methods declared in the class header file. Notice that the class header file is included into this file in line 2 which contains the prototypes for its methods and the definitions of the variables to be manipulated. The code from lines 16 through 35 of BOXES1.CPP is contained in this file which is the implementation of the methods declared in the class named box.

This file can be compiled but it cannot be executed because there is no main entry point which is required for all ANSI-C or C++ programs. When it is compiled, the object code will be stored in the current directory and available for use by other programs. It should be noted here that the result of compilation is usually referred to as an object file because it contains object code. This use of the word object has nothing to do with the word object as used in object oriented programming. It is simply a matter of overloading the use of the word. The practice of referring to the compiled result as an object file began long before the technique of object oriented programming was ever considered.

The separation of the definition and the implementation is a major step forward in software engineering. The definition file is all the user needs in order to use this class effectively in a program. He needs no knowledge of the actual implementation of the methods. If he had the implementation available, he may

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap05.htm (12 of 17)02.03.2005 09:10:06

Page 44: C++ Language Tutorial

C++ Tutorial - Chapter 5

study the code and find a trick he could use to make the overall program slightly more efficient, but this would lead to nonportable software and possible bugs later if the implementor changed the implementation without changing the interface. The purpose of object oriented programming is to hide the implementation in such a way that the implementation can not affect anything outside of its own small and well defined boundary or interface.

You should compile this implementation file now and we will use the result with the next example program.

USING THE BOX OBJECT

Example program ------> BOXES2.CPP

Examine the file named BOXES2.CPP and you will find that the class we defined previously is used within this file. In fact, these last three programs taken together are identical to the program named BOXES1.CPP studied earlier.

The BOX.H file is included here, in line 3, since the definition of the box class is needed to declare three objects and use their methods. You should have no trouble seeing that this is a repeat of the previous program and will execute in exactly the same way. There is a big difference in BOXES1.CPP and BOXES2.CPP as we will see shortly.

A very important distinction must be made at this point. We are not merely calling functions and changing the terminology a little to say we are sending messages. There is an inherent difference in the two operations. Since the data for each object is tightly bound up within the object, there is no way to get to the data except through the methods and we send a message to the object telling it to perform some operation based on its internally stored data. However, whenever we call a function, we take along the data for it to work with as parameters since it doesn't contain its own data. Admittedly, the difference is slight, but you will see the new terminology used in the literature, and you need to realize that there is a slight difference.

Be sure to compile and execute this program, but when you come to the link step, you will be required to link this program along with the result of the compilation when you compiled the class named box. The file is probably named BOX.OBJ that must be linked with this file. You may need to consult the documentation for your C++ compiler to learn how to do this.

Depending on your compiler, this is your first opportunity to use either a project file, or the "make" facility included with your compiler. Regardless of which C++ compiler you are using, it would pay you to stop and learn how to use the multifile technique provided with your compiler because you will need to use it several times before the end of this tutorial. The nature of C++ tends to drive the programmer to use many files for a given programming project and you should develop the habit early.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap05.htm (13 of 17)02.03.2005 09:10:06

Page 45: C++ Language Tutorial

C++ Tutorial - Chapter 5

INFORMATION HIDING

The three example programs we have just studied illustrate a method of information hiding that can have a significant impact on the quality of software developed for a large project. Since the only information the user of the class really needs is the class header, that is all he needs to be given. The details of implementation can be kept hidden from him to prevent him from studying the details and possibly using a quirk of programming to write some rather obtuse code. Since he doesn't know exactly what the implementor did, he must follow only the definition given in the header file. This can have a significant impact on a large project. As mentioned earlier, accidental corruption of data is prevented also.

Another reason for hiding the implementation is economic. The company that supplied you with your C++ compiler gave you many library functions but did not supply the source code to the library functions, only the interface to each function. You know how to use the file access functions but you do not have the details of implementation, nor do you need them. Likewise a class library industry can develop which supplies users with libraries of high quality, completely developed and tested classes, for a licensing fee of course. Since the user only needs the interface defined, he can be supplied with the interface and the object (compiled) code for the class and can use it in any way he desires. The suppliers source code is protected from accidental or intentional compromise and he can maintain complete control over it.

It is very important that you understand the principles covered in this chapter before proceeding on to the next chapter. If you feel you are a little weak in any of the areas covered here, you should go over them again before proceeding on. A point that should be made here that may be obvious to you, is that it requires a considerable amount of forethought to effectively use classes.

ABSTRACT DATA TYPES

We mentioned the abstract data type at the beginning of this chapter and again briefly midway through, and it is time to describe it a little more completely. An abstract data type is a group of data, each of which can store a range of values, and a set of methods or functions that can operate on that data. Since the data are protected from any outside influence, it is protected and said to be encapsulated. Also, since the data is somehow related, it is a very coherent group of data that may be highly interactive with each other, but with little interaction outside the scope of its class.

The methods, on the other hand, are coupled to the outside world through the interface, but there are a limited number of contacts with the outside world and therefore a weak coupling with the outside. The object is therefore said to be loosely coupled to the outside world. Because of the tight coherency and the loose coupling, ease of maintenance of the software is greatly enhanced. The ease of maintenance may be the greatest benefit of object oriented programming.

It may bother you that even though the programmer may not use the private variables directly outside of the class, they are in plain sight and he can see what they are and can probably make a good guess at

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap05.htm (14 of 17)02.03.2005 09:10:06

Page 46: C++ Language Tutorial

C++ Tutorial - Chapter 5

exactly how the class is implemented. The variables could have been hidden completely out of sight in another file, but because the designers of C++ wished to make the execution of the completed application as efficient as possible, the variables were left in the class definition where they can be seen but not used.

FRIEND FUNCTIONS

A function outside of a class can be defined to be a friend function by the class which gives the friend free access to the private members of the class. This in effect, opens a small hole in the protective shield of the class, so it should be used very carefully and sparingly. There are cases where it helps to make a program much more understandable and allows controlled access to the data. Friend functions will be illustrated in some of the example programs later in this tutorial. It is mentioned here for completeness of this section. A single isolated function can be declared as a friend, as well as members of other classes, and even entire classes can be given friend status if needed in a program. Neither a constructor nor a destructor can be a friend function.

THE struct IN C++

The struct is still useable in C++ and operates just like it does in ANSI-C with one addition. You can include methods in a structure that operate on data in the same manner as in a class, but methods and data are automatically defaulted to be public at the beginning of a structure. Of course you can make any of the data or methods private by defining a private section within the structure. The structure should be used only for constructs that are truly structures. If you are building even the simplest objects, you are advised to use classes to define them.

A VERY PRACTICAL CLASS

The examples of encapsulation used in this chapter have all been extremely simple in order to illustrate the mechanics of encapsulation. Since it would be expedient to study a larger example, the date class is given for your instruction. The date class is a complete nontrivial class which can be used in any program to get the current date and print it as an ASCII string in any of four predefined formats. It can also be used to store any desired date and format it for display.

Example program ------> DATE.H

Examine the file named DATE.H which is the header file for the date class. This file is so well commented that we don't have much else to say about it. If you understand the principles covered in this chapter you should have no problem understanding this class. One thing that is new to you is the reserved word protected which is used in line 13. We will define this word in a couple of chapters. Until then, pretend that it means the same thing as private and you will be close enough for this present example. The code in lines 8 and 9 along with line 58 will be explained shortly. For the present time, simply pretend those lines of code are not there. Also the keyword static as used in lines 18 and 19 will

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap05.htm (15 of 17)02.03.2005 09:10:06

Page 47: C++ Language Tutorial

C++ Tutorial - Chapter 5

be explained later. These new constructs are added because we plan to use this class later when we study inheritance.

You should spend the time necessary to completely understand this class header, with the exception of the new things added, before going on to the implementation for this class.

Example program ------> DATE.CPP

The file named DATE.CPP is the implementation for the date class and once again, there is nothing unusual or difficult about this code. It uses very simple logic to store and format the date in a usable manner. You should study this code until you understand it completely before going on to the next example which will use the date class in a main program.

The constructor implementation in lines 14 through 25 use DOS system calls to get the current date. Unless you are using 16 bit DOS, these calls will not be compiled or executed properly because they are not portable. You can modify this code so it uses calls to your system or simply assign the member variables some default values. The purpose of this code is to illustrate the use of encapsulation and constructors, not how to read the real time clock and calendar on your particular computer.

Example program ------> USEDATE.CPP

The very simple program named USEDATE.CPP is a main program that uses the date class to list the current date and another date on the monitor. Once again, you should have no problem understanding this program so nothing more will be said about it.

You should spend the time necessary to understand these three files because they are the starting point for a practical track in the next few chapters. This class will be used in conjunction with others to illustrate single and multiple inheritance. Even though you do not understand all of the details of these files, spend enough time that you are comfortable with the structure and the major points of them.

We will continue our discussion of encapsulation in the next chapter.

PROGRAMMING EXERCISES

1. Add a method to CLAS.CPP which will supply the square of the stored value. Include some code in the main program to read and display the squared values.

2. Continuing with CLAS.CPP, add a constructor to initialize the stored value to 10 and add a few lines of code to the main program to display the values immediately following the object definition.

3. Add an output statement to the rectangle constructor of the program named CONSPOLE.CPP and another to the destructor to prove to yourself that they really are called by the system when we said they are.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap05.htm (16 of 17)02.03.2005 09:10:06

Page 48: C++ Language Tutorial

C++ Tutorial - Chapter 5

4. Write a more comprehensive program to use the date class presented at the end of this chapter.5. Write a name class which is somewhat similar to the date class which can store any name in

three parts and return the full name in any of several different formats such as the following;

John Paul Doe J. P. Doe Doe, John Paul and any other formats you desire.

Advance to Chapter 6

Return to the Table of Contents

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap05.htm (17 of 17)02.03.2005 09:10:06

Page 49: C++ Language Tutorial

C++ Tutorial - Chapter 6

C++ Tutorial - Chapter 6

MORE ENCAPSULATION

WHY BOTHER WITH ENCAPSULATION?

We asked this question earlier, but now that we have a little experience, we can provide a much better answer. Encapsulation protects data from accidental corruption, and constructors guarantee proper initialization. Both prevent errors that we are very prone to make since we are thinking only about the internals of the class when we are writing it. Later, when we are actually using the class, we have no need to concern ourselves with the internal structure or operation, but can spend our energies using the class to solve the overall problem we are working on. As you may guess, there is a lot more to learn about the use and benefits of classes so we will dive right into some new topics.

The purpose of this chapter is to illustrate how to use some of the traditional aspects of C or C++ with classes and objects. Pointers to an object as well as pointers within an object will be illustrated. Arrays embedded within an object, and an array of objects will be illustrated. Since objects are simply another C++ data construct, all of these things are possible and can be used if needed.

In order to have a systematic study, we will use the program named BOXES1.CPP from the last chapter as a starting point and we will add a few new constructs to it for each example program. You will recall that it was a very simple program with the class definition, the class implementation, and the main program all in one file. This was selected as a starting point because we will eventually make changes to all parts of the program and it will be convenient to have it all in a single file for illustrative purposes. It must be kept in mind however that the proper way to use these constructs is to separate them into the three files as was illustrated in BOX.H, BOX.CPP, and BOXES2.CPP in the last chapter. This allows the implementor of box to supply the user with only the interface, namely BOX.H. Not giving him the implementation file named BOX.CPP, is practicing the technique of information hiding. As we have said many times, it seems silly to break up such a small program into three separate files, and it is sort of silly. The last chapter of this tutorial will illustrate a program large enough to require dividing the program up into many separate files.

AN ARRAY OF OBJECTS

Example program ------> OBJARRAY.CPP

Examine the file named OBJARRAY.CPP for our first example of an array of objects. This file is nearly identical to the file named BOX1.CPP until we come to line 45 where an array of 4 boxes are defined.

Recalling the operation of the constructor you will remember that each of the four box objects will be initialized to the values defined within the constructor since the constructor will be executed for each

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap06.htm (1 of 17)02.03.2005 09:10:11

Page 50: C++ Language Tutorial

C++ Tutorial - Chapter 6

box as they are defined. In order to define an array of objects, a constructor for that object with no parameters must be available. (We have not yet illustrated a constructor with initializing parameters, but we will in the next program.) This is an efficiency consideration since it would probably be an error to initialize all elements of an array of objects to the same value. We will see the results of executing the constructor when we compile and execute the file later.

Line 50 defines a for loop that begins with 1 instead of the normal starting index for an array leaving the first object, named group[0], to use the default values stored when the constructor was called. You will observe that sending a message to one of the objects uses the same construct as is used for any object. The name of the array followed by its index in square brackets is used to send a message to one of the objects in the array. This is illustrated in line 51 and the operation of that code should be clear to you. The other method is called in the output statement in lines 58 and 59 where the area of the four boxes in the group array are listed on the monitor.

Another fine point should be mentioned. The integer variable named index is defined in line 50 and is still available for use in line 57 since we have not yet left the enclosing block which begins in line 44 and extends to line 68. But this is true only if your compiler is aging slightly. If you have a new compiler, you may find that index is undefined in line 57. See the discussion in Chapter 1 if this is not clear.

DECLARATION AND DEFINITION OF A VARIABLE

An extra variable was included for illustration, the one named extra_data in line seven. Since the keyword static is used to modify this variable in line 8, it is an external variable and only one copy of this variable will ever exist. All seven objects of this class share a single copy of this variable which is global to the objects defined in line 44.

The variable is actually only declared here which says it will exist somewhere, but it is not yet defined. A declaration says the variable will exist and gives it a name, but the definition actually defines a place to store it somewhere in the computers memory space. By definition, a static variable can be declared in a class header but it cannot be defined there, so it is usually defined in the implementation file. In this case it is defined in line 17 and can then be used throughout the class.

Figure 6-1 is a graphical representation of some of the variables. Note that the objects named large, group[0], group[1], and group[2] are not shown but they also share the variable named extra_data. They are not shown in order to simplify the picture and enhance the clarity. Each object has its own personal length and width because they are not declared static.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap06.htm (2 of 17)02.03.2005 09:10:11

Page 51: C++ Language Tutorial

C++ Tutorial - Chapter 6

Line 24 of the constructor sets the single global variable to 1 each time an object is declared. Only one assignment is necessary so the other six are actually wasted code. It is generally not a good idea to assign a value to a static member in a constructor, but in this case, it illustrates how the static variable works. To illustrate that there is only one variable shared by all objects of this class, the method to read its value also increments it. Each time it is read in lines 61 through 65, it is incremented and the result of the execution proves that there is only a single variable shared by all objects of this class. You will also note that the method named get_extra() is defined within the class declaration so it will be assembled into the final program as inline code.

You will recall the 2 static variables we declared in lines 18 and 19 of DATE.H in chapter 5 of this tutorial. We defined them in lines 9 and 10 of DATE.CPP and overlooked a complete explanation of what they did at that time. The declaration and definition of these variables should be considered a good example of the proper place to put these constructs in your classes.

Be sure you understand this program and especially the static variable, then compile and execute it to see if you get the same result as listed at the end of the program.

A STRING WITHIN AN OBJECT

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap06.htm (3 of 17)02.03.2005 09:10:11

Page 52: C++ Language Tutorial

C++ Tutorial - Chapter 6

Example program ------> OBJSTRNG.CPP

Examine the program named OBJSTRNG.CPP for our first example of an object with an embedded string. Actually, the object does not have an embedded string, it has an embedded pointer, but the two work so closely together that we can study one and understand both.

You will notice that line 8 contains a pointer to a char named line_of_text. The constructor contains an input parameter which is a pointer to a string which will be copied to the string named line_of_text within the constructor. We could have defined the variable line_of_text as an actual array in the class, then used strcpy() to copy the string into the object and everything would have worked the same, but we will leave that as an exercise for you at the end of this chapter. It should be pointed out that we are not limited to passing a single parameter to a constructor. Any number of parameters can be passed, as will be illustrated later.

You will notice that when the three boxes are defined this time, we supply a string constant as an actual parameter with each declaration which is used by the constructor to assign the string pointer some data to point to. When we call get_area() in lines 50 through 54, we get the message displayed and the area returned. It would be prudent to put these operations in separate methods since there is no apparent connection between printing the message and calculating the area, but it was written this way to illustrate that it can be done. What this really says is that it is possible to have a method that has a side effect, the message output to the monitor, and a return value, the area of the box. However, as we discussed in chapter 4 when we studied DEFAULT.CPP, the order of evaluation is sort of funny, so we broke each line into two lines.

After you understand this program, compile and execute it.

AN OBJECT WITH AN INTERNAL POINTER

Example programs ------> OBJINTPT.CPP

The program named OBJINTPT.CPP is our first example program with an embedded pointer which will be used for dynamic allocation of data.

In line 8 we declare a pointer to an integer variable, but it is only a pointer, there is no storage associated with it. The constructor therefore allocates an integer type variable on the heap for use with this pointer in line 22. It should be clear to you that the three objects defined in line 46 each contain a pointer which points into the heap to three different locations. Each object has its own dynamically allocated variable for its own private use. Moreover each has a value of 112 stored in its dynamically allocated data because line 23 stores that value in each of the three locations, once for each call to the constructor.

In such a small program, there is no chance that we will exhaust the heap, so no test is made for unavailable memory. In a real production program, it would be mandatory to test that the value of the

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap06.htm (4 of 17)02.03.2005 09:10:11

Page 53: C++ Language Tutorial

C++ Tutorial - Chapter 6

returned pointer is not NULL to assure that the data actually did get allocated.

The method named set() has three parameters associated with it and the third parameter is used to set the value of the new dynamically allocated variable. There are two messages passed, one to the small box and one to the large box. As before, the medium box is left with its default values.

The three areas are displayed followed by the three stored values in the dynamically allocated variables, and we finally have a program that requires a destructor in order to be completely proper. If we simply leave the scope of the objects as we do when we leave the main() program, we will leave the three dynamically allocated variables on the heap with nothing pointing to them. They will be inaccessible and will therefore represent wasted storage on the heap. For that reason, the destructor is used to delete the variable which the pointer named point is referencing, as each object goes out of existence. In this case, lines 38 and 39 assign zero to variables that will be automatically deleted. Even though these lines of code really do no good, they are legal statements.

Actually, in this particular case, the variables will be automatically reclaimed when we return to the operating system because all program cleanup is done for us at that time. This is an illustration of good programming practice, that of cleaning up after yourself when you no longer need some dynamically allocated variables.

One other construct should be mentioned again, that of the inline method implementations in line 12 and 13. As we mentioned in chapter 5, inline functions can be used where speed is of the utmost in importance since the code is assembled inline rather than by actually making a method call. Since the code is defined as part of the declaration, the system will assemble it inline, and a separate implementation for these methods is not needed. If the inline code is too involved, the compiler is allowed to ignore the inline request and will actually assemble it as a separate method, but it will do it invisibly to you and will probably not even tell you about it.

Remember that we are interested in using information hiding and inline code prevents hiding of the implementation, putting it out in full view. Many times you will be more interested in speeding up a program than you are in hiding a trivial implementation. Since most inline methods are trivial, you should feel free to use the inline code construct wherever it is expedient. Be sure to compile and execute this program.

A DYNAMICALLY ALLOCATED OBJECT

Example program ------> OBJDYNAM.CPP

Examine the file named OBJDYNAM.CPP for our first look at a dynamically allocated object. This is not any different than any other dynamically allocated object, but an example is always helpful.

In line 40 we define a pointer to an object of type box and since it is only a pointer with nothing to point

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap06.htm (5 of 17)02.03.2005 09:10:11

Page 54: C++ Language Tutorial

C++ Tutorial - Chapter 6

to, we dynamically allocate an object for it in line 45, with the object being created on the heap just like any other dynamically allocated variable. When the object is created in line 45, the constructor is called automatically to assign values to the two internal storage variables. Note that the constructor is not called when the pointer is defined since there is nothing to initialize. It is called when the object is allocated.

Reference to the components of the object are handled in much the same way that structure references are made, through use of the pointer operator as illustrated in lines 51 through 53. Of course you can use the pointer dereferencing method without the arrow such as (*point).set(12, 12); as a replacement for line 52 but the arrow notation is much more universal and should be used. Finally, the object is deleted in line 55 and the program terminates. If there were a destructor for this class, it would be called automatically as part of the delete statement to clean up the object prior to deletion.

You have probably noticed by this time that the use of objects is not much different from the use of structures. Be sure to compile and execute this program after you have studied it thoroughly.

AN OBJECT WITH A POINTER TO ANOTHER OBJECT

Example program ------> OBJLIST.CPP

The program named OBJLIST.CPP contains an object with an internal reference to another object of its own class. This is the standard structure used for a singly linked list and we will keep the use of it very simple in this program.

The constructor contains the statement in line 22 which assigns the pointer the value of NULL to initialize the pointer. This is a good idea for all of your programming, don't allow any pointer to point off into space, but initialize all pointers to something. By assigning the pointer within the constructor, you guarantee that every object of this class will automatically have its pointer initialized. It will be impossible to overlook the assignment of one of these pointers.

Two additional methods are declared in lines 13 and 14 with the one in line 14 having a construct we have not yet mentioned in this tutorial. This method returns a pointer to an object of the box class. As you are aware, you can return a pointer to a struct in standard C, and this is a parallel construct in C++. The implementation in lines 49 through 52 returns the pointer stored as a member variable within the object. We will see how this is used when we get to the actual program.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap06.htm (6 of 17)02.03.2005 09:10:11

Page 55: C++ Language Tutorial

C++ Tutorial - Chapter 6

An extra pointer named box_pointer is defined in the main program for use later and in line 67 we make the embedded pointer within the small box point to the medium box. Line 68 makes the embedded pointer within the medium box point to the large box. We have effectively generated a linked list with three elements. In line 70 we make the extra pointer point to the small box. Continuing in line 71 we use it to refer to the small box and update it to the value contained in the small box which is the address of the medium box. We have therefore traversed from one element of the list to another by sending a message to one of the objects. If line 71 were repeated exactly as shown, it would cause the extra pointer to refer to the large box, and we would have traversed the entire linked list which is only composed of three elements. Figure 6-2 is a graphical representation of the data space following execution of line 70. Note that only a portion of each object is actually depicted here to keep it simple.

ANOTHER NEW KEYWORD this

Another new keyword is available in C++, the keyword this. The word this is defined within any object as being a pointer to the object in which it is contained. It is implicitly defined as;

class_name *this;

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap06.htm (7 of 17)02.03.2005 09:10:11

Page 56: C++ Language Tutorial

C++ Tutorial - Chapter 6

and is initialized to point to the object for which the member function is invoked. This pointer is most useful when working with pointers and especially with a linked list when you need to reference a pointer to the object you are inserting into the list. The keyword this is available for this purpose and can be used in any object. Actually the proper way to refer to any variable within a list is through use of the predefined pointer this, by writing this->variable_name, but the compiler assumes the pointer is used, and we can simplify every reference by omitting the pointer. Use of the keyword this is not illustrated in a program at this point, but will be used in one of the larger example programs later in this tutorial.

You should study this program until you understand it completely then compile and execute it in preparation for our next example program.

A LINKED LIST OF OBJECTS

Example program ------> OBJLINK.CPP

The next example program in this chapter is named OBJLINK.CPP and is a complete example of a linked list written in object oriented notation.

This program is very similar to the last one. In fact it is identical until we get to the main() program. You will recall that in the last program the only way we had to set or use the embedded pointer was through use of the two methods named point_at_next() and get_next() which are listed in lines 42 through 52 of the present program. We will use these to build up our linked list then traverse and print the list. Finally, we will delete the entire list to free the space on the heap.

In lines 57 through 59 we define three pointers for use in the program. The pointer named start will always point to the beginning of the list, but temp will move down through the list as we create it. The pointer named box_pointer will be used for the creation of each object. We execute the loop in lines 62 through 75 to generate the list where line 64 dynamically allocates a new object of the box class and line 65 fills it with nonsense data for illustration. If this is the first element in the list, the start pointer is set to point to this element, but if elements already exist, the last element in the list is assigned to point to the new element. In either case, the temp pointer is assigned to point to the last element of the list, in preparation for adding another element if there is another element to be added.

In line 78, the pointer named temp is caused to point to the first element and it is used to increment its way through the list by updating itself in line 82 during each pass through the loop. When temp has the value of NULL, which it gets from the last element of the list, we are finished traversing the list.

Finally, we delete the entire list by starting at the beginning and deleting one element each time we pass through the loop in lines 87 through 92.

A careful study of the program will reveal that it does indeed generate a linked list of ten elements, each element being an object of class box. The length of this list is limited by the practicality of how large a

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap06.htm (8 of 17)02.03.2005 09:10:11

Page 57: C++ Language Tutorial

C++ Tutorial - Chapter 6

list we desire to print out, but it could be lengthened to many thousands of these simple elements provided you have enough memory available to store them all.

Once again, the success of the dynamic allocation is not checked as it should be in a correctly written program. Be sure to compile and execute this example program.

NESTING OBJECTS

Example program ------> NESTING.CPP

Examine the program named NESTING.CPP for an example of nesting classes which results in nested objects. A nested object could be illustrated with your computer in a rather simple manner. The computer itself is composed of many items which work together but work entirely differently, such as a keyboard, a disk drive, and a power supply. The computer is composed of these very dissimilar items and it is desirable to discuss the keyboard separately from the disk drive because they are so different. A computer class could be composed of several objects that are dissimilar by nesting the dissimilar classes within the computer class.

If however, we wished to discuss disk drives, we may wish to examine the characteristics of disk drives in general, then examine the details of a hard disk, and the differences of floppy disks. This would involve inheritance because much of the data about both drives could be characterized and applied to the generic disk drive then used to aid in the discussion of the other three. We will study inheritance in the next three chapters, but for now we will look at the embedded or nested class.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap06.htm (9 of 17)02.03.2005 09:10:11

Page 58: C++ Language Tutorial

C++ Tutorial - Chapter 6

This example program contains a class named box which contains an object of another class embedded within it in line 17, the mail_info class. It is depicted graphically in figure 6-3. This object is available for use only within the class implementation of box because that is where it is defined. The main() program has objects of class box defined but no objects of class mail_info, so the mail_info class cannot be referred to in the main() program. In this case, the mail_info class object is meant to be used internally to the box class and one example is given in line 22 where a message is sent to the label.set() method to initialize the variables. Additional methods could be used as needed, but these are given as an illustration of how they can be called.

Of prime importance is the fact that there are never any objects of the mail_info class declared directly in the main() program, they are inherently declared when the enclosing objects of class box are declared. Of course objects of the mail_info class could be declared and used in the main() program if needed, but they are not in this example program. In order to be complete, the box class should have one or more methods to use the information stored in the object of the mail_info class. Study this program until you understand the new construct, then compile and execute it.

If the class and the nested classes require parameter lists for their respective constructors an initialization list can be given. This will be discussed and illustrated later in this tutorial.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap06.htm (10 of 17)02.03.2005 09:10:11

Page 59: C++ Language Tutorial

C++ Tutorial - Chapter 6

OPERATOR OVERLOADING

Example program ------> OPOVERLD.CPP

The example file named OPOVERLD.CPP contains examples of overloading operators. This allows you to define a class of objects and redefine the use of the normal operators. The end result is that objects of the new class can be used in as natural a manner as the predefined types. In fact, they seem to be a part of the language rather than your own add-on.

In this case we overload the + operator and the * operator, with the declarations in lines 11 through 13, and the definitions in lines 17 through 41. The methods are declared as friend functions so we can use the double parameter functions as listed. If we did not use the friend construct, the function would be a part of one of the objects and that object would be the object to which the message was sent. Including the friend construct allows us to separate this method from the object and call the method with infix notation. Using this technique, it can be written as object1 + object2 rather than object1.operator+(object2). Also, without the friend construct we could not use an overloading with an int type variable for the first parameter because we can not send a message to an integer type variable such as int.operator+(object). Two of the three operator overloadings use an int for the first parameter so it is necessary to declare them as friend functions.

There is no upper limit to the number of overloadings for any given operator. Any number of overloadings can be used provided the parameters are different for each particular overloading.

The header in line 17 illustrates the first overloading where the + operator is overloaded by giving the return type followed by the keyword operator and the operator we wish to overload. The two formal parameters and their types are then listed in the parentheses and the normal function operations are given in the implementation of the function in lines 19 through 22. The observant student will notice that the implementation of the friend functions are not actually a part of the class because the class name is not prepended onto the method name in line 17. There is nothing unusual about this implementation, it should be easily understood by you at this point. For purposes of illustration, some silly mathematics are performed in the method implementation, but any desired operations can be done.

The biggest difference occurs in line 57 where this method is called by using the infix notation instead of the usual message sending format. Since the variables small and medium are objects of the box class, the system will search for a way to use the + operator on two objects of class box and will find it in the overloaded operator+ method we have just discussed. The operations within the method implementation can be anything we need them to be, and they are usually much more meaningful than the silly math included here.

In line 59 we ask the system to add an int type constant to an object of class box, so the system finds the other overloading of the + operator beginning in line 26 to perform this operation. Also in line 61 we ask

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap06.htm (11 of 17)02.03.2005 09:10:11

Page 60: C++ Language Tutorial

C++ Tutorial - Chapter 6

the system to use the * operator to do something to an int constant and an object of class box, which it satisfies by finding the method in lines 35 through 41. Note that it would be illegal to attempt to use the * operator the other way around, namely large * 4 since we did not define a method to use the two types in that order. Another overloading could be given with reversed types, and we could then use the reverse order in a program.

You will notice that when using operator overloading, we are also using function name overloading since some of the function names are the same.

When we use operator overloading in this manner, we actually make our programs look like the class is a natural part of the language since it is integrated into the language so well. C++ is therefore an extendible language and can be molded to fit the mechanics of the problem at hand.

OPERATOR OVERLOADING CAVEATS

Each new topic we study has its pitfalls which must be warned against and the topic of operator overloading seems to have the record for pitfalls since it is so prone to misuse and has several problems. The overloading of operators is only available for classes, you cannot redefine the operators for the predefined simple types. This would probably be very silly anyway since the code could be very difficult to read if you changed some of them around.

The logical and "&&" and the logical or "||" operators can be overloaded for the classes you define, but they will not operate as short circuit operators. All members of the logical construction will be evaluated with no regard concerning the outcome. Of course the normal predefined logical operators will continue to operate as short circuit operators as expected, but not the overloaded ones.

If the increment "++" or decrement "--" operators are overloaded, the system has no way of telling whether the operators are used as preincrement or postincrement (or predecrement or postdecrement) operators. Which method is used is implementation dependent, so you should use them in such a way that it doesn't matter which is used.

Be sure to compile and execute OPOVERLD.CPP before continuing on to the next example program.

FUNCTION OVERLOADING IN A CLASS

Example program ------> FUNCOVER.CPP

Examine the program named FUNCOVER.CPP for an example of function name overloading within a class. In this program the constructor is overloaded as well as one of the methods to illustrate what can be done.

This file illustrates some of the uses of overloaded names and a few of the rules for their use. You will

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap06.htm (12 of 17)02.03.2005 09:10:11

Page 61: C++ Language Tutorial

C++ Tutorial - Chapter 6

recall that the function selected is based on the number and types of the formal parameters only. The type of the return value is not significant in overload resolution.

In this case there are three constructors. The constructor which is actually called is selected by the number and types of the parameters in the definition. In line 78 of the main program the three objects are declared, each with a different number of parameters and inspection of the results will indicate that the correct constructor was called based on the number of parameters.

In the case of the other overloaded methods, the number and type of parameters is clearly used to select the proper method. You will notice that one method uses a single integer and another uses a single float type variable, but the system is able to select the correct one. As many overloadings as desired can be used provided that all of the parameter patterns are unique.

You may be thinking that this is a silly thing to do but it is, in fact, a very important topic. Throughout this tutorial we have been using an overloaded operator and you haven't been the least confused over it. It is the << operator which is part of the cout class, which operates as an overloaded function since the way it outputs data is a function of the type of its input variable or the field we ask it to display. Many programming languages have overloaded output functions so you can output any data with the same function name.

Be sure to compile and execute this program.

SEPARATE COMPILATION

Separate compilation is available with C++ and it follows the identical rules as given for ANSI-C separate compilation. As expected, separately compiled files can be linked together. However, since classes are used to define objects, the nature of C++ separate compilation is considerably different from that used for ANSI-C. This is because the classes used to create the objects are not considered as external variables, but as included classes. This makes the overall program look different from a pure ANSI-C program. Your programs will take on a different appearance as you gain experience in C++.

YOU GET SOME METHODS BY DEFAULT

Example program ------> DEFMETHS.CPP

Even if you include no constructors or operator overloadings you get a few defined automatically by the compiler. Examine the file named DEFMETHS.CPP which will illustrate those methods provided by the compiler, and why you sometimes can't use the defaults but need to write your own to do the job the defaults were intended to do for you.

Before we actually look at the program, we will list a few rules that all compiler writers must follow in order to deliver a useful implementation of C++. First we will state the rules, then take a closer look at

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap06.htm (13 of 17)02.03.2005 09:10:11

Page 62: C++ Language Tutorial

C++ Tutorial - Chapter 6

them and the reason for their existence.

1. If no constructors are defined by the writer of a class, the compiler will automatically generate a default constructor and a copy constructor. Both of these constructors will be defined for you shortly.

2. If the class author includes any constructor in the class, the default constructor will not be supplied by the constructor.

3. If the class author does not include a copy constructor, the compiler will generate one, but if the writer includes a copy constructor, the compiler will not generate one automatically.

4. If the class author includes an assignment operator, the compiler will not include one automatically, otherwise it will generate a default assignment operator.

Any class declared and used in a C++ program must have some way to construct an object because the compiler, by definition, must call a constructor when we define an object. If we don't provide a constructor, the compiler itself will generate one that it can call during construction of the object. This is the default constructor and we have used it unknowingly in a lot of our example programs. The default constructor does not initialize any of the member variables, but it sets up all of the internal class references it needs, and calls the base constructor or constructors if they exist. We haven't studied inheritance yet, but we will in the next chapter of this tutorial so we will know then what base classes are all about. Line 12 of the present program declares a default constructor which is called when you define an object with no parameters. In this case, the constructor is necessary because we have an embedded string in the class that requires a dynamic allocation and an initialization of the string to the null string. It will take little thought to see that our constructor is much better than the default constructor which would leave us with an uninitialized pointer.

The default constructor is used in line 79 of this example program.

THE COPY CONSTRUCTOR

The copy constructor is generated automatically for you by the compiler if you fail to define one yourself. It is used to copy the contents of an object to a new object during construction of that new object. If the compiler generates it for you, it will simply copy the contents of the original into the new object as a byte by byte copy, which may not be what you want. For simple classes with no pointers, that is usually sufficient, but in the present example program, we have a pointer as a class member so a byte by byte copy would copy the pointer from one to the other and they would both be pointing to the same allocated member. For this program, we declared our own copy constructor in line 15 and implemented it in lines 35 to 40. A careful study of the implementation will reveal that the new class will indeed be identical to the original, but the new class has its own string to work with. Since both constructors contain dynamic allocation, we must assure that the allocated data is destroyed when we are finished with the objects, so a destructor is mandatory as implemented in lines 51 through 54 of the present example program. The copy constructor is used in line 85 of the current example program.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap06.htm (14 of 17)02.03.2005 09:10:11

Page 63: C++ Language Tutorial

C++ Tutorial - Chapter 6

THE ASSIGNMENT OPERATOR

It is not too obvious, but an assignment operator is required for this program also, because the default assignment operator simply copies the source object to the destination object byte by byte. This would result in the same problem we had with copy constructor. The assignment operator is declared in line 18 and defined in lines 42 through 49 where we deallocate the old string in the existing object prior to allocating room for the new text and copying the text from the source object into the new object. The assignment operator is used in line 92.

It should be fairly obvious to the student that when a class is defined which includes any sort of dynamic allocation, the above three methods should be included in addition to the proper destructor. If any of the four entities are omitted, the program may have terribly erratic behavior. Be sure to compile and execute this example program.

A PRACTICAL EXAMPLE

Example program ------> PHRASE.H

Using the inline keyword with a class member can cause a bit of difficulty unless you understand how the compiler uses the inline code definition to perform the inline code insertion. Examine the header file named PHRASE.H which includes some inline methods. These are included as an illustration of one means of defining the inline methods in a clean way that the compiler can use efficiently.

When any implementation uses this class, it must have access to the inline implementation in order to insert the proper inline code for the member functions. One way to do this is to put all of the inline methods in a separate file named with the INL extension, then including that file into the end of the .H file as shown here. This makes all of the inline code available for the compiler while compiling files that use this class.

Example program ------> PHRASE.INL

The example file named PHRASE.INL contains all of the inline code for this class.

Example program ------> PHRASE.CPP

Note that the only reason for this file to exist is to define the static string variable full_phrase. Since this is a definition, and therefore some memory is defined, it cannot be placed in the header file. If it were placed there, it would seem to work all right in this program because the header file is only used once, but using a bad technique like that would lead to problems later. For illustrative purposes, all of the methods were declared inline, so there are no member definitions in this class.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap06.htm (15 of 17)02.03.2005 09:10:11

Page 64: C++ Language Tutorial

C++ Tutorial - Chapter 6

Example program ------> USEPHRAS.CPP

The file named USEPHRAS.CPP uses the phrase class defined in the last two example files. It is plain to see that this class is no different than any others we have studied. It simply illustrates a way to package inline code in a simple and very efficient manner.

ANOTHER PRACTICAL EXAMPLE

We come again to the practical part of this lesson where we study a practical class that can actually be used in a program but is still simple enough for the student to completely understand.

Example program ------> TIME.H

In the last chapter we studied the date class and in this chapter we will study a simple time class. You should begin by studying the file named TIME.H which will look very similar to the date class header. The only major difference in this class from the date class is the overloaded constructors and methods. The program is a very practical example that illustrates very graphically that many constructor overloadings are possible.

Example program ------> TIME.CPP

The implementation for the time class is given in the file named TIME.CPP. Once again, the code is very simple and you should have no problem understanding this example in its entirety. It should be pointed out that three of the four overloadings actually call the fourth so that the code did not have to be repeated four times. This is a perfectly good coding practice and illustrates that other member functions can be called from within the implementation.

As we have mentioned before, this code contains calls that are specific to DOS and are therefore not portable to other platforms. If you are using some other platform, you will need to change the code to make valid calls to your operating system, or simply assign default values to the member variables.

Example program ------> USETIME.CPP

The example program named USETIME.CPP is a very simple program that uses the time class in a very rudimentary way as an illustration for you. You should be able to understand this program in a very short time. It will be to your advantage to completely understand the practical example programs given at the end of the last chapter and the end of this chapter. As mentioned above, we will use the time class and the date class as the basis for both single and multiple inheritance in the next three chapters.

WHAT SHOULD BE THE NEXT STEP?

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap06.htm (16 of 17)02.03.2005 09:10:11

Page 65: C++ Language Tutorial

C++ Tutorial - Chapter 6

At this point you have learned enough C++ to write meaningful programs and it would be to your advantage to stop studying and begin using the knowledge you have gained. Because C++ is an extension to ANSI-C, it can be learned in smaller pieces than would be required if you are learning a completely new language. You have learned enough to study and completely understand the example program given in chapter 12, the Flyaway adventure game. You should begin studying this program now.

One of your biggest problems is learning to think in terms of object oriented programming. It is not a trivial problem if you have been programming in procedural languages for any significant length of time. However, it can be learned by experience, so you should begin trying to think in terms of classes and objects immediately. Your first project should use only a small number of objects and the remainder of code can be completed in standard procedural programming techniques. As you gain experience, you will write more of the code for any given project using classes and objects but every project will eventually be completed in procedural code.

After you have programmed for a while using the techniques covered up to this point in the tutorial, you can continue on to the next few chapters which will discuss inheritance and virtual functions.

PROGRAMMING EXERCISES

1. Modify OBJDYNAM.CPP to make the objects named small and medium pointers, then dynamically allocate them prior to using them.

2. Modify the loop in line 62 of OBJLINK.CPP so that the loop will store 1000 elements in the list before stopping. You will probably wish to remove the printout from line 81 so the program will stop in a reasonable time. You may also get an integer overflow indicated by wrong answers if you send a message to get_area() with such large numbers. That will depend upon your compiler.

3. Write a program that uses both the date and time classes in a meaningful manner. No answer will be given in the ANSWERS directory for this exercise since it is so straight forward. These classes can be used in all of your future C++ programs to time stamp the time and date of execution.

Advance to Chapter 7

Return to Table of Contents

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap06.htm (17 of 17)02.03.2005 09:10:11

Page 66: C++ Language Tutorial

C++ Tutorial - Chapter 7

C++ Tutorial - Chapter 7

INHERITANCE

One reason to use inheritance is that it permits you to reuse code from a previous project, but gives you the flexibility to slightly modify it if the old code doesn't do exactly what you need for the new project. It doesn't make sense to start every new project from scratch since some code will certainly be repeated in several programs and you should strive to build on what you did previously. However, it is easy to make an error if you try to modify the original class. You are less likely to make an error if you leave the original alone and only add to it. Another reason for using inheritance is if the project requires the use of several classes which are very similar but slightly different.

In this chapter we will concentrate on the mechanism of inheritance and how to build it into a program. A better illustration of why you would use inheritance will be given in later chapters where we will discuss some practical applications of object oriented programming. The principle of inheritance is available with several modern programming languages and is handled slightly differently with each. C++ allows you to inherit all or part of the members and methods of a class, modify some, and add new ones not available in the parent class. You have complete flexibility, and as usual, the method used with C++ has been selected to result in the most efficient code execution.

A SIMPLE CLASS TO START WITH

Example program ------> VEHICLE.H

Examine the file named VEHICLE.H for a simple class which we will use to begin our study of inheritance. There is nothing unusual about this class header, it has been kept very simple. It consists of

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap07.htm (1 of 9)02.03.2005 09:10:15

Page 67: C++ Language Tutorial

C++ Tutorial - Chapter 7

four simple methods which can be used to manipulate data pertaining to our vehicle. What each method does is not especially important at this time. We will eventually refer to this as a base class or parent class, but for the time being, we will simply use it like any other class to show that it is indeed identical to the classes already studied. Note that we will explain the added keyword protected shortly. Figure 7-1 is a graphical representation of the vehicle class.

Ignore lines 4, 5, and 19 until the end of this chapter where they will be explained in detail. This file cannot be compiled or executed because it is only a header file.

THE IMPLEMENTATION FOR VEHICLE

Example program ------> VEHICLE.CPP

Examine the file named VEHICLE.CPP and you will find that it is the implementation of the vehicle class. The initialize() method assigns the values input as parameters to the wheels and weight variables. We have methods to return the number of wheels and the weight, and finally, we have one that does a trivial calculation to return the loading on each wheel. We will have a few examples of methods that do some significant processing later, but at this point, we are more interested in learning how to set up the interface to the classes, so the implementations will be kept trivial.

As stated above, this is a very simple class which will be used in the next program. Later in this tutorial we will use it as a base class. You should compile this class at this time in preparation for the next example program, but you cannot execute it because there is no entry point.

USING THE VEHICLE CLASS

Example program ------> TRANSPRT.CPP

The file named TRANSPRT.CPP uses the vehicle class in exactly the same manner as we illustrated in the last chapter. This should be an indication to you that the vehicle class is truly nothing more than a normal class as defined in C++. We will make it a little special, however, by using it unmodified as a base class in the next few example files to illustrate inheritance. Inheritance uses an existing class and adds functionality to it to accomplish another, possibly more complex job.

You should have no problem understanding the operation of this program. It declares four objects of the vehicle class, initializes them, and prints out a few of the data values to illustrate that the vehicle class can be used as a simple class because it is a simple class. We are referring to it as a simple class as opposed to calling it a base class or derived class as we will do shortly.

If you thoroughly understand this program, you should compile and execute it, remembering to link the vehicle object file with this object file.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap07.htm (2 of 9)02.03.2005 09:10:15

Page 68: C++ Language Tutorial

C++ Tutorial - Chapter 7

OUR FIRST DERIVED CLASS

Example program ------> CAR.H

Examine the file named CAR.H for our first example of the use of a derived class or child class. The vehicle class is inherited due to the ": public vehicle" added to line 7. This derived class named car is composed of all of the information included in the base class vehicle, and all of its own additional information. Even though we did nothing to the class named vehicle, we made it into a base class because of the way we are using it here. To go a step further, even though it will be used as a base class in an example program later in this chapter, there is no reason it cannot continue to be used as a simple class in the previous example program. In fact, it can be used as a simple class and a base class in the same program. The question of whether it is a simple class or a base class is answered by the way it is used.

A discussion of terminology is needed here. When discussing object oriented programming in general, a class that inherits another is often called a derived class or a child class, but the most proper term as defined for C++, is a derived class. Since these terms are very descriptive, and most writers tend to use the terms interchangeably, we will also use these terms in this tutorial. Likewise the proper C++ terminology for the inherited class is to call it a base class, but parent class and super class are sometimes used also.

A base class is a rather general class which can cover a wide range of objects, whereas a derived class is somewhat more restricted but at the same time more useful. For example if we had a base class named programming language and a derived class named C++, then we could use the base class to define Pascal, Ada, C++, or any other programming language, but it would not tell us about the use of classes in C++ because it can only give a general view of each language. On the other hand, the derived class named C++ could define the use of classes, but it could not be used to describe the other languages because it is too narrow. A base class tends to be more general, and a derived class is more specific.

In this case, the vehicle base class can be used to declare objects that represent trucks, cars, bicycles, or any number of other vehicles you can think up. The class named car however can only be used to declare an object that is of type car because we have limited the kinds of data that can be intelligently used with it. The car class is therefore more restrictive and specific than the vehicle class. The vehicle class is more general than the car class.

If we wished to get even more specific, we could define a derived class using car as the base class, name it sports_car, and include such information as red_line_limit for the tachometer which would be silly for the family station wagon. The car class would therefore be used as a derived class and a base class at the same time, so it should be clear that these names refer to how a class is used.

HOW DO WE DECLARE A DERIVED CLASS?

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap07.htm (3 of 9)02.03.2005 09:10:15

Page 69: C++ Language Tutorial

C++ Tutorial - Chapter 7

Enough generalities about classes, let's get down to the specifics. A derived class is defined by including the header file for the base class as is done in line 5, then the name of the base class is given following the name of the derived class separated by a colon as is illustrated in line 7. Ignore the keyword public immediately following the colon in this line. This defines public inheritance and we will study it in detail in the next chapter. All objects declared as being of class car therefore are composed of the two variables from the class vehicle because they inherit those variables, and the single variable declared in the class car named passenger_load.

An object of this class will have three of the four methods of vehicle and the two new ones declared here. The method named initialize() which is part of the vehicle class will not be available here because it is hidden by the local version of initialize() which is a part of the car class. The local method will be used if the name is repeated allowing you to customize your new class. Figure 7-2 is a graphical representation of an object of this class.

Note once again that the implementation for the base class only needs to be supplied in its compiled form. The source code for the implementation can be hidden for economic reasons to aid software developers. Hiding the source code also allows the practice of information hiding. The header for the base class must be available as a text file since the class definitions are required in order to use the class.

THE CAR CLASS IMPLEMENTATION

Example program ------> CAR.CPP

Examine the file named CAR.CPP which is the implementation file for the car class. The first thing you should notice is that this file has no indication of the fact that it is a derived class of any other file, that

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap07.htm (4 of 9)02.03.2005 09:10:15

Page 70: C++ Language Tutorial

C++ Tutorial - Chapter 7

can only be determined by inspecting the header file for the class. Since we can't tell if it is a derived class or not, it is written in exactly the same way as any other class implementation file.

The implementations for the two new methods are written in exactly the same way as methods are written for any other class. If you think you understand this file, you should compile it for later use.

ANOTHER DERIVED CLASS

Example program ------> TRUCK.H

Examine the file named TRUCK.H for an example of another class that uses the vehicle class and adds to it. Of course, it adds different things to it, because it will specialize in those things that pertain to trucks. In fact, it adds two more variables and three more methods. Once again, ignore the keyword public following the colon in line 7 for a few minutes and we will cover it in detail in the next chapter of this tutorial. See figure 7-3 for a graphical representation of the truck class.

A very important point that must be made is that the car class and the truck class have absolutely nothing to do with each other, they only happen to be derived classes of the same base class or parent class as it is sometimes called.

Note that both the car and the truck classes have methods named passengers() but this causes no problems and is perfectly acceptable. If classes are related in some way, and they certainly are if they are both derived classes of a common base class, you would expect them to be doing somewhat similar

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap07.htm (5 of 9)02.03.2005 09:10:15

Page 71: C++ Language Tutorial

C++ Tutorial - Chapter 7

things. In this situation there is a good possibility that a method name would be repeated in both child classes.

THE TRUCK IMPLEMENTATION

Example program ------> TRUCK.CPP

Examine the file named TRUCK.CPP for the implementation of the truck class. It has nothing unusual included in it.

You should have no problem understanding this implementation. Your assignment at this point is to compile it in preparation for our example program that uses all three of the classes defined in this chapter.

USING ALL THREE CLASSES

Example program ------> ALLVEHIC.CPP

Examine the program named ALLVEHIC.CPP for an example that uses all three of the classes we have been discussing in this chapter. It uses the parent class vehicle to declare objects and also uses the two child classes to declare objects. This was done to illustrate that all three classes can be used in a single program.

All three of the header files for the classes are included in lines 3 through 5 so the program can use the components of the classes. Notice that the implementations of the three classes are not in view here and do not need to be in view. This allows the code to be used without access to the source code for the actual implementation of the class. However, it should be clear that the header file definition must be available.

In this example program, only one object of each class is declared and used but as many as desired could be declared and used in order to accomplish the programming task at hand. You will notice how clean and uncluttered the source code is for this program. The classes were developed, debugged, and stored away previously, and the interfaces were kept very simple. There is nothing new here so you should have no trouble understanding the operation of this program.

Compiling and executing this program will take a bit of effort but the process is not complicated. The three classes and the main() program can be compiled in any order desired. All four must be compiled prior to linking the four resulting object (or binary) files together. Finally, you can execute the complete program. Be sure you do the required steps to compile and execute this program because the effective use of C++ will require you to compile many separate files and link them together. This is because of the nature of the C++ language, but it should not be a burden if a good "make" capability exists with your compiler. If you are using an implementation of C++ that has a "project" capability, it will make this a

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap07.htm (6 of 9)02.03.2005 09:10:15

Page 72: C++ Language Tutorial

C++ Tutorial - Chapter 7

snap.

WHY THE #ifndef VEHICLE_H ?

We promised to return to the strange looking preprocessor directive in lines 4, 5 and 19 in the VEHICLE.H file, and this is the time for it. When we define the derived class car, we are required to supply it with the full definition of the interface to the vehicle class since car is a derived class of vehicle and must know all about its parent. We do that by including the vehicle class into the car class, and the car class can be compiled. The vehicle class must also be included in the header file of the truck class for the same reason.

When we get to the ALLVEHIC.CPP program, we must inform it of the details of all three classes, so all three header files must be included as is done in lines 3 through 5 of ALLVEHIC.CPP, but this leads to a problem. When the preprocessor gets to the car class, it includes the vehicle class because it is listed in the car class header file, but since the vehicle class was already included in line 3 of ALLVEHIC.CPP, it is included twice and we attempt to redeclare the class vehicle. Of course it is the same declaration, but the system doesn't care, it simply doesn't allow redeclaration of a class. We allow the double inclusion of the file and at the same time prevent the double inclusion of the class by building a bridge around it using the word VEHICLE_H. If the word is already defined, the declaration is skipped, but if the word is not defined, the declaration is included and VEHICLE.H is defined at that time. The end result is the actual inclusion of the class only once, even though the file is included more than once. You should have no trouble understanding the logic of the includes if you spend a little time studying this program sequence.

Even though ANSI-C allows multiple definitions of entities, provided the definitions are identical, C++ does not permit this. The primary reason is because the compiler would have great difficulty in knowing if it has already made a constructor call for the redefined entity, if there is one. A multiple constructor call for a single object could cause great havoc, so C++ was defined to prevent any multiple constructor calls by making it illegal to redefine any entity. This is not a problem in any practical program.

The name VEHICLE_H was chosen as the word because it is the name of the file, with the period replaced by the underline. If the name of the file is used systematically in all of your class definitions, you cannot have a name clash because the filename of every class must be unique provided you keep all files in the same directory. It would be good for you to get into the practice of building the optional skip around all of your class headers. All class definition files in the remainder of this tutorial will include this skip around to prevent multiple inclusions and to be an example for you. You should get into the practice of adding the skip around to all of your class headers no matter how trivial they may seem to be.

OUR FIRST PRACTICAL INHERITANCE

Example program ------> NEWDATE.H

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap07.htm (7 of 9)02.03.2005 09:10:15

Page 73: C++ Language Tutorial

C++ Tutorial - Chapter 7

Continuing where we started in chapter 5, we will inherit the date class into the file named NEWDATE.H and add a member variable and a new method to the class. Actually, this is not a good way to add the day_of_year to the date class since it is available in the structure returned from the system call in the date class. However, we are more interested in illustrating inheritance in a practical example than we are in developing a perfect class, so we will live with this inefficiency. You will note that we add one variable and one method to create our new class.

Example program ------> NEWDATE.CPP

The program named NEWDATE.CPP contains the implementation for the added method and should be easy for the student to understand. This class implementation uses the array days[] from the date class implementation since it was defined as a global variable there. The method named get_time_of_day() involves very simple logic. It doesn't even adjust for leap years. Once again, we are not really interested in writing a good date class, but in learning the mechanics of inheritance.

Example program ------> TRYNDATE.CPP

Finally, the example program named TRYNDATE.CPP will use the new class in a very simple way to illustrate that the derived class is as easy to use as the base class and in fact the main program has no way of knowing that it is using a derived class.

You should compile and link this program to gain the experience of doing so. Remember that it will be necessary to link in the object code for the original date class as well as the object code from the newdate class and the main() program.

PROGRAMMING EXERCISES

1. Add another object of the vehicle class to ALLVEHIC.CPP named bicycle, and do some of the same operations as were done to the unicycle. You will only need to recompile the main() program and link all four files together to get an executable file, the three classes will not require recompilation.

2. Add a new method to the truck class to return the total weight of the truck plus its payload and add code to ALLVEHIC.CPP to read the value out and display it on the monitor. This will require an addition to TRUCK.H, another addition to TRUCK.CPP, and of course the changes to the main program named ALLVEHIC.CPP. The answer is given as three files named CH07_3A.H (TRUCK.H), CH07_3B.CPP (TRUCK.CPP) and the changed main() program is found in CH07_3C.CPP in the answers for this tutorial.

3. Add a variable named sex of type char to the name class you developed in chapter 5 as well as methods to set and retrieve the value of this variable. The only legal inputs are 'M' or 'F'. These additions should be done by inheriting the name class into the new class.

Advance to Chapter 8

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap07.htm (8 of 9)02.03.2005 09:10:15

Page 74: C++ Language Tutorial

C++ Tutorial - Chapter 7

Return to the Table of Contents

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap07.htm (9 of 9)02.03.2005 09:10:15

Page 75: C++ Language Tutorial

C++ Tutorial - Chapter 8

C++ Tutorial - Chapter 8

MORE INHERITANCE

In the last chapter we developed a model using modes of transportation to illustrate the concept of inheritance. In this chapter we will use that model to illustrate some of the finer points of inheritance and what it can be used for. If it has been a while since you read and studied chapter 7, it would be good for you to return to that material and review it in preparation for a more detailed study of the topic of inheritance.

REORGANIZED FILE STRUCTURE

Example program ------> INHERIT1.CPP

A close examination of the file named INHERIT1.CPP will reveal that it is identical to the program developed in chapter 7 named ALLVEHIC.CPP except that the program text is rearranged. The biggest difference is that some of the simpler methods in the classes have been changed to inline code to shorten the file considerably. In a practical programming situation, methods that are this short should be programmed inline since the actual code to return a simple value is shorter than the code required to send a message to a non-inline method.

The only other change is the reordering of the classes and associated methods with the classes all defined first, followed by the main program. This puts all class interface definitions on a single page to make the code easier to study. The implementations for the methods are deferred until the end of the file where they are available for quick reference but are not cluttering up the class definitions which we wish to study carefully in this chapter. This should be an indication to you that there is considerable flexibility in the way the classes and methods can be arranged in C++. Of course you realize that this violates the spirit of C++ and its use of separate compilation, but is only done here for convenience. The best way to package all of the example programs in this chapter is like the packaging illustrated in chapter 7.

As mentioned before, the two derived classes, car and truck, each have a variable named passenger_load which is perfectly legal. The car class has a method of the same name, initialize(), as one declared in the super-class named vehicle. The rearrangement of the files in no way voids this allowable repeating of names.

After you have convinced yourself that this program is truly identical to the program named ALLVEHIC.CPP from chapter 7, compile and execute it with your compiler to assure yourself that this arrangement is legal. Due to this means of code packaging, you will not need a "make" file or a "project" capability to compile and execute this code. This code arrangement is designed to make it easy to compile and execute the example programs in this chapter.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap08.htm (1 of 8)02.03.2005 09:10:18

Page 76: C++ Language Tutorial

C++ Tutorial - Chapter 8

THE SCOPE OPERATOR

Because the method initialize() is declared in the derived car class, it hides the method of the same name which is part of the base class, and there may be times you wish to send a message to the method in the base class for use in the derived class object. This can be done by using the scope operator in the following manner in the main program;

sedan.vehicle::initialize(4, 3500.0);

As you might guess, the number and types of parameters must agree with those of the method in the base class because it will respond to the message.

WHAT IS PROTECTED DATA?

If the data within a base class were totally available in all classes inheriting that base class, it would be a simple matter for a programmer to inherit the base class into a derived class and have free access to all data in the parent class. This would completely override the protection afforded by the use of information hiding. For this reason, the data in a class are not automatically available to the methods of an inheriting class. There are times when you may wish to automatically inherit all variables directly into the subclasses and have them act just as though they were declared as a part of those classes also. For this reason, the designer of C++ has provided the keyword protected.

In the present example program, the keyword protected is given in line 6 so that all of the data of the vehicle class can be directly imported into any derived classes but are not available outside of the base class or derived classes. As we have mentioned before, all data are automatically defaulted to private at the beginning of a class if no specifier is given.

You will notice that the variables named wheels and weight are available to use in the method named initialize() in lines 83 through 88 just as if they were declared as a part of the car class itself. They are available because they were declared protected in the base class. Of course, they would be available here if they had been decared public in the base class, but then they would be available outside of both classes and we would lose our protection. Note that the two variables are available for use in the base class as illustrated in lines 77 and 78. We can now state the rules for the three means of defining variables and methods.

● private - The variables and methods are not available to any outside calling routines, and they are not available to any derived classes inheriting this class.

● protected - The variables and methods are not available to any outside calling routines, but they are directly available to any derived class inheriting this class.

● public - All variables and methods are freely available to all outside calling routines and to all derived classes.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap08.htm (2 of 8)02.03.2005 09:10:18

Page 77: C++ Language Tutorial

C++ Tutorial - Chapter 8

You will note that these three means of definition can also be used in a struct type. The only difference with a struct is that everything defaults to public until one of the other keywords is used.

Be sure to compile and execute this program before continuing on to the next example program.

WHAT IS PRIVATE DATA?

Example program ------> INHERIT2.CPP

Examine the file named INHERIT2.CPP where the data in the base class is permitted to use the private default because line 6 is commented out. In this program, the data is not available for use in the derived classes, so the only way the data in the base class can be used is by sending messages to methods in the base class, even within the derived class.

It seems a little silly to have to call methods in the base class to access the data which is actually a part of the derived class, but that is the way C++ is defined to work. This would indicate to you that you should spend some time thinking about how any class you define will be used. If you think somebody may wish to inherit your class into a new class and expand it, you should make the data members protected so they can be easily used in the new class. Lines 86 and 87 are invalid now since the members are not visible, but line 88 now does the job they did before they were hidden by calling the public method of the base class. Line 104 is also changed because of the hidden data. You will notice that the data is still available in lines 77 and 78 just as they were before because the member variables are protected in the vehicle class. Be sure to compile and execute this program.

HIDDEN METHODS

Example program ------> INHERIT3.CPP

Examine the file named INHERIT3.CPP carefully and you will see that it is a repeat of the first example program in this chapter with a few minor changes.

You will notice that the derived classes named car and truck do not have the keyword public prior to the name of the base class in the first line of each class declaration. The keyword public, when included prior to the base class name, makes all of the methods defined in the base class available for use in the derived class at the same security level as they were defined at in the base class. Therefore, in the previous program, we were permitted to call the methods defined as part of the base class from the main program even though we were working with an object of one of the derived classes.

In this program, all entities are inherited as private due to the use of the keyword private prior to the name of the base class. They are therefore unavailable to any code outside of the derived class. The general rule is that all elements are inherited into the derived class at the most restrictive of the two restrictions placed on them, one being the definition in the base class and the other being the restriction

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap08.htm (3 of 8)02.03.2005 09:10:18

Page 78: C++ Language Tutorial

C++ Tutorial - Chapter 8

on inheritance. This defines the way the elements are viewed outside of the derived class.

The elements are all inherited into the derived class such that they have the same level of protection they had in the base class, as far as their visibility restrictions within the derived class. We have returned to the use of protected data instead of private in the base class, therefore the member variables are available for use within the derived class.

In the present program, the only methods available for objects of the car class, are those that are defined as part of the class itself, and therefore we only have the methods named initialize() and passengers() available for use with objects of class car.

When we declare an object of type car, according to the definition of the C++ language, it contains three variables. It contains the one defined as part of its class named passenger_load and the two that are part of its parent class, wheels and weight. All are available for direct use within its methods because of the use of the keyword protected in the base class. The variables are a part of an object of class car when it is declared and are stored as part of the object.

The observant student will notice that several of the output statements have been commented out of the main program since they are no longer legal or meaningful operations. Lines 57 through 59 have been commented out because the methods named get_weight() and wheel_loading() are not available as members of the car class because we are using private inheritance. You will notice that initialize() is still available but this is the one in the car class, not the method of the same name in the vehicle class.

USING THE TRUCK CLASS

Moving on to the use of the truck class in the main program, we find that lines 63 and 65 are commented out for the same reason as given above, but lines 66 and 67 are commented out for an entirely different reason. Even though the method named efficiency() is available and can be called as a part of the truck class, it cannot be used because we have no way to initialize the wheels or weight of the truck object. We can get the weight of the truck object, as we have done in line 102, but since the weight has no way to be initialized, the result is meaningless and lines 66 and 67 are commented out.

Private inheritance is very similar to using an embedded object and, in fact, is very rarely used. Until you gain a lot of experience with C++ and the proper use of Object Oriented Programming, you should use public inheritance exclusively. There is probably no reason to ever use private or protected inheritance. They were probably added to the language for completeness.

Be sure to compile and execute this example program to see that your compiler gives the same result. It would be a good exercise for you to reintroduce some of the commented out lines to see what sort of an error message your compiler issues for these errors.

INITIALIZING ALL DATA

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap08.htm (4 of 8)02.03.2005 09:10:18

Page 79: C++ Language Tutorial

C++ Tutorial - Chapter 8

Example program ------> INHERIT4.CPP

If you will examine the example program named INHERIT4.CPP, you will find that we have fixed the initialization problem that we left dangling in the last example program. We also added default constructors to each of the classes so we can study how they are used when we use inheritance and we have returned to the use of public inheritance.

When we create an object of the base class vehicle, there is no problem since inheritance is not a factor. The constructor for the base class operates in exactly the same manner that all constructors have in previous chapters. You will notice that we create the unicycle object in line 47 using the default constructor and the object is initialized to the values contained in the constructor. Line 49 is commented out because we no longer need the initialization code for the object.

When we define an object of one of the derived classes in line 57, the sedan, it is a little different because not only do we need to call a constructor for the derived class, we have to worry about how we get the base class initialized through its constructor also. Actually, it is no problem because the compiler will automatically call the default constructor for the base class unless the derived class explicitly calls another constructor for the base class. We will explicitly call another constructor in the next example program, but for now we will only be concerned about the default constructor for the base class that is called automatically.

ORDER OF CONSTRUCTION

The next problem we need to be concerned about is the order of construction, and it is easy to remember if you remember the following statement, "C++ classes honor their parents by calling their parents constructor before they call their own." The base class constructor will be called before the derived class constructor. This makes sense because it guarantees that the base class is properly constructed when the constructor for the derived class is executed. This allows you to use some of the data from the base class during construction of the derived class. That was a mouthful, but if you spend a little time with this concept, it will make a lot of sense, and you will not easily forget it. In this case, the vehicle part of the sedan object is constructed, then the local portions of the sedan object will be constructed, so that all member variables are properly initialized. This is why we can comment out the initialize method in line 59. It is not needed.

When we define a semi object in line 66, it will also be constructed in the same manner. The constructor for the base class is executed, then the constructor for the derived class will be executed. The object is now fully defined and useable with default data in each member. Lines 68 and 69 are therefore not needed.

The remainder of this program should be no problem for you to understand except for the order of destruction of the various objects.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap08.htm (5 of 8)02.03.2005 09:10:18

Page 80: C++ Language Tutorial

C++ Tutorial - Chapter 8

HOW ARE THE DESTRUCTORS EXECUTED?

As the objects go out of scope, they must have their destructors executed also, and since we didn't define any, the default destructors will be executed. Once again, the destruction of the base class object named unicycle is no problem, it's destructor is executed and the object is gone. The sedan object however, must have two destructors executed to destroy each of its parts, the base class part and the derived class part. It should not be too much of a surprise that the destructors for this object are executed in reverse order from the order in which they were constructed. In other words, the object is dismantled in the opposite order from the order in which it was assembled. The derived class destructor is executed first, then the base class destructor is executed and the object is removed from they system.

Remember that every time an object is defined or created, every portion of it must have a constructor executed on it. Every object must also have a destructor executed on each of its parts when it is destroyed in order to properly dismantle the object.

Be sure to compile and execute this program following your detailed study of it.

INHERITANCE WHEN CONSTRUCTORS ARE USED

Example program ------> INHERIT5.CPP

Examine the example program named INHERIT5.CPP for yet another variation to our basic program, this time using constructors that are more than just the default constructors. You will notice that each class has another constructor declared within it. The additional constructor added to the vehicle class in lines 12 through 14 is nothing special, it is just like some of the constructors we have studied earlier in this tutorial. It is used in line 59 of the main program where we define unicycle with two values passed in to be used when executing this constructor.

The constructor for the car class which is declared in lines 28 through 31 is a bit different, because we pass in three values. One of the values, the one named people, is used within the derived class itself to initialize the member variable named passenger_load. The other two literal values however, must be passed to the base class somehow in order to initialize the number of wheels and the weight. This is done by using a member initializer, and is illustrated in this constructor. The colon near the end of line 28 indicates that a member initializer list follows, and all entities between the colon and the opening brace of the constructor body are member initializers. The first member initializer is given in line 29 and looks like a constructor call to the vehicle class that requires two input parameters. That is exactly what it is, and it calls the constructor for the vehicle class and initializes that part of the sedan object that is inherited from the vehicle class. We can therefore control which base class initializer gets called when we construct an object of the derived class.

The next member initializer, in line 30, acts kind of like a constructor for a simple variable. By

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap08.htm (6 of 8)02.03.2005 09:10:18

Page 81: C++ Language Tutorial

C++ Tutorial - Chapter 8

mentioning the name of the variable and including a value of the correct type within the parentheses, that value is assigned to that variable even though the variable is not a class, but a simple predefined type. This technique can be used to initialize all members of the derived class or any portion of them. When all of the members of the member initializer list are executed, the code within the braces is executed. In this case, there is no code within the executable block of the constructor. The code within the braces would be written in a normal manner for a constructor.

WHAT ABOUT THE ORDER OF EXECUTION?

This may seem to be very strange, but the elements of the member initializer list are not executed in the order in which they appear in the list. The constructors for the inherited classes are executed first, in the order of their declaration in the class header. When using multiple inheritance, several classes can be listed in the header line, but in this program, only one is used. The member variables are then initialized, but not in the order as given in the list, but in the order in which they are declared in the class. Finally, the code within the constructor block is executed, if there is any code in the block.

There is a good reason for this seemingly strange order. The destructors must be executed in reverse order from the construction order, but if there are two constructors with different construction order defined, which should define the destruction order? The correct answer is neither. The system uses the declaration order for construction order and reverses it for the destruction order.

You will notice that the truck class uses one initializer for the base class constructor and two member initializers, one to initialize the passenger_load, and one to initialize the payload. The body of the constuctor, much like the car class, is empty.

The two constructors in the car class and the truck class are called to construct objects in lines 69 and 78 for a car object and a truck object as illustrations in this example program.

The remainder of this program should be easy for you to folow. Be sure to compile and execute this program before moving on.

POINTERS TO AN OBJECT AND AN ARRAY OF OBJECTS

Example program ------> INHERIT6.CPP

Examine the example program named INHERIT6.CPP for examples of the use of an array of objects and a pointer to an object. In this program, the objects are instantiated from an inherited class and the intent of this program is to illustrate that there is nothing magic about a derived class. A class acts the same whether it is a base class or a derived class.

This program is identical to the first program in this chapter until we get to the main() program where we find an array of 3 objects of class car declared in line 53. It should be obvious that any operation that

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap08.htm (7 of 8)02.03.2005 09:10:18

Page 82: C++ Language Tutorial

C++ Tutorial - Chapter 8

is legal for a simple object is legal for an object that is part of an array, but we must be sure to tell the system which object of the array we are interested in by adding the array subscript as we do in lines 58 through 64. The operation of this portion of the program should be very easy for you to follow, so we will go on to the next construct of interest.

You will notice, in line 68, that we do not declare an object of type truck but a pointer to an object of type truck. In order to use the pointer, we must give it something to point at which we do in line 70 by dynamically allocating an object. Once the pointer has an object to point to, we can use the object in the same way we would use any object, but we must use the pointer notation to access any of the methods of the object. This is illustrated for you in lines 76 through 80, and will be further illustrated in the example program of chapter 12 in this tutorial.

Finally, we deallocate the object in line 81. You should spend enough time with this program to thoroughly understand the new material presented here, then compile and execute it.

THE NEW TIME CLASS

We began a series of nontrivial classes in chapter 5 where we developed a date class, then a time class, and finally a newdate class in the last chapter. Now it is your turn to add to this series. Your assignment is to develop the newtime class which inherits the time class and adds a new member variable named seconds_today and a method to calculate the value of seconds since midnight to fill the variable.

A complete solution to this problem will be found in cppans.zip available for download. The files named NEWTIME.H, NEWTIME.CPP, and TRYNTIME.CPP are the solution files. It would be a good exercise for you to attempt to write this new class before you look at the example solution.

PROGRAMMING EXERCISES

1. Remove the comment delimiters from lines 57 through 59 of INHERIT3.CPP to see what kind of errors are reported.

2. Add cout statements to each of the constructors of INHERIT4.CPP to output messages to the monitor so you can see the order of sending messages to the constructors.

Advance to Chapter 9

Return to the Table of Contents

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap08.htm (8 of 8)02.03.2005 09:10:18

Page 83: C++ Language Tutorial

C++ Tutorial - Chapter 9

C++ Tutorial - Chapter 9

MULTIPLE INHERITANCE AND FUTURE DIRECTIONS

Multiple inheritance is the ability to inherit data and methods from more than one base class into a derived class. Multiple inheritance and a few of the other recent additions to the language will be discussed in this chapter along with some of the expected future directions of the language.

Several companies have C++ compilers available in the marketplace, and others are sure to follow. Because the example programs in this tutorial are designed to be as generic as possible, most should be compilable with any good quality C++ compiler provided it follows the AT&T definition of version 2.1 or newer. Many of these examples will not work with earlier definitions because the language was significantly changed with the version 2.1 update.

After completing this tutorial, you should have enough experience with the language to study additional new constructs on your own as they are implemented by the various compiler writers. We will update the entire tutorial as soon as practical following procurement of any new compiler, but hopefully the language will not change rapidly enough now to warrant an update oftener than semi-annually.

MULTIPLE INHERITANCE

A major recent addition to the C++ language is the ability to inherit methods and variables from two or more parent classes when building a new class. This is called multiple inheritance, and is purported by many people to be a major requirement for an object oriented programming language. Some writers, however, have expressed doubts as to the utility of multiple inheritance. To illustrate the validity of this, it was not easy to think up a good example of the use of multiple inheritance as an illustration for this chapter. In fact, the resulting example is sort of a forced example that really does nothing useful. It does however, illustrate the mechanics of the use of multiple inheritance with C++, and that is our primary concern at this time.

The biggest problem with multiple inheritance involves the inheritance of variables or methods with duplicated names from two or more parent classes. Which variable or method should be chosen as the inherited variable or method if two or more have the same name? This will be illustrated in the next few example programs.

SIMPLE MULTIPLE INHERITANCE

Example program ------> MULTINH1.CPP

An examination of the file named MULTINH1.CPP will reveal the definition of two very simple classes in lines 4 through 29 named moving_van and driver.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap09.htm (1 of 8)02.03.2005 09:10:21

Page 84: C++ Language Tutorial

C++ Tutorial - Chapter 9

In order to keep the program as simple as possible, all of the member methods are defined as inline functions. This puts the code for the methods where it is easy to find and study. You will also notice that all variables in both classes are declared to be protected so they will be readily available for use in any class that inherits them. The code for each class is kept very simple so that we can concentrate on studying the interface to the methods rather than spending time trying to understand complex methods. As mentioned previously, chapter 12 will illustrate the use of non-trivial methods.

Beginning in line 32, we define another class named driven_truck which inherits all of the data and all of the methods from both of the previously defined classes. In the last two chapters, we studied how to inherit a single class into another class, and to inherit two or more classes, the same technique is used except that we use a list of inherited classes separated by commas as illustrated in line 32. The observant student will notice that we use the keyword public prior to the name of each inherited class in order to be able to freely use the methods within the subclass. In this case, we didn't define any new variables, but we did introduce two new methods into the subclass in lines 35 through 42.

We define an object named chuck_ford which presumably refers to someone named Chuck who is driving a Ford moving van. The object named chuck_ford is composed of four variables, three from the moving_van class, and one from the driver class. Any of these four variables can be manipulated in any of the methods defined within the driven_truck class in the same way as in a singly inherited situation. A few examples are given in lines 50 through 59 of the main program and the diligent student should be able to add additional output messages to this program if he understands the principles involved.

All of the rules for private or protected variables and public or private method inheritance as used with single inheritance extends to multiple inheritance.

DUPLICATED METHOD NAMES

You will notice that both of the parent classes have a method named initialize(), and both of these are inherited into the subclass with no difficulty. However, if we attempt to send a message to one of these methods, we will have a problem, because the system does not know which we are referring to. This problem will be solved and illustrated in the next example program.

Before going on to the next example program, it should be noted that we have not declared any objects of the two parent classes in the main program. Since the two parent classes are normal classes themselves, it should be apparent that there is nothing magic about them and they can be used to define and manipulate objects in the usual fashion. You may wish to do this to review your knowledge of simple classes and objects of those classes.

Be sure to compile and execute this program after you understand its operation completely.

MORE DUPLICATE METHOD NAMES

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap09.htm (2 of 8)02.03.2005 09:10:21

Page 85: C++ Language Tutorial

C++ Tutorial - Chapter 9

Example program ------> MULTINH2.CPP

The second example program in this chapter named MULTINH2.CPP, illustrates the use of classes with duplicate method names being inherited into a derived class.

If you study the code, you will find that a new method has been added to all three of the classes named cost_per_full_day(). This was done intentionally to illustrate how the same method name can be used in all three classes. The class definitions are no problem at all, the methods are simply named and defined as shown. The problem comes when we wish to use one of the methods since they are all the same name and they have the same numbers and types of parameters and identical return types. This prevents some sort of an overloading rule to disambiguate the message sent to one or more of the methods.

The method used to disambiguate the method calls are illustrated in lines 63, 67, and 71 of the main program. The solution is to prepend the class name to the method name with the double colon as used in the method implementation definition. This is referred to as qualifying the method name. Qualification is not necessary in line 71 since it is the method in the derived class and it will take precedence over the other method names. Actually, you could qualify all method calls, but if the names are unique, the compiler can do it for you and make your code easier to write and read.

Be sure to compile and execute this program and study the results. The observant student will notice that there is a slight discrepancy in the results given in lines 84 through 86, since the first two values do not add up to the third value exactly. This is due to the limited precision of the float variable but should cause no real problem.

WE VIOLATED SOME OOP PRINCIPLES

One of the hallmarks of object oriented programming is that when you inherit a base class into a derived class, you are implying that the derived class "is a" kind of the base class, with emphasis on the words "is a" in this statement. It would be silly to inherit the characteristics of a polar bear into an object meant to describe a skyscraper, because we cannot say that a "skyscraper is a polar bear." However, since a "skyscraper is a building", it would make sense to inherit the characteristics of a building into a skyscraper class and add the unique properties of a skyscraper to the class.

The real problem is that multiple inheritance doesn't fit this problem chosen as an example too well, except for the fact that the entities within these classes are easy to visualize and therefore relatively easy to grasp the concepts. At this point we are more interested in illustrating the mechanics of multiple inheritance than principles of good object oriented programming. You will have lots of time to study the proper use of all forms of inheritance later. For the time being, we are interested in giving you a complete tool box of C++ constructs.

DUPLICATED VARIABLE NAMES

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap09.htm (3 of 8)02.03.2005 09:10:21

Page 86: C++ Language Tutorial

C++ Tutorial - Chapter 9

Example program ------> MULTINH3.CPP

If you will examine the example program named MULTINH3.CPP, you will notice that each base class has a variable with the same name.

According to the rules of inheritance, an object of the driven_truck class will have two variables with the same name, weight. This would be a problem if it weren't for the fact that C++ has defined a method of accessing each one in a well defined way. You have probably guessed that we will use qualification to access each variable. Lines 41 and 48 illustrate the use of the variables. It may be obvious, but it should be explicitly stated, that there is no reason that the derived class itself cannot have a variable of the same name as those inherited from the parent classes. In order to access it, no qualification would be required, but qualification with the derived class name is permitted.

It should be apparent to you that once you understand single inheritance, multiple inheritance is nothing more than an extension of the same rules. Of course, if you inherit two methods or variables of the same name, you must use qualification to allow the compiler to select the correct one.

Constructors are called for both classes before the derived class constructor is executed. The constructors for the base classes are called in the order they are declared in the class header line.

PRACTICAL MULTIPLE INHERITANCE

Example program ------> DATETIME.H

Examine the example program named DATETIME.H for a practical example using multiple inheritance. You will notice that we are returning to our familiar new_date and time_of_day classes from earlier chapters.

There is a good deal to be learned from this very short header file since it is our first example of member initialization used with multiple inheritance. There are two constructors for this class, the first being a very simple constructor that does nothing in itself, as is evident from an examination of line 13. This constructor allows the default constructors to be executed for the classes new_date and time_of_day. In both cases the constructor that requires no parameters will be executed. A default constructor is available for each of these classes.

The second constructor is more interesting since it does not simply use the default constructor, but instead passes some of the input parameters to the inherited class constructors. Following the colon in line 14 are two member initializers which are used to initialize members of this class. Since the two parent classes are inherited, they are also members of this class and can be initialized as shown. Each of the member initializers is actually a call to a constructor of the base classes and it should be evident that there must be a constructor in each base class with the proper number of input parameters to respond to

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap09.htm (4 of 8)02.03.2005 09:10:21

Page 87: C++ Language Tutorial

C++ Tutorial - Chapter 9

the messages given. You will note that in line 15, we are actually calling the default constructor of the new_date class since no parameters are given explicitly. If we chose, we could simply let the system call the default constructor automatically, but this gives us an explicit comment on what is happening.

Following all member initialization, the normal constructor code for the derived class is executed which in this case is given in line 17.

ORDER OF MEMBER INITIALIZATION

The order of member initialization seems a bit strange, but it does follow a few simple rules. You will recall from the last chapter that the order of member initialization does not follow the order given by the initialization list, but another very strict order over which you have complete control. All inherited classes are initialized first in the order they are listed in the class header. If lines 15 and 16 were reversed, class new_date would still be initialized first because it is mentioned first in line 8. We mentioned that C++ respects its elders and initializes its parents prior to itself. That should be a useful memory aid in the use of member initializers.

Next, all local class members, if there are any, are initialized in the order in which they are declared in the class, not the order in which they are declared in the initialization list.

Finally, after the member initializers are all executed in the proper order, the main body of the constructor is executed in the normal manner.

USING THE NEW CLASS

Example program ------> USEDTTM.CPP

The example program named USEDTTM.CPP uses the datetime class we just built, and like our previous examples, the main program is kept very simple and straight forward. You will note that the default constructor is used for the object named now, and the constructor with the member initializers is used with the objects named birthday and special.

The diligent student should have no trouble understanding the remaining code in this very simple example. You will note that the class, once we are finished with it, is very easy to use because of the effort we put into properly declaring it.

FUTURE DIRECTIONS OF C++

An ANSI committee has been formed to write an ANSI standard for C++. They first met in the Spring of 1990 and have released a preliminary draft of the standard. The goal for the release of the standard is 1998, but until the new standard is released, the C++ language was supposed to stay fairly stable. However, due to the nature of compiler writers and their desire to improve their offerings over their

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap09.htm (5 of 8)02.03.2005 09:10:21

Page 88: C++ Language Tutorial

C++ Tutorial - Chapter 9

competitors, the language has not remained static during this period.

Many changes have been added in recent years that affect the C++ programmer in a big way. You can be sure that the language will evolve into a very usable and reliable language. In the meantime, however, the language is changing and we must follow in order to stay effective and competitive.

There are two areas, however, that should be discussed in a little detail because they will add so much to the language in future years. Those two topics are parameterized types and exception handling, both of which are now available with good C++ compilers.

PARAMETERIZED TYPES

Many times, when developing a program, you wish to perform some operation on more than one data type. For example you may wish to sort a list of integers, another list of floating point numbers, and a list of alphabetic strings. It seems silly to have to write a separate sort function for each of the three types when all three are sorted in the same logical way. With parameterized types, you will be able to write a single sort routine that is capable of sorting all three of the lists.

This is already available in the Ada language as the generic package or procedure. Because it is available in Ada, there is a software components industry that provides programmers with prewritten and thoroughly debugged software routines that work with many different types. When this is generally available in C++, there will be a components industry for C++ and precoded, debugged and efficient source code will be available off the shelf to perform many of the standard operations. These operations will include such things as sorts, queues, stacks, lists, etc. There is already a library of these components available as a part of the ANSI-C++ standard. It is called the Standard Template Library, usually referred to as the STL. Even though studying this library is beyond the scope of this tutorial, it will be very beneficial for you to study it and learn how to use it in your programs.

Most compiler writers have included the ability to use templates in their newest compilers. The next three example programs will illustrate the use of templates according to the proposed ANSI standard. Since some compiler writers did not follow that standard initially, these programs may not work with all compilers. Eventually, all C++ compilers will have to follow the standard in order to remain competitive, so it would pay you to study these examples.

THE FIRST TEMPLATE

Example program ------> TEMPLAT1.CPP

The example program named TEMPLAT1.CPP is the first example of the use of a template. This program is so simple it seems silly to even bother with it but it will illustrate the use of the parameterized type.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap09.htm (6 of 8)02.03.2005 09:10:21

Page 89: C++ Language Tutorial

C++ Tutorial - Chapter 9

The template is given in lines 4 through 8 with the first line indicating that it is a template with a single type to be replaced, the type ANY_TYPE. This type can be replaced by any type which can be used in the comparison operation in line 7. If you have defined a class, and you have overloaded the operator ">", then this template can be used with objects of your class. Thus, you do not have to write a maximum function for each type or class in your program.

This function is included automatically for each type it is called with in the program, and the code itself should be very easy to understand.

The diligent student should realize that nearly the same effect can be achieved through use of a macro, except that when a macro is used, the strict type checking is not done. Because of this and because of the availability of the inline method capability in C++, the use of macros is essentially non-existent by experienced C++ programmers.

A CLASS TEMPLATE

Example program ------> TEMPLAT2.CPP

The example program named TEMPLAT2.CPP is a little more involved since it provides a template for an entire class rather than a single function. The template code is given in lines 6 through 16 and a little study will show that this is an entire class definition. The diligent student will recognize that this is a very weak stack class since there is nothing to prevent popping data from an empty stack, and there is no indication of a full stack. Our intent, however, is to illustrate the use of the parameterized type and to do so using the simplest class possible.

In the main program we create an object named int_stack in line 25 which will be a stack designed to store integers, and another object named float_stack in line 26 which is designed to store float type values. In both cases, we enclose the type we desire this object to work with in "<>" brackets, and the system creates the object by first replacing all instances of ANY_TYPE with the desired type, then creating the object of that type. You will note that any type can be used that has an assignment capability since lines 13 and 14 use the assignment operator on the parameterized type. The assignment operator is used in line 14 because it returns an object of that type which must be assigned to something in the calling program.

Even though the strings are all of differing lengths, we can even use the stack to store a stack of strings if we only store a pointer to the strings and not the entire string. This is illustrated in the object named string_stack defined in line 27 and used later in the program.

This program should be fairly easy for you to follow if you spend a bit of time studying it. You should compile and run it if you have a compiler that will handle this new construct.

REUSING THE STACK CLASS

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap09.htm (7 of 8)02.03.2005 09:10:21

Page 90: C++ Language Tutorial

C++ Tutorial - Chapter 9

Example program ------> TEMPLAT3.CPP

The program named TEMPLAT3.CPP uses the same class with the template as defined in the last program but in this case, it uses the date class developed earlier as the stack members. More specifically, it uses a pointer to the date class as the stack member.

Because class assignment is legal, you could also store the actual class in the stack rather than just the pointer to it. To do so however, would be very inefficient since the entire class would be copied into the stack each time it is pushed and the entire class would be copied out again when it was popped. Use of the pointer is a little more general, so it was illustrated here for your benefit.

All three of the previous programs can be compiled and executed if you have a compiler that supports templates. Parameterized types are a part of the C++ specification, and are included in most of the newest implementations.

EXCEPTION HANDLING

A future version of C++ will have some form of exception handling to allow the programmer to trap errors and prevent the system from completely shutting down when a fatal error occurs. The Ada language allows the programmer to trap any error that occurs, even system errors, execute some recovery code, and continue on with the program execution in a very well defined way.

(Note - Exception handling will be added to this tutorial very soon.)

WHAT SHOULD BE YOUR NEXT STEP?

Once again, we have reached a major milestone in C++ programming. With the ability to use inheritance, you have nearly all of the tools you need to effectively use the object oriented programming techniques of C++ and you would do well to stop studying again and begin programming. The only topic left with C++ is virtual methods which are used for dynamic binding or polymorphism. This will be covered in the next two chapters. The vast majority of all programming can be done without dynamic binding, and in attempting to force it into every program, you could wind up with an unreadable mess, so you should approach it slowly.

Advance to Chapter 10

Return to the Table of Contents

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap09.htm (8 of 8)02.03.2005 09:10:21

Page 91: C++ Language Tutorial

C++ Tutorial - Chapter 10

C++ Tutorial - Chapter 10

VIRTUAL FUNCTIONS

Once again we are into a completely new topic with terminology which will be new to you. If you are new to object oriented programming, you should follow along in this chapter very carefully because every attempt has been made to define every detail of this new and somewhat intimidating topic. However, if you are well versed in object oriented programming, and simply learning C++ as a new language, you may wish to skip the first four programs in this chapter and go directly to the example program named VIRTUAL5.CPP and continue from there to the end of the chapter.

One term which must be defined is polymorphism, a rather large word that simply means similar when used in the context of object oriented programming. Objects are polymorphic if they have some similarities but are still somewhat different. We will see how it is used in the context of object oriented programming as we proceed through this chapter.

We have already studied operator overloading and function overloading in this tutorial, and they are a subtle form of polymorphism since in both cases, a single entity is used to refer to two or more things. The use of virtual functions can be a great aid in programming some kinds of projects as you will see in these two chapters.

A SIMPLE PROGRAM WITH INHERITANCE

Example program ------> VIRTUAL1.CPP

Examine the example program named VIRTUAL1.CPP for the basic program outline we will use for all discussion in this chapter. Since this program has nothing to do with virtual functions, the name may be somewhat misleading. It is named VIRTUAL1.CPP because it is part of a series of programs intended to illustrate the use of virtual functions. The last program in this chapter will illustrate the proper use of virtual functions.

The first program is very simple and you will recognize it as being similar to the programs studied earlier in this tutorial except that this program is greatly simplified in order to effectively instruct you in the use of a virtual function. You will notice that many of the methods from the last chapter have been completely dropped from this example for simplicity, and a new method has been added to the parent class, the method named message() in line 9. Throughout this chapter we will be studying the operation of the method named message() in the base class and the derived classes. For that reason, there is a method named message() in the car class as well as in the new class named boat in lines 30 through 36.

You will also notice that there is a lack of a method named message() in the truck class. This has been done on purpose to illustrate the use of the virtual method, or if you prefer, you can refer to it as a virtual

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap10.htm (1 of 6)02.03.2005 09:10:24

Page 92: C++ Language Tutorial

C++ Tutorial - Chapter 10

function. You will recall that the method named message() from the base class is available in the truck class because the method from the base class is inherited with the keyword public included in line 21.

The method named message() in the base class and in the derived classes has been kept very simple on purpose. Once again, we are interested in the technique of the virtual method rather than a long complicated example.

The main program is as simple as the classes, one object of each of the classes is defined in lines 41 through 44 and the method named message() is called once for each object. The result of executing the program indicates that the method for each is called except for the object named semi, which has no method named message(). As discussed in the last chapter, the method named message() from the parent class is called and the data output to the monitor indicates that this did happen since it displays "Vehicle message" for the object named semi.

The data for the objects is of no concern in this chapter so all data is allowed to default to private type and none is inherited into the derived classes. Some of the data is left in the example program simply to make the classes look like classes. Based on your experience with C++ by now, you realize that the data could be removed since it is not used.

After you understand this program, compile and execute it to see if your compiler gives the same result of execution.

ADDING THE KEYWORD VIRTUAL

Example program ------> VIRTUAL2.CPP

As you examine the next example program named VIRTUAL2.CPP, you will notice that there is one small change in line 9. The keyword virtual has been added to the declaration of the method named message() in the parent class.

It may be a bit of a disappointment to you to learn that this program operates no differently than the last example program. This is because we are using objects directly and virtual methods have nothing to do with objects, only with pointers to objects as we will see soon. There is an additional comment in line 50 illustrating that since all four objects are of different classes, it is impossible to assign any object to any other object in this program. We will soon see that some pointer assignments are permitted between objects of dissimilar classes.

After you are sure that the fact that they are virtual functions, or methods, has nothing to do with the objects as they are instantiated, compile and execute this example program to see if your compiler results in the same output as that listed.

USING OBJECT POINTERS

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap10.htm (2 of 6)02.03.2005 09:10:24

Page 93: C++ Language Tutorial

C++ Tutorial - Chapter 10

Example program ------> VIRTUAL3.CPP

Examine the example program named VIRTUAL3.CPP and you will find a repeat of the first program but with a different main program.

In this program the keyword virtual has been removed from the method declaration in the parent class in line 9, and the main program defines pointers to the objects rather than defining the objects themselves in lines 41 through 44. Since we only defined pointers to the objects, we find it necessary to allocate the objects before using them by using the new operator in lines 46 through 53. Upon running the program, we find that even though we are using pointers to the objects we have done nothing different than what we did in the first program. Upon execution, we find that the program operates in exactly the same manner as the first example program in this chapter. This should not be surprising because a pointer to a method can be used to operate on an object in the same manner as an object can be manipulated.

Be sure to compile and execute this program before continuing on to the next example program. The observant student will notice that we failed to check the allocation to see that it did allocate the objects properly, and we also failed to deallocate the objects prior to terminating the program. As always, in such a simple program, it doesn't matter because the heap will be cleaned up automatically when we return to the operating system.

A POINTER AND A VIRTUAL FUNCTION

Example program ------> VIRTUAL4.CPP

The example program named VIRTUAL4.CPP is identical to the last program except for the addition of the keyword virtual to line 9 once again.

I hope you are not terribly disappointed to find that this program, including the keyword virtual, is still identical to the last program. Once again we are simply using pointers to each of the objects, and in every case the pointer is of the same type as the object to which it points. You will begin to see some changes in the next example program, so be patient, we are almost there.

Once again, it would be best for you to compile and execute this program.

The four previous programs were meant to instruct you in what virtual functions do not do. The next two will show you what virtual functions do.

A SINGLE POINTER TO THE PARENT CLASS

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap10.htm (3 of 6)02.03.2005 09:10:24

Page 94: C++ Language Tutorial

C++ Tutorial - Chapter 10

Example program ------> VIRTUAL5.CPP

Examine the example program named VIRTUAL5.CPP where we almost use a virtual method. Be just a little patient because we are almost ready to use a virtual method.

You will notice that this is another copy of our program with the keyword virtual omitted from line 9 and with a totally different main program. In this program, we only define a single pointer to a class and the pointer is pointing to the base class of the class hierarchy. We will use the single pointer to refer to each of the four classes and observe what the output of the method named message() is.

A little digression is in order to understand how we can use a pointer which has been declared to point to one class, to actually refer to another class. If we referred to a vehicle (in the real world, not necessarily in this program), we could be referring to a car, a truck, a motorcycle, or any other kinds of transportation, because we are referring to a very general form of an object. If however, we were to refer to a car, we are excluding trucks, motorcycles, and all other kinds of transportation, because we are referring to a car specifically. The more general term of vehicle can therefore refer to many kinds of vehicles, but the more specific term of car can only refer to a single kind of vehicle, namely a car.

We can apply the same thought process in C++ and say that if we have a pointer to a vehicle, we can use that pointer to refer to any of the more specific objects, and that is indeed legal in C++ according to the definition of the language. In a like manner, if we have a pointer to a car, we cannot use that pointer to reference any of the other classes including the vehicle class because the pointer to the car class is too specific and restricted to be used on any of the other classes.

THE C++ POINTER RULE

The rule as given in C++ terms is as follows. A pointer declared as pointing to a base class can be used to point to an object of a derived class of that base class, but a pointer to a derived class cannot be used to point to an object of the base class or to any of the other derived classes of the base class. In our program therefore, we are allowed to declare a pointer to the vehicle class which is the base class, and use that pointer to refer to objects of the base class or any of the derived classes.

This is exactly what we do in the main program. We define a single pointer which points to the vehicle class and use it to point to objects of each of the classes in the same order as in the last four programs. In each case, we allocate the object, send a message to the method named message() and deallocate the object before going on to the next class. You will notice that when we send the four messages, we are sending the message to the same method, namely the method named message() which is a part of the vehicle base class. This is because the pointer has a class associated with it. Even though the pointer is actually pointing to four different classes in this program, the program acts as if the pointer is always pointing to an object of the base class because the pointer is of the type of the base class.

The next program will finally do something you have not seen in any C program or in any C++ program

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap10.htm (4 of 6)02.03.2005 09:10:24

Page 95: C++ Language Tutorial

C++ Tutorial - Chapter 10

in this tutorial up to this point. After you compile and execute the current program, we will go on to study our first virtual function.

AN ACTUAL VIRTUAL FUNCTION

Example program ------> VIRTUAL6.CPP

We finally come to an example program with a virtual function that operates as a virtual function and exhibits dynamic binding or polymorphism as it is called. This is in the program named VIRTUAL6.CPP.

This program is identical to the last example program except that the keyword virtual is added to line 9 to make the method named message() a virtual function. You will notice that the keyword virtual only appears in the base class, all classes that derive this class will have the corresponding method automatically declared virtual by the system. In this program, we will once again use the single pointer to the base class and allocate, use, then delete an object of each of the four available classes using the identical code we used in the last program. However, because of the addition of the keyword virtual in line 9, this program acts entirely different from the last example program.

Since the method named message() is declared to be a virtual method in its declaration in the base class, anytime we refer to this method with a pointer to the base class, we actually execute the method associated with one of the derived classes. But this is true only if there is a method available in the derived class and if the pointer is actually pointing to that derived class. When the program is executed, the output reflects the same output we saw in the other cases when we were actually calling the methods in the derived classes, but now we are using a pointer of the base class type to make the calls.

You will notice that in lines 44, 48, 52, and 56, even though the code is identical in each line, the system is making the decision of which method to actually call based on the type of the pointer when each message is sent. The decision of which method to call is not made during the time when the code is compiled but when the code is executed. This is dynamic binding and can be very useful in some programming situations. In fact, there are only three different calls made because the class named truck does not have a method named message(), so the system simply uses the method from the base class to satisfy the message passed. For this reason, a virtual function must have an implementation available in the base class which will be used if one is not available in one or more of the derived classes. Note that the message is actually sent to a pointer to the object, but this is splitting hairs and should not be overly emphasized at this time.

It is probably not obvious, but the observant student will note that the structure of the virtual function in the base class and each of the derived classes is identical. The return type and the number and types of the parameters must be identical for all functions, since a single statement can be used to call any of them.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap10.htm (5 of 6)02.03.2005 09:10:24

Page 96: C++ Language Tutorial

C++ Tutorial - Chapter 10

IS THIS REALLY SIGNIFICANT?

This program probably does not seem to do much when you first approach it, but the dynamic binding is a very useful construct and will be illustrated in the next chapter with a rather simple program that uses the technique of dynamic binding to implement a personnel list for a small company.

If the keyword virtual is used, the system will use late binding which is done at run time, but if the keyword is not included, early binding will be used. What these words actually mean is that with late binding, the compiler does not know which method will actually respond to the message because the type of the pointer is not known at compile time. With early binding, however, the compiler decides at compile time what method will respond to the message sent to the pointer.

Be sure to compile and execute this example program before continuing on to the next chapter where we will see a practical example of the use of this technique.

PROGRAMMING EXERCISES

1. Modify VIRTUAL3.CPP to deallocate the objects prior to terminating the program.2. Add a message() method to the truck class of VIRTUAL6.CPP to observe the use of the new

method instead of defaulting to the parent class method.

Advance to Chapter 11

Return to the Table of Contents

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap10.htm (6 of 6)02.03.2005 09:10:24

Page 97: C++ Language Tutorial

C++ Tutorial - Chapter 11

C++ Tutorial - Chapter 11

MORE VIRTUAL FUNCTIONS

This chapter will actually be a continuation of the topics covered in the last chapter but this will be a fuller explanation of what virtual functions are and how they can be used in a program. We will present a simple database program with a virtual function to show how it can be used, then we will go on to illustrate a more complex use of the virtual function in a manner that finally illustrates its utility and reason for existence.

HOW TO START AN OOP PROJECT

The observant student will notice that we begin our use of object oriented programming by identifying an object, or in this case, a class of objects and even some subordinate objects, which we completely define. When we get to the main program we then have a simple job with the remaining needs and they are completed using standard procedural programming techniques which we are familiar with. This is the way to begin any object oriented programming project, by first identifying a few objects that can be separated conveniently from the rest of the code, programming them, then writing the main program. It should be added that, for your first project using objects, do not try to make everything an object. Select a few objects and after gaining experience with object oriented programming techniques, use more objects on future projects. Most programmers use too many objects for their first project and write very obtuse, unreadable code.

THE PERSON HEADER FILE

Example program ------> PERSON.H

Examine the file named PERSON.H for the definition file for the person class. This class definition should cause you no problem to understand since there is nothing new here. The only thing that should be mentioned about this class is that the protected mode is used for the variables so that they are readily available in the derived classes which will inherit this class. Notice that the one method in this class, line 11, is declared virtual.

THE PERSON IMPLEMENTATION

Example program ------> PERSON.CPP

The implementation for the person class is given here and it is a little strange in the way it is written and used. The intent of this program is that the virtual method named display() in this file will never be used, but it is required by the C++ compiler so it can be used for a default in case some of the subclasses do not have this function available. In the main program we will be careful to never call this function

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap11.htm (1 of 7)02.03.2005 09:10:27

Page 98: C++ Language Tutorial

C++ Tutorial - Chapter 11

due to the nature of the program we are writing. Keep in mind that C++ requires an implementation of all virtual functions even if they are never used. In this case the message is obviously intended to be output as an error message.

Be sure to compile this program prior to going on to the next class definitions.

THE SUPERVISOR HEADER

Example program ------> SUPERVSR.H

The file named SUPERVSR.H contains the class definitions for the three derived classes, supervisor, programmer, and secretary. These were all placed in a single file for two reasons. The first reason is to simply illustrate to you that this can be done, and secondly, to allow some of the files to be combined on the disk and to require fewer compilations by you prior to executing the resulting program. This is actually a good way to combine these files since they are all derived classes of a common class. It is a matter of style or personal taste.

You will notice that all three of these classes contain a method named display(), all have the same return value of void, and all have the same number of parameters as the parent class's method of the same name. All of this equality is required because they can all be called by the same call statement. You will also notice that the other method in each class has the same name, but different numbers and types of formal parameters which prevents this method from being used as a virtual method.

The remainder of this file is simple and you should be able to read the code and understand it completely. Once again, this file cannot be compiled or executed.

THE SUPERVISOR IMPLEMENTATION

Example program ------> SUPERVSR.CPP

The file named SUPERVSR.CPP contains the implementation for the three classes. If you spend a little time studying the code, you will find that each of the methods named init_data() simply initializes all fields to those passed in as the actual arguments in a very simple manner.

The method named display(), however, outputs the stored data in different ways for each class since the data is so different in each of the classes. Even though the interface to these three methods is identical, the actual code is significantly different. There is no reason code besides output could not have been used, but the output is so visible when the program is executed that it was chosen for this illustration.

This file should be compiled at this time in preparation for the next example program which will use all four classes as defined in these four files.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap11.htm (2 of 7)02.03.2005 09:10:27

Page 99: C++ Language Tutorial

C++ Tutorial - Chapter 11

THE FIRST CALLING PROGRAM

Example program ------> EMPLOYEE.CPP

The file named EMPLOYEE.CPP is the first program that uses the classes developed in this chapter, and you will find that it is a very simple program.

We begin with an array of ten pointers, each pointing to the base class. As you recall from the last chapter, this is very important when using virtual functions, the pointer must point to the base class. The pointers that will be stored in this array will all point to objects of the derived classes however. When we use the resulting pointers to refer to the methods, the system will choose the method at run time, not at compile time as nearly all of our other programs have been doing.

We allocate six objects in lines 16 through 39, initialize them to some values using the methods named init_data(), then assign the pointers to the members of the array of pointers to person. Finally, in lines 41 through 44, we call the methods named display() to display the stored data on the monitor. You will notice that even though we only use one method call in line 43, we actually send messages to each of the three methods named display() in the derived classes. This is true dynamic binding because if we were to change the values of some of the pointers in the array, we would then call different methods with the same pointers.

In order for this to work, the interface had to be identical for each function, but the implementation could be different for each function. Polymorphism consists of two root words, poly and morph. Poly means different and refers to the implementation, and morph means the same which refers to the interface.

Be sure to compile and execute this program before continuing on in this chapter. You will recall that the linking step requires you to combine several files in order to satisfy all system calls. After you have done that, we will use the same objects in another way to show how they can be reused.

THE LINKED LIST CLASS

Example program ------> ELEMLIST.H

Examination of the file named ELEMLIST.H will reveal the definition of two more classes which will be used to build a linked list of employees to illustrate a more practical way to use the dynamic binding we have been studying in this chapter.

The two classes were put in the same file because they work together so closely and neither is of much value without the other. You will notice that the elements of the linked list do not contain any data, only a pointer to the person class that we developed for the last program, so that the linked list will be

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap11.htm (3 of 7)02.03.2005 09:10:27

Page 100: C++ Language Tutorial

C++ Tutorial - Chapter 11

composed of elements of the person class without modifying the class itself.

There are two interesting constructs used here that must be pointed out before going on to the next program. The first is the partial declaration given in line 8 which allows us to refer to the class named employee_list before we actually declare it. The complete declaration for the class is given in lines 23 through 31. The second construct of interest is the friend class listed in line 18 where we give the entire class named employee_list free access to the variables which are a part of the employee_element class. This is necessary because the method named add_person() must access the pointers contained in employee_element. We could have defined an additional method as a part of employee_element and used this method to refer to the pointers but it was felt that these two classes work so well together that it is not a problem to open a window of visibility between the classes. We still have complete privacy from all other programs and classes declared as parts of this program.

Note that the single method included in the employee_element class is implemented in inline code. Two of the methods of employee_list are still undefined so we need an implementation for this class.

THE LINKED LIST IMPLEMENTATION

Example program ------> ELEMLIST.CPP

The file named ELEMLIST.CPP is the implementation for the linked list classes and should be self explanatory if you understand how a singly linked list operates. All new elements are added to the end of the current list. This was done to keep it simple but an alphabetic sorting mechanism could be added to sort the employees by name if desired. This will be used to store a list of employees as described earlier in this chapter. You will notice that if memory cannot be allocated, the program simply exits. This is not acceptable for a production program that must be competitive in the marketplace. Error recovery is a major topic and one you will need to study someday.

The method to display the list simply traverses the list and calls the method named display() in line 30 once for each element of the list.

It is important for you to take notice that in this entire class, there is no mention made of the existence of the three derived classes which we desribed earlier in this chapter, only the base class named person is mentioned. The linked list therefore has no hint that the three subclasses even exist, but in spite of that, we will see this class send messages to the three subclasses as they are passed through this logic. That is exactly what dynamic binding is, and we will have a little more to say about it after we examine the calling program.

USING THE LINKED LIST

Example program ------> EMPLOYE2.CPP

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap11.htm (4 of 7)02.03.2005 09:10:27

Page 101: C++ Language Tutorial

C++ Tutorial - Chapter 11

At this time you should examine the example program named EMPLOYE2.CPP for our best example of dynamic binding in this tutorial, yet the program is kept very simple.

This program is very similar to the example program named EMPLOYEE.CPP with a few changes to better illustrate dynamic binding. In line 7 we define an object of the class employee_list to begin our linked list. This is the only copy of the list we will need for this program. For each of the elements, we allocate the data, fill it, and send it to the linked list to be added to the list where we allocate another linked list element to point to the new data, and add it to the list. The code is very similar to the last program down through line 40.

In line 43 we send a message to the display_list() method which outputs the entire list of personnel. You will notice that the linked list class defined in the files named ELEMLIST.H and ELEMLIST.CPP are never informed in any way that the subclasses even exist but they dutifully pass the pointers to these subclasses to the correct methods and the program runs as expected.

WHAT GOOD IS ALL OF THIS?

Now that we have the program completely debugged and working, suppose that we wished to add another class to the program. For example, suppose we wished to add a class named consultant because we wished to include some consultants in our business.

We would have to write the class of course and the methods within the classes, but the linked list doesn't need to know that the new class is added, so it doesn't require any changes in order to update the program to handle consultant class objects. In this particular case, the linked list is very small and easy to understand, but suppose the code was very long and complex as with a large database. It would be very difficult to update every reference to the subclasses and add another subclass to every list where they were referred to, and this operation would be very error prone. In the present example program, the linked list would not even have to be recompiled in order to add the new functionality.

It should be clear to you that it would be possible to actually define new types, dynamically allocate them, and begin using them even while the program was executing if we properly partitioned the code into executable units operating in parallel. This would not be easy, but it could be done for a large database that was tracking the inventory for a large retail store, or even for an airlines reservation system. You probably have little difficulty understanding the use of dynamically allocated memory for data, but dynamically allocating classes or types is new and difficult to grasp, but the possibility is there with dynamic binding.

If you were very alert, you noticed that we have no provision to deallocate either the elements of the list or the list itself. To add it, we would need to add a method to the employee_list class, possibly named delete_person(), and add a destructor to the employee_data class .

AN APPLICATION FRAMEWORK

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap11.htm (5 of 7)02.03.2005 09:10:27

Page 102: C++ Language Tutorial

C++ Tutorial - Chapter 11

Example program ------> APPFRAM1.CPP

The example program named APPFRAM1.CPP illustrates the method used to write an application framework. If you do much serious programming, you will encounter one because they provide so many benefits for the MS Windows programmer. There are application frameworks available for other operating systems too, so most programmers should be familiar with them.

The class named CForm is the base class for our trivial but important example, and it consists of four methods but no data members. The diligent student will note that the method named display_form calls the other three members to actually do the work of displaying our little form on the monitor. There is nothing magic about this program except that it is the framework for a very interesting concept used by all of the application frameworks currently available. Note that three of the methods are declared as virtual in lines 9 through 11.

The interesting part occurs when we inherit the class into our new class named CMyForm in line 27 and write new methods for two of the base class methods. We have inherited as much functionality from the base class as we liked, and written new methods for those that didn't serve our purpose as originally written. When we finally execute an object of the new class in line 42 of the main program, we do indeed use part of the base class, and override those parts that we explicitly wrote methods for.

This is not too appealing in such a simple example, but if we consider how this is used in a real application framework, it is a very useful construct. The writer of an application framework will write a complete program that does all of the necessary housekeeping and windows maintenance chores and partition it in a number of virtual methods much like we did here. Of course, the framework will be composed of a large body of code to do all of those chores. In much the same manner that we picked which parts of this little display program we wished to use, and which to override, we pick those parts of the framework that we wish to keep as is and override those parts that we wish change. A large body of code is therefore already written for us and ready for our use.

The application framework can include many other preprogrammed functions ready for our use, such as editor code for edit windows, data verification code for dialogue windows, and ready to use message window code. You will find it to be a very rewarding study to spend time examining the capabilities of one or more of the commercially available application frameworks.

A PURE VIRTUAL FUNCTION

Example program ------> APPFRAM2.CPP

The example program named APPFRAM2.CPP illustrates a pure virtual function. A pure virtual function is declared by assigning the value of zero to the function as illustrated in line 10. A class containing one or more pure virtual functions cannot be used to define an object. The class is therefore

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap11.htm (6 of 7)02.03.2005 09:10:27

Page 103: C++ Language Tutorial

C++ Tutorial - Chapter 11

only useful as a base class to be inherited into a useable derived class. It is sometimes called an abstract class.

Every derived class must include a function for each pure virtual function that is inherited from the base class if it will be used to create an object. This assures that there will be a function available for each call and none will ever need to be answered by the base class, which it cannot do since it does not have an implementation for a pure virtual function. You cannot create an object of any class which contains one or more pure virtual functions, because there is nothing to answer a message if one is sent to the pure virtual method. The compiler will enforce the two rules mentioned in this paragraph. If a class inherits an abstract class without providing an override for the pure virtual function, then it too becomes an abstract class and cannot be used to define an object.

You will notice that the present example uses an abstract base class which makes it illegal to use an object of the base class as we did in the last example program. For that reason, some of the main program is commented out.

You will find abstract classes used in many commercially available libraries and in application frameworks. Be sure to compile and execute this program, then make some modifications to see what the compiler indicates if you try to violate some of the rules we have delineated here.

PROGRAMMING EXERCISES

1. Add a new class named consultant to the files named SUPERVSR.H and SUPERVSR.CPP, then add code to EMPLOYE2.CPP to exercise the new class. Note that you do not need to recompile the linked list class in order to execute the new code and use the new class. Even without recompiling the linked list class it is capable of storing and passing the new class of data provided of course that the new class is referred to using a pointer to the parent class.

Advance to Chapter 12

Return to the Table of Contents

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap11.htm (7 of 7)02.03.2005 09:10:27

Page 104: C++ Language Tutorial

C++ Tutorial - Chapter 12

C++ Tutorial - Chapter 12

FLYAWAY ADVENTURE GAME

Now that you have learned lots of things about C++, and know how to write and use a single isolated class, you have the problem of how to build a program with several classes that work together to accomplish some task. After some amount of thought, it seems that an adventure game is a good candidate for a relatively large example program. It has lots of input and output and requires a good deal of flexibility while running since there are so many things that can be included in the game as obstacles, mazes, items to find, and puzzles to solve.

The adventure game presented in this chapter is unique as far as I know, since I have never heard of another adventure game featuring an airport. The location is not nearly as important as the code used to get through the airport. You are advised to play the game to get familiar with what the code does, then study the code to see how it works. Finally, you are given an assignment to extend the code which will be the real test of whether you understand its operation.

PLAYING THE GAME

Example program ------> FLYAWAY.EXE

Prior to studying the source code for this game, it would be to your advantage to spend some time playing the game to get familiar with what the game does. Load the file FLYAWAY.EXE (available for downloading in the same manner as the source files were downloaded) and begin the adventure through the airport. The executable file is precompiled for you so you can begin executing the program before you have to compile and link the whole thing. The entire program is composed of 15 files and will take a little effort on your part to properly compile and link it, but that will come later.

If you have played adventure games before, sometimes called interactive fiction, you should begin trying various commands to find your way through the airport to your proper plane. If you have not played before, a few hints are in order concerning how to play the game.

The object of the game is to get to your proper plane on time so you can fly away to your vacation. Of course there a few obstacles and problems along the way and they will be brought up at the appropriate time. It will be up to you to solve the puzzles associated with each problem. To add a little excitement, you only have about twenty-five minutes to get to your plane, with each move taking a minute, so you must hurry. Of course, just getting to the plane on time is not enough, there are a few additional requirements. You will find what they are as you progress through the game. You will probably find it necessary to restart the game many times before you arrive at your destination unscathed and on time.

THE METHOD OF PLAY

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap12.htm (1 of 9)02.03.2005 09:10:30

Page 105: C++ Language Tutorial

C++ Tutorial - Chapter 12

The method of play is extremely simple. You simply wander around the airport looking for things to do and places to go. You move around the airport by giving the system commands to move in a certain direction with four choices available, north, south, east, or west. You can abbreviate any of these four direction commands to the first letter only, and you can use either upper or lower case. The system may move you to another area of the airport, or it may tell you that you can't go that way. Try loading the game now and typing the four directions once each to see what happens. If this is not clear, enter the word help to get you started.

In addition to moving around, you can pick up items or ask for more information in any of the rooms. Try telling the system to look around the room and see what additional information it gives you for each room, some of the clues for solving the puzzle are given in the clues issued in response to a look command. Another important command is inventory which will give you a list of the items you possess at any given point in time. Type the word inventory at this time to see what items you possess.

The remainder of the commands consist of two words, a verb and a noun. These can be given in either order, since the system is smart enough to know the difference, and additional words may be given following the legal words. If you give the system a command that is not in its limited vocabulary, it will tell you it doesn't understand that word. Try telling the system to drop an item you possess, or get an item that is located in the room you are currently in.

Several friends have played this game with no more knowledge than you have been given. One solved it in 40 minutes, but most took about an hour to complete the game. After you play the game for awhile, return to the text and we will study the source code for the game. The entire source code for the game is contained in cppcrc.zip which you should have accessed to obtain all of the example programs for this tutorial. The game was purposely kept small so the code could be easily grasped by a programming student. There is no reason the game could not have been made much larger by the addition of more rooms, items, and traps. You may choose to do just that to gain experience in working with C++.

A FEW SPECIAL CONSTANTS

Example program ------> FLYAWAY.H

The file named FLYAWAY.H contains the definitions for TRUE and FALSE as well as the enumerated type defining the legal dictionary of words for use in playing the game. The list was started at a value of 1 so the value of zero can be used to indicate that the word in question was not in the library and hence not a legal word for use with the game.

The #ifndef in line 4 is required because this header file is included in many of the other files and if it is included more than once, there will be a multiple definition, and hence an error. A class only needs to be defined once, so after it is defined by one of the includes, the name FLYAWAY_H will be defined and any other defines will be ignored. This is necessary because of the separate compilation capability of C+

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap12.htm (2 of 9)02.03.2005 09:10:30

Page 106: C++ Language Tutorial

C++ Tutorial - Chapter 12

+. This was described in more detail near the end of chapter 7.

THE FIRST CLASS - clock

Example program ------> CLOCK.H

Examine the file named CLOCK.H for the definition of the clock class. This is the class for the game clock, and only one instance of this class will be used. It will be used for the object time_of_day defined in line 23 of FLYAWAY.CPP.

The class is very simple, consisting of only two variables, the hour and the minute, and four methods. The first method is the constructor used to initialize the clock to 8:51 as you can see if you refer to the implementation of this class in the file named CLOCK.CPP. The next two methods are used to get the current values of the two variables. The final method is much more interesting since it does more. It updates the time of day clock and outputs the user prompt to ask for the next command. This may not be the best place to output the user prompt since this class is devoted to the time of day and associated operations, but this was chosen as the place to do it since the time of day is part of the user prompt. You will notice that the clock was initialized to 8:51, but the first time output was 8:52 when you played the game. In order to simplify the coding later, when we need to decide if we made it to the plane on time, the time was incremented at the beginning of each game move. The time is therefore the same when the command is entered and when it is executed, hence the time is incremented prior to even the first output. The clock class is by far the simplest class in the adventure game and should be simple for you to understand. After you are sure you understand it, we will go on to the next class.

INPUT COMMAND PARSING

Example program ------> WORDS.H

The input command parsing routines are defined within the words class and the code for the class is in WORDS.CPP. The code is straightforward and simple to understand if you study it, so only a few comments will be made about this class.

The method get_command() reads two words from the keyboard by calling the function read_a_line() and stores the words in the class members verb and noun. It stores zero for either or both of the words if it does not find a valid noun and a valid verb.

Two methods are included to provide the verb or noun which was input as the last user input. This allows any code that has visibility of the object based on this class to find out what the player would like to do.

There are four methods beginning with is_ in this class that are used to determine if a word is a verb, a noun, a direction, or an operation. These are called upon from various places within the program. What

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap12.htm (3 of 9)02.03.2005 09:10:30

Page 107: C++ Language Tutorial

C++ Tutorial - Chapter 12

they do should be easy for you to understand, but it will take a little thought on your part to see why these are needed in other parts of the code.

Finally the simple method named stop_game() is used to set the verb to the value of quit so the game will be ended by the control logic in the main program FLYAWAY.CPP.

All of the source code for the implementation is given in the file named WORDS.CPP. Since this code is fairly simple and well commented, you will be left on your own to study it to whatever depth you desire.

THE SECOND CLASS - items

Example program ------> ITEMS.H

If you examine the files named ITEMS.H and ITEMS.CPP, you will find the complete definitions of the handling of the items that you carried around the airport in the game. There were exactly four transportable items that could be located in each room or carried by yourself, the keys, the candy, the ticket, and the money. The keys and the money keep you from getting through security and the ticket and candy are required to get you safely on the plane and enroute to your destination.

The four items are stored in the class named items in the form of TRUE or FALSE since that is the only required indication. A TRUE means the item is located here, and a FALSE means the item is not here. The values of TRUE and FALSE are defined in FLYAWAY.H. Finally, there are six methods to operate on these items.

The first method is a constructor to set all items to FALSE, and the next two are used to either get a specific item, or drop one. The fourth method is used to tell us if the item is located here and the last two are used to tell us what items are on hand in this location. You will notice that the final two are different because different text was desired depending on whether you are carrying the items, or they are located in a room somewhere.

This file, like all other header files, is protected from multiple inclusion by the #ifndef construct discussed earlier.

This class is used in line 24 of FLYAWAY.CPP to define an object for the player named personal_items which stores the list of items the player is carrying around. It is also used in the class location as an embedded or nested object to store the items that are located in each of the 19 locations in the game.

Once again, the implementation for this class is so simple that you will have no difficulty in understanding it.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap12.htm (4 of 9)02.03.2005 09:10:30

Page 108: C++ Language Tutorial

C++ Tutorial - Chapter 12

THE FLIGHT AND GATE CLASS - schedule

Example program ------> SCHEDULE.H

Examine the example files named SCHEDULE.H and SCHEDULE.CPP for our first example of a rather large class, the one that does the flight and gate scheduling. You will find a large number of variables in this class, and eight methods to handle the variables. Instead of a detailed description of each variable and method, we will only give a brief overview of the class.

Only one object of this class is declared named flight_info in line 22 of the main program named FLYAWAY.CPP. The constructor initializes the flight possibilities, and the method named shuffle_gates() shuffles all gates around if the player arrives at his correct gate without reading the monitor in the waiting area. Once the monitor in the waiting area is read, the flights_frozen variable is made TRUE. Likewise, the players destination is changed during every move by the method named shuffle_flights() until the player reads his ticket invoking the method named list_actual_destination().

This class contains the methods to list the data seen on the monitor, as well as the data seen when invoking the command look at one of the gates. Finally, this class contains the method named check_flight() which searches through the list of requirements to see if the player has completed all requirements to successfully reach the final destination for his vacation.

You will notice that several of the location objects were required to be available within this code and are listed as extern in lines 12 through 21 of the implementation of the class. The only other thing to point out is the rest room requirement prior to boarding the flight. Line 28 is where the global variable is defined and initialized, then in line 77 it is set TRUE if the current location is the rest room, since this is called once during each player move. Finally, the state of this variable is checked in line 230 of this file and the appropriate action taken. You will note that the main program is not aware that the rest room variable exists or that anything happens as a result of this variable. In addition to information hiding, we may coin a new term, something like "Information Ignorance", since the main program did not even need to be aware that there was a requirement to visit the rest room.

Even though this is a relatively large and complex class, it is well commented so no further information will be given concerning the implementation.

THE MOST USED CLASS - location

Example program ------> LOCATION.H

The file named LOCATION.H is the header file for the class named location. It is the class that controls all of the moves from location to location.

This class is a bit unusual in that most of the stored data is in the form of pointers to the various entities.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap12.htm (5 of 9)02.03.2005 09:10:30

Page 109: C++ Language Tutorial

C++ Tutorial - Chapter 12

The first four are the locations to which we will go if we move in one of the four directions from the current location. You will note that they are pointers to those four locations. Next we have pointers to two different character strings associated with this room. Finally in line 22, we declare the object named list_of_items which is an object of class items defined earlier. Note that this is an embedded class, a class embedded within the location class. It is not a parent class which we are inheriting something from. In fact we are instantiating an object of class items for use within the room since the room is allowed to store any combination of the four items contained in the class named items.

There is no constructor used with this class since we choose to initialize the locations one by one. The method named init() has 6 variable parameters, all of which are pointers, associated with it which it uses to initialize the first six variables of this object. The last variable, an object of class items, is initialized through use of the constructor associated with its class. Referring to lines 40 through 171 of the implementation for the map class, you will find all of the initialization code for the 19 objects of class location. If you drew a map when you played the game, you will see the interconnections between the various locations embedded in the initialization statements. Notice there is no way to get back to the car from the passenger drop off area, because presumably the car leaves when you get out of it.

The next method, named move(), returns a pointer to the new location if a move was legal, otherwise it returns a NULL value. The observant student will also notice that there are special cases involved with getting out of the snack bar and getting through security. These are located here because they are part of the move logic. If you played the game to the complete conclusion, you surely had trouble with at least one of these situations.

The rest of the methods in this class should be self explanatory and will not be discussed any further.

THE LOCATION MESSAGES

Example program ------> MESSAGE.TXT

Examine the file named MESSAGE.TXT for a complete listing of the messages output to the monitor when each location was entered. You will also find the text for each of the messages output in response to a look command in this file. These were put into a separate file only for the purpose of reducing the size of the map class implementation file. It does not reduce the compile time since these messages are not separately compiled. They are included into the file and compiled each time the map file MAP.CPP is compiled. You will note that a few of the messages have no text at all, only the empty quote marks, but are included in order to have something for the initialization code to work with.

Three other messages are stored here for convenience in lines 5 through 40. Their use and meaning should be self-evident.

THE MAIN PROGRAM

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap12.htm (6 of 9)02.03.2005 09:10:30

Page 110: C++ Language Tutorial

C++ Tutorial - Chapter 12

Example program ------> FLYAWAY.CPP

We finally reach the main program, the one that actually does the top level control. Examine the program named FLYAWAY.CPP and we will look at some of its interesting characteristics.

Beginning with the main() entry point itself, we see that following a call to airport.initialize(), we enter a single do while loop which terminates when the player enters the word quit or when the verb quit comes up some other way. There are other ways to set the verb to quit because it is generated internally in some cases such as at end of game.

The loop itself consists of 5 method calls. First we call the function named input_words.get_command() to get the players input command in line 30. Next we send two messages to the object named flight_info to shuffle the flights and gates if the proper actions have not been performed, then we call airport.perform_action() which we will describe in a few paragraphs. Finally, we send a messages to the object named flight_info to check if the player has reached one of the gates. Remember that within most of the methods we perform checks to see if we need to do the thing requested in the message, then either perform the action or simply return to the caller or message sender.

THE WORKING METHOD

Example program ------> MAP.H

The only function we have not mentioned yet is the one that does most of the interesting work, the function named perform_action() which begins in line 183 of the MAP.CPP file. This function looks at the verb and noun, if there is one, and causes the correct action to be performed. Because of the way we packaged all of the other routines, this function is a snap to implement and to study. If you go through each of the else if clauses in this function, you will have no trouble understanding what action is taken for each of the input commands. You will notice that many of the actions have conditional clauses before the action is taken. For example, it is illegal to buy candy unless the player has money, the location has candy, and the location must be the snack_bar according to the rules of the game.

Finally, at the end of this method in line 277, we have the default case if nothing else was accomplished. It is assumed that there was something funny requested such as a request to get a monitor. Both of these are legal words but they make no sense together.

FINAL COMMENTS ON FLYAWAY

Now that you have played the game for awhile and studied the game in detail, you should have an appreciation for how this game can be written. Of course, it could be written in any of several thousand different ways of packaging and definition. This has been only one of the ways.

Because the student may be left with the sinking feeling that this method simply fell out of the sky or

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap12.htm (7 of 9)02.03.2005 09:10:30

Page 111: C++ Language Tutorial

C++ Tutorial - Chapter 12

was arrived at in some other esoteric way, it would only be fair to point out that several earlier attempts at outlining this project were attempted and rejected prior to this arrangement. Also, when this tutorial was being updated from version 2.0 to 2.2, the entire program was restructured. In version 2.0 and prior versions, about 50% of the code was in classes, but due to additional programming experience, about 98% of the flyaway program is now encapsulated in classes.

Object oriented programming requires the same forethought as non-object oriented programming, but the object oriented compiler will help you in the coding and debugging phase since the compiler will find and flag many of the oversight errors we are so good at introducing into our code. It was observed during the coding and debugging phase of this project that in nearly every case, when the program finally got through the compiler, the program would actually run without bombing out the system. This is not always the case using any standard procedural programming language.

YOUR PROGRAMMING PROJECT

This programming assignment is intended to give you a little experience in working with a relatively large project as opposed to the very small programs we have been working with in this tutorial.

Add a suitcase to the game, to be found in the car at arrival, and which must be checked in at the ticket counter prior to attempting to get through airport security. This will not be trivial since several classes will be affected. Some of the operations you will have to do are listed below.

1. Add the noun "suitcase" and the verb "check" to the word list. Of course, they must be entered at the right place in the list.

2. Add the suitcase to the items class, including additional code to each of its methods.3. Initialize the items at location your_car to include the suitcase.4. Add an additional check when passing through security to check that the player is not carrying

the suitcase. You can add any sort of penalty desired, including death by firing squad for attempting such an obviously crooked deed.

5. You will need to add a check when the player finally gets on his correct airplane to see that he checked his suitcase. If he did not, you could output any desired text indicating stupidity or forgetfulness.

Since I have not actually added the suitcase to the game and tested it, I am not sure that this is all that will be required, but it should be the majority of effort required. The bottom line of this effort is that if you understand this program enough to perform this modification, you have a good understanding of how the program works and how objects work together to perform a task.

Once you understand this program, you should define a programming project for yourself that will use object oriented programming techniques and begin designing and programming it. The best way to learn to use OOP is to actually use it.

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap12.htm (8 of 9)02.03.2005 09:10:30

Page 112: C++ Language Tutorial

C++ Tutorial - Chapter 12

Good luck in your OOP endeavors.

Return to Table of Contents

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/chap12.htm (9 of 9)02.03.2005 09:10:30

Page 113: C++ Language Tutorial

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/PHRASE.INL

// Chapter 6 - Program 12 - PHRASE.INL

#include <string.h> inline phrase::phrase(void){ strcpy(noun, ""); strcpy(verb, ""); strcpy(full_phrase, "(No text yet)");}

inline void phrase::set_noun(char *in_noun){ strcpy(noun, in_noun);}

inline void phrase::set_verb(char *in_verb){ strcpy(verb, in_verb);}

inline char *phrase::get_phrase(void){ strcpy(full_phrase, verb); strcat(full_phrase, " the "); strcat(full_phrase, noun); return full_phrase;}

// Result of execution//// (This file cannot be executed)

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/PHRASE.INL02.03.2005 09:10:56

Page 114: C++ Language Tutorial

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/MESSAGE.TXT

// The first three messages are relatively long, so they have // been removed from the text in order to make the text more // readable.

char startup_message[] = " Welcome to Flyaway, version 2.60\n\n" " Your best friend offered to drop you off at the airport\n" " so you can begin your dream vacation and you have just\n" " arrived at the passenger drop off area. You have about\n" " 25 minutes to get to your plane, you haven't had any \n" " lunch, and you have a full bladder. Be very careful, \n" " there is a lot of construction going on all around the \n" " airport. Good luck!\n\n" " Type help if you want a few clues and a word list.\n\n";

char paper_message[] = "\n C++ TUTORIAL RELEASED\n" "Coronado Enterprises has a full line of computer language\n" "programming tutorials available. Write and ask for the\n" "latest information.\n" " Coronado Enterprises\n" " 12501 Coronado Ave NE\n" " Albuquerque, NM 87122\n\n" "There is another story about danger at the airport due to\n" "construction. Be very careful!\n";

char help_message[] = // Help "Each action requires a verb, or a verb and a noun, and only\n" "the first two words of the command are significant, any \n" "other words on a line are ignored. The four directions can\n" "be abbreviated to the first letter to make it easier to get\n" "to your flight. The entire vocabulary is given as;\n\n" " ------- verbs ------- ---- nouns ----\n" " north drop read keys money\n" " east get buy candy monitor\n" " south look help ticket paper\n" " west quit inventory\n\n" " look = give more information on current location\n" " inventory = list items I am carrying\n\n" "You better hurry, you just wasted a minute reading this.\n\n";

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/MESSAGE.TXT (1 of 4)02.03.2005 09:11:30

Page 115: C++ Language Tutorial

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/MESSAGE.TXT

// These messages are output when entering a location

char your_car_message[] = ""; // Never needed - can't enter here

char pass_drop_off_message[] = "You are in the passenger drop off area.\n";

char lobby_message[] = "You are in the airport lobby.\n";

char baggage_claim_message[] = "You are in the baggage claim area. There are a few bags left\n" "over from the last flight slowly going around the carrosel.\n";

char dark_room_message[] = "You are in a poorly lit room and as you move about, you step\n" "on a board that gives way under your weight. You fall into \n" "a subbasement and are killed. No vacation - game over.\n";

char ticket_counter_message[] = "You are at the ticket counter area.\n";

char tunnel_message[] = "You are in the tunnel to the gates.\n";

char rest_room_message[] = "You are in the rest room, and it really feels good to have\n" "taken care of that problem.\n";

char snack_bar_message[] = "You are in the snack bar and gift shop.\n";

char security_message[] = "You are in the security and inspection area leading toward\n" "all gates.\n";

char waiting_area_message[] = "You are in the waiting area between the gates.\n";

char gate1_message[] = "You are in the gate 1 waiting area.\n";

char gate2_message[] =

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/MESSAGE.TXT (2 of 4)02.03.2005 09:11:30

Page 116: C++ Language Tutorial

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/MESSAGE.TXT

"You are in the gate 2 waiting area.\n";

char gate3_message[] = "You are in the gate 3 waiting area.\n";

char gate4_message[] = "You are in the gate 4 waiting area.\n";

char plane_message[] = "You are inside of a large Jumbo-jet. The doors close, and\n" "the plane taxis away from the gate to prepare for takeoff.\n";

// These are output in response to a "look" command

char y_c_look_message[] = "You are in your car with your friend, but that should have\n" "been obvious. You better hurry, you may miss your plane.\n";

char p_d_o_look_message[] = "The airport entrance is to the north.\n";

char l_look_message[] = "A small newsstand is here, and the latest edition of the news-\n" "paper is on the newsstand. A group of three ragged looking\n" "characters have signs that proclaim \"BAN THE BOMB\", and are\n" "trying to sell you some books.\n";

char b_c_look_message[] = "There is a dark room to the west with a sign near the door\n" "that cautions you to keep out - danger. You should not enter\n" "this room under any circumstances.\n";

char d_r_look_message[] = "";

char t_c_look_message[] = "There is a departure monitor on the west wall with a list of\n" "all of the currently active flights. Wilbur Snuffle is stand-\n" "ing behind the ticket counter. He asks if you have any baggage\n" "to check through.\n";

char t_look_message[] = "A sign on the north wall says \"TO ALL GATES\".\n";

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/MESSAGE.TXT (3 of 4)02.03.2005 09:11:30

Page 117: C++ Language Tutorial

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/MESSAGE.TXT

char r_r_look_message[] = "That's not at all polite to look around in here, and there is\n" "nothing of interest here, you better hurry to your flight.\n";

char s_b_look_message[] = "There are many expensive items for sale here, but have no need\n" "of any of those expensive things. They are always overpriced\n" "at the airport anyway. A sweet looking old lady is ready to\n" "help you find what you need.\n";

char s_look_message[] = "The security inspectors are to the north, and they look you\n" "over very carefully as you enter. The tall inspector is Ralph\n" "and the short one is either Homer or Bill.\n";

char w_a_look_message[] = "There is a departure monitor on the north wall, and a lot of\n" "construction material laying around everywhere.\n";

char g1_look_message[] = "";

char g2_look_message[] = "";

char g3_look_message[] = "";

char g4_look_message[] = "";

char plane_look_message[] = "";

http://hellnet.perverz.hu/ebookz/C++%20LANGUAGE%20TUTORIAL/MESSAGE.TXT (4 of 4)02.03.2005 09:11:30