coronado enterprises c++ tutor - version 2 · 2006. 5. 28. · c++ tutor - version 2.2 this...

119
CORONADO ENTERPRISES C++ TUTOR - Version 2.2 Gordon Dodrill - Jan 20, 1992 Copyright (c) 1989, 1990, 1992 Coronado Enterprises Coronado Enterprises 12501 Coronado Ave NE Albuquerque, New Mexico 87122

Upload: others

Post on 30-Aug-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

CORONADO ENTERPRISES

C++ TUTOR - Version 2.2

Gordon Dodrill - Jan 20, 1992

Copyright (c) 1989, 1990, 1992 Coronado Enterprises

Coronado Enterprises12501 Coronado Ave NE

Albuquerque, New Mexico 87122

Page 2: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Table of contents––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––I.1

CORONADO ENTERPRISES

C++ TUTOR - Version 2.2

This documentation and the accompanying software, including all of the example C++programs and text files, are protected under United States copyright law to protect themfrom unauthorized commercialization. This version of the tutorial is distributed underthe shareware concept, which means you are not required to pay for it. You arepermitted to copy the disks, and pass the copies on to a friend, provided that you donot modify any files or omit any files from the complete package. You are, in fact,encouraged to pass on complete copies to friends. You are permitted to charge a smallfee to cover the costs of duplication, but you are not permitted to charge anything forthe software itself.

If you find the tutorial helpful, you are encouraged to register with the author and tosubmit a small fee to help compensate him for his time and expense in writing it. Wewill provide you with a beautifully printed copy of the tutorial if you submit a fullregistration. See the READ.ME file in either the TEXT directory or the SOURCEdirectory for additional details.

Whether or not you send a registration fee, feel free to request a copy of the latest listof available tutorials and a list of the authorized Shareware libraries that distribute ourfull line of programming language tutorials.

Gordon Dodrill - Jan 20, 1992

Copyright (c) 1989, 1990, 1992 Coronado Enterprises

Coronado Enterprises12501 Coronado Ave NE

Albuquerque, New Mexico 87122

Page 3: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Table of contents––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––I.2

C++ TUTORIAL - TABLE OF CONTENTS

Introduction Page I-1

Chapter 1 - Simple Things Page 1-1

CONCOM.CPP Constants and comments 1-1SCOPEOP.CPP Scope operator 1-3MESSAGE.CPP The stream library 1-3FSTREAM.CPP File streams 1-5VARDEF.CPP Variable definitions 1-6

Chapter 2 - Compound Types Page 2-1

ENUM.CPP The enumerated type 2-1STRUCTUR.CPP The structure 2-1CLASS1.CPP The class 2-2UNIONEX.CPP The union 2-3TYPECONV.CPP Type conversions 2-3

Chapter 3 - Pointers Page 3-1

POINTERS.CPP Using Pointers 3-1NEWDEL.CPP New and delete operators 3-2FUNCPNT.CPP Function pointers 3-4

Chapter 4 - Functions Page 4-1

PROTYPE1.CPP Using prototypes 4-1PROTYPE2.CPP Using prototypes 4-3PASSREF.CPP Pass by reference 4-4DEFAULT.CPP Parameter defaults 4-5VARARGS.CPP Variable number of arguments 4-6OVERLOAD.CPP Overloading function names 4-7

Chapter 5 - Encapsulation Page 5-1

OPEN.CPP No information hiding 5-1CLAS.CPP Information hiding 5-2OPENPOLE.CPP Corruptible data 5-6CLASPOLE.CPP Protected data 5-7CONSPOLE.CPP Constructors and destructors 5-9BOXES1.CPP All in one file 5-10BOX.H Box interface 5-11BOX.CPP Box implementation 5-11BOXES2.CPP Using the box class 5-12DATE.H The date class header 5-15DATE.CPP The date implementation 5-15USEDATE.CPP Using the date class 5-16

Page 4: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Table of contents––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––I.3

Chapter 6 - More encapsulation Page 6-1

OBJARRAY.CPP An Array of objects 6-1OBJSTRNG.CPP An object with a string 6-3OBJINTPT.CPP An object with a pointer 6-3OBJDYNAM.CPP Dynamic allocation of objects 6-5OBJLIST.CPP Embedded pointers 6-5OBJLINK.CPP Linked list of objects 6-7NESTING.CPP Nested classes 6-8OPOVERLD.CPP Operator overloading 6-9FUNCOVER.CPP Function name overloading 6-11TIME.H The time class header 6-12TIME.CPP The time implementation 6-12USETIME.CPP Using the time class 6-12

Chapter 7 - Inheritance Page 7-1

VEHICLE.H Vehicle interface 7-1VEHICLE.CPP Vehicle implementation 7-2TRANSPRT.CPP Using the vehicle class 7-2CAR.H Car interface 7-3CAR.CPP Car implementation 7-4TRUCK.H Truck interface 7-5TRUCK.CPP Truck implementation 7-5ALLVEHIC.CPP Use of car, truck, & vehicle 7-5NEWDATE.H The newdate class header 7-7NEWDATE.CPP The newdate implementaion 7-7TRYNDATE.CPP Using the newdate class 7-8

Chapter 8 - More inheritance Page 8-1

INHERIT1.CPP Using public 8-1INHERIT2.CPP Omitting public 8-2INHERIT3.CPP Intra class messages 8-3INHERIT4.CPP Without protected 8-4INHERIT5.CPP Using protected 8-5INHERIT6.CPP Using Constructors 8-5INHERIT7.CPP Arrays and pointers 8-6

Chapter 9 - Multiple Inheritance Page 9-1

MULTINH1.CPP Multiple inheritance 9-2MULTINH2.CPP Duplicate method names 9-3MULTINH3.CPP Duplicate variable names 9-4DATETIME.H Datetime class header 9-4USEDTTM.CPP Using the datetime class 9-6TEMPLAT1.CPP Simple template example 9-7TEMPLAT2.CPP Strings template example 9-7TEMPLAT3.CPP Class template example 9-8

Page 5: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Table of contents––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––I.4

Chapter 10 - Virtual functions Page 10-1

VIRTUAL1.CPP The starting point 10-1VIRTUAL2.CPP Adding virtual 10-2VIRTUAL3.CPP Using pointers to subclasses 10-3VIRTUAL4.CPP Using virtual 10-3VIRTUAL5.CPP Using pointers to parent class 10-4VIRTUAL6.CPP True virtual functions 10-5

Chapter 11 - More Virtual Functions Page 11-1

PERSON.H Person header 11-1PERSON.CPP Person implementation 11-2SUPERVSR.H Personnel header 11-2SUPERVSR.CPP Personnel implementation 11-2EMPLOYEE.CPP A simple user program 11-3ELEMLIST.H Linked list header 11-4ELEMLIST.CPP Linked list implementation 11-5EMPLOYE2.CPP A better user program 11-5

Chapter 12 - Flyaway adventure game Page 12-1

FLYAWAY.EXE Flyaway executable 12-1FLYAWAY.H Global definitions 12-3CLOCK.H Clock header 12-3CLOCK.CPP Clock implementation 12-3WORDS.H Command parsing header 12-4WORDS.CPP Command parsing code 12-4ITEMS.H Moveable items header 12-4ITEMS.CPP Items implementation 12-4SCHEDULE.H Scheduler header 12-5SCHEDULE.CPP Scheduler implementation 12-5LOCATION.H Locations header 12-6LOCATION.CPP Locations implementation 12-6MESSAGE.TXT String messages 12-7FLYAWAY.CPP Main program 12-7MAP.H Airport map header 12-8MAP.CPP Airport map implementation 12-8

Page 6: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Table of contents––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––I.5

ABOUT THE AUTHOR

_________________________________________________________________

The author of this tutorial began programming in 1961 using FORTRAN on an IBM1620. Since then, most of his career has been involved with designing digital logic forsatellite application. In 1983, being somewhat burned out with logic design, he began astudy of some of the more modern programming languages and has since made acomplete career shift to software development. After learning Pascal, C was studied,followed by Modula-2 and Ada, and more recently C++. Rather than simply learningthe syntax of each new language, modern methods of software engineering werestudied and applied to effectively utilize the languages. He is currently employed by alarge research and development laboratory where he continues to study, teach, andapply the newer programming languages.

Page 7: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Introduction - What is C++––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––II.1

Introduction

WHAT IS C++

THE ORIGIN OF C++

_________________________________________________________________

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

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

HOW TO GET STARTED IN C++

_________________________________________________________________

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

This tutorial will assume a thorough knowledge of the C programming language andlittle time will be spent on the fundamental aspects of the language. However, becausewe realize that many programmers have learned the dialect of C as defined byKernigan & Ritchie, some sections will be devoted to explaining the newer additions asprovided by the ANSI-C standard. As the ANSI-C standard was in development, manyof the newer constructs from C++ were included as parts of C itself, so even though

Page 8: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Introduction - What is C++––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––II.2

C++ is a derivation and extension of C, it would be fair to say that ANSI-C has some ofits roots in C++. An example is prototyping which was developed for C++ and lateradded to C.

The best way to learn C++ is by using it. Almost any valid C program is also a validC++ program, and in fact the addition of about 12 keywords is the only reason thatsome C programs will not compile and execute as a C++ program. There are a fewother subtle differences but we will save the discussion of them until later. Since this istrue, the best way to learn C++ is to simply add to your present knowledge and use afew new constructs as you need them for each new program. It would be atremendous 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 bemore inefficient than the same program written purely in C. It would be far better to adda few new constructs to your toolkit each day, and use them as needed while you gainexperience with their use.

As an illustration of the portability of C to C++, all of the example programs included inthe Coronado Enterprises C tutorial compile and execute correctly when compiled asC++ programs with no changes. None of the C++ programs will compile and executecorrectly with any C compiler however, if for no other reason than the use of the newstyle of C++ comments.

HOW TO USE THIS TUTORIAL

_________________________________________________________________

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

After you successfully compile and execute the example program, introduce a fewerrors into the program to see what kind of error messages are issued. If you havedone much programming, you will not be surprised if your compiler gives you an errormessage that seems to have nothing to do with the error introduced. This is becauseerror message analysis is a very difficult problem with any modern programminglanguage. The most important result of these error introduction exercises is theexperience you will gain using your compiler and understanding its nuances. Youshould then attempt to extend the program using the techniques introduced with theprogram to gain experience. In the text of this tutorial, keywords, variable names, andfunction names will be written in bold type as an aid when you are studying theexample programs.

The way this tutorial is written, you will not find it necessary to compile and executeevery program. At the end of each example program, listed in comments, you will findthe result of execution of that program. Some of the constructs are simple and easy foryou to understand, so you may choose to ignore compilation and execution of thatexample program, depending upon the result of execution to give you the output.

Page 9: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Introduction - What is C++––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––II.3

Some students have used these results of execution to study several chapters of thistutorial on an airplane by referring to a hardcopy of the example programs.

Page 10: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Introduction - What is C++––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––II.4

DIFFERENT C++ IMPLEMENTATIONS

_________________________________________________________________

There are primarily two standards for naming C++ files, one using the extension CPPand the other using the extension CXX. All files in this tutorial use the CPP extensionfor naming files. If your compiler requires the CXX extension it will be up to you torename the files. When C++ was in its infancy, header files generally used theextension .HPP, but there is a definite trend to use .H for all header files. For thatreason 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 possiblethat some constructs will not actually compile and run with some C++ compilers. As wefind new implementations of C++, and acquire copies of them, we will compile andexecute all files in an attempt to make all example programs as universal as possible.

The C++ language is very new and is changing rapidly. The developer of thelanguage, AT&T, has changed the formal definition several times in the last few yearsand the compiler writers are staying busy trying to keep up with them. It would be bestfor you to search the more popular programming languages for evaluations andcomparisons of compilers. New C++ implementations are being introduced at such arapid rate, that we cannot make a compiler recommendation here.

PRINTING OUT THE EXAMPLE PROGRAMS

_________________________________________________________________

Some students prefer to work from a hardcopy of the example programs. If you desireto print out the example programs, there is a batch file on the distribution disk to helpyou do this. Make the distribution disk the default drive and type PRINTALL at the userprompt and the system will print out about 170 pages of C++ programs, all of theexample programs in this tutorial.

The PRINTALL batch file calls the program named LIST.EXE once for each exampleprogram on the distribution disk. LIST.EXE was written in TURBO Pascal and compiledfor your use in listing any program with line numbers and the date and time the programwas last modified. TURBO Pascal was used because Borland does not require alicensing fee for distributing copies of the resulting run time files, and this file is includedwith all Coronado Enterprises tutorials.

Page 11: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Introduction - What is C++––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––II.5

PROGRAMMING EXERCISES

_________________________________________________________________

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

An answer for each programming exercise is given in the ANSWERS directory on thedistribution disk. The answers are all given in compilable C++ source files named in theformat CHnn_m.CPP, where nn is the chapter number and m is the exercise number. Ifmore than one answer is required, an A, B, or C, is included following the exercisenumber.

RECOMMENDED ADDITIONAL READING

_________________________________________________________________

Richard S. Wiener & Lewis J. Pinson. "An Introduction to Object- Oriented Programming and C++". Addison-Wesley, 1988. This is the first book recommended since it covers both object oriented programming and C++ in depth. It is clearly written and well organized.

Brad Cox. "Object Oriented Programming, An Evolutionary Approach". Addison-Wesley, 1986. This book is excellent for a study of object oriented programming and what it is, but since it is based on Objective-C, it covers nothing of the C++ language or how to use it.

Stephen Dewhurst & Kathy Stark. Programming in C++". Prentice Hall, 1989. This book covers the fundamentals of the language well and covers the proper application of object oriented programming techniques.

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.

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

Page 12: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Introduction - What is C++––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––II.6

A SPECIAL NOTE FOR THE SHAREWARE VERSION

_________________________________________________________________

It is impossible to include the graphics diagrams in chapters 5 and 7 in a pure ASCIItext. They are therefore omitted from this version of the tutorial. If you need thesediagrams, they can be purchased directly from Coronado Enterprises along with yourregistration. See the READ.ME file in either the TEXT directory or the SOURCEdirectory for more information.

Page 13: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter I - Simple things––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––1.1

Chapter 1

SIMPLE THINGS

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

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

EVEN COMMENTS ARE IMPROVED IN C++

_________________________________________________________________

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

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

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

Page 14: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter I - Simple things––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––1.2

THE KEYWORDS const AND volatile

_________________________________________________________________

There are two new keywords used in lines 9 through 11 which were not part of theoriginal K&R definition of C, but are part of the ANSI-C standard. The keyword const isused to define a constant. In line 9 the constant is of type int, it is named START, andis initialized to the value 3. The compiler will not allow you to accidentally orpurposefully change the value of START because it has been declared a constant. Ifyou had another variable named STARTS, the system would not allow you to slightlymisspell STARTS as START and accidentally change it. The compiler would give youan error message so you could fix the error. Since it is not permissible to change thevalue of a constant, it is imperative that you initialize it when it is declared so it will havea useful value. The compiler does not require you to initialize it however, and will notissue an error message if you do not.

You will note that the keyword const is also used in the function header in line 21 toindicate that the formal parameter named data_value is a constant throughout thefunction. Any attempt to assign a new value to this variable will result in a compileerror. This is a small thing you can add to your programs to improve the compilersability to detect errors for you.

The keyword volatile is also part of the ANSI-C standard but was not included in theoriginal K&R definition of C. Even though the value of a volatile variable can bechanged by you, the programmer, there may be another mechanism by which the valuecould be changed, such as by an interrupt timer causing the value to be incremented.The compiler needs to know that this value may be changed by some external forcewhen 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, whichmeans that you cannot change it, but the system can through some hardware function.

Ignore the output statement given in line 23 for a few minutes. We will study it in somedetail later in this chapter. If you are experienced in K&R style programming, you mayfind line 5 and 21 a little strange. This illustrates prototyping and the modern method offunction definition as defined by the ANSI-C standard. We will discuss this in greatdetail in chapter 4 of this tutorial. Prototyping is optional in C but absolutely required inC++. 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 thelisting. One of the primary purposes of compiling it is to prove that your compiler isloaded and executing properly.

Page 15: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter I - Simple things––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––1.3

THE SCOPE OPERATOR

_________________________________________________________________

The example program named SCOPEOP.CPP ===============illustrates another construct that is new to SCOPEOP.CPPC++. ===============

There is no corresponding construct in either K&R or ANSI-C. This allows access tothe global variable named index even though there is a local variable of the same namewithin the main function. The use of the double colon in front of the variable name, inlines 11, 13, and 16, instructs the system that we are interested in using the globalvariable 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 beused in calculations, as a function parameter, or for any other purpose. It is not reallygood programming practice to abuse this construct, because it could make the codedifficult to read. It would be best to use a different variable name instead of reusing thisname, but the construct is available to you if you find that you need it sometime.

The scope operator allows access to global variables even though hidden by a localvariable. Be sure to compile and execute this program before proceeding on to thenext example program where we will discuss the cout operator in lines 10, 11, 15, and16.

THE iostream LIBRARY

_________________________________________________________________

Examine the example program named MESSAGE.CPP ===============for our first hint of object oriented MESSAGE.CPPprogramming, even though it is a very simple ===============one.

In this program, we define a few variables and assign values to them for use in theoutput statements illustrated in lines 17 through 20, and in lines 23 through 26. Thenew operator cout is the output function to the standard device, the monitor, but worksa little differently from our old familiar printf() function, because we do not have to tellthe system what type we are outputting.

C++, like the C language itself, has no input or output operations as part of thelanguage itself, but defines the stream library to add input and output functions in avery elegant manner.

The operator <<, sometimes called the "put to" operator but more properly called theinsertion operator, tells the system to output the variable or constant following it, butlets the system decide how to output the data. In line 17, we first tell the system tooutput the string, which it does by copying characters to the monitor, then we tell it tooutput the value of index. Notice however, that we fail to tell it what the type is or howto output the value. Since we don't tell the system what the type is, it is up to the

Page 16: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter I - Simple things––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––1.4

system to determine what the type is and to output the value accordingly. After thesystem finds the correct type, we also leave it up to the system to use the built indefault as to how many characters should be used for this output. In this case, we findthat the system uses exactly as many as needed to output the data, with no leading ortrailing blanks, which is fine for this output. Finally, the newline character is output, andthe line of code is terminated with a semicolon.

When we called the cout output function in line 17, we actually called two differentfunctions because we used it to output a string and a variable of type int. This is thefirst hint at object oriented programming because we simply broadcast a message tothe 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 tooutput it. This is a very weak example of object oriented programming, and we will getinto it in much more depth later.

In line 18, we tell the system to output a different string, followed by a floating pointnumber, and another string of one character, the newline character. In this case, wetold it to output a floating point number without telling it that it was a floating pointnumber, once again letting the system choose the appropriate output means based onits type. We did lose a bit of control in the transaction, however, because we had nocontrol over how many significant digits to print before or after the decimal point. Wechose 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 Xin line 14, then printed as a letter in line 19.

Because C++ has several other operators and functions available with streams, youhave complete flexibility in the use of the stream output functions. You should refer toyour compiler documentation for details of other available formatting commands. Thecout and the printf() statements can be mixed in any way you desire. Both statementsresult in output to the monitor.

MORE ABOUT THE stream LIBRARY

_________________________________________________________________

The stream library was defined for use with C++ in order to add to the executionefficiency of the language. The printf() function was developed early in the life of the Clanguage and is meant to be all things to all programmers. As a result, it became ahuge function with lots of extra baggage that is only used by a few programmers. Bydefining the small special purpose stream library, the designer of C++ allows theprogrammer to use somewhat limited formatting capabilities, which are still adequatefor most programming jobs. If more elaborate formatting capabilities are required, thecomplete printf() library is available within any C++ program, and the two types ofoutputs can be freely mixed.

Lines 23 through 26 illustrate some of the additional features of the stream librarywhich can be used to output data in a very flexible yet controlled format. The value ofindex 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

Page 17: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter I - Simple things––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––1.5

output will be in that number base. Looking ahead to line 32, we find the value of indexprinted in hex format due to the selection of the hexadecimal base in line 25. If none ofthese special stream operators are output, the system defaults to decimal format.

THE cin OPERATOR

_________________________________________________________________

In addition to the cout operator, there is a cin operator which is used to read data fromthe standard input device, usually the keyboard. The cin operator uses the >>operator, usually called the "get from" operator but properly called the extractionoperator. It has most of the flexibility of the cout operator. A brief example of the use ofthe cin operator 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 coutstream. If none is specified, the input stream also defaults to decimal.

In addition to the cout operator and the cin operator there is one more standardoperator, the cerr, which is used to output to the error handling device. This devicecannot be redirected to a file like the output to the cout can be. The three operators,cout, cin, and cerr, correspond to the stdout, the stdin, and the stderr stream pointers ofthe programming language C. Their use will be illustrated throughout the remainder ofthis tutorial.

The stream library also has file I/O capability which will be briefly illustrated in the nextexample 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 echoedback to the monitor, but changed to the hexadecimal base.

FILE STREAM OPERATIONS

_________________________________________________________________

Examine the example program named FSTREAM.CPP ===============for examples of the use of streams with files. FSTREAM.CPP ===============

In this program a file is opened for reading, another for writing, and a third stream isopened to the printer to illustrate the semantics of stream operations on a file. The onlydifference between the streams in the last program and the streams in this program isthe fact that in the last program, the streams were already opened for us by the system.You will note that the stream named printer is used in the same way we used the coutoperator in the last program. Finally, because we wish to exercise good programmingpractice, we close all of the files we have opened prior to ending the program.

The standard file I/O library is available with ANSI-C and is as easy to use as thestream library and very portable. For more information on the stream file I/O library,

Page 18: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter I - Simple things––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––1.6

see Bjarne Stroustrup's book which is listed in the introduction to this tutorial, or refer toyour compiler documentation.

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

VARIABLE DEFINITIONS

_________________________________________________________________

Examine the file named VARDEF.CPP for a few more ==============additions to the C++ language which aid in VARDEF.CPPwriting a clear and easy to understand program. ==============

In C++, as in ANSI-C, global and static variables are automatically initialized to zerowhen they are declared. The variables named index in line 4, and goofy in line 26 aretherefore automatically initialized to zero. Of course, you can still initialize either tosome other value if you so desire. Global variables are sometimes called externalsince they are external to any functions.

Automatic variables, those declared inside of any function, are not automaticallyinitialized but will contain the value that happens to be in the location where they aredefined, 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 beused for any meaningful purpose. In line 11, it is assigned a value based on theinitialized value of index and it is then displayed on the monitor for your examination.

THE REFERENCE VARIABLE

_________________________________________________________________

Notice the ampersand in line 9. This defines another_stuff as a reference variablewhich is a new addition to C++. The reference variable should not be used very often,if at all, in this context. In order to be complete however, we will discuss its operation.The reference variable is not quite the same as any other variable because it operateslike a self dereferencing pointer. Following its initialization, the reference variablebecomes a synonym for the variable stuff, and changing the value of stuff will changethe value of another_stuff because they are both actually referring to the samevariable. The synonym can be used to access the value of the variable for any legalpurpose in the language. It should be pointed out that a reference variable must beinitialized to reference some other variable when it is declared or the compiler willrespond with an error. Following initialization, the reference variable cannot bechanged to refer to a different variable.

The use of the reference variable in this way can lead to very confusing code, but it hasanother use where it can make the code very clear and easy to understand. We willstudy this use in chapter 4 of this tutorial.

Page 19: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter I - Simple things––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––1.7

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 alsolegal to declare a new variable because a data declaration is defined as an executablestatement in C++. In this case, we define the new variable named more_stuff andinitialize it to the value of 13. It has a scope from the point where it was defined to theend of the block in which it is defined, so it is valid throughout the remainder of themain program. The variable named goofy is declared even later in line 26.

It is very significant that the variable is declared near its point of usage. This makes iteasier to see just what the variable is used for, since it has a much more restrictedscope of validity. When you are debugging a program, it is convenient if the variabledeclaration 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-Calso for that matter. They really are different and have different meanings, so weshould spend a little time defining exactly what the words mean in C++. A declarationprovides information to the compiler about the characteristics of something such as atype or a function but it doesn't actually define any code to be used in the executableprogram, and you are permitted to make as many declarations of the same entity asyou desire. A definition, on the other hand, actually defines something that will exist inthe executable program, either some useful variables, or some executable code, andyou are required to have one and only one definition of each entity in the program. Inshort, a declaration introduces a name into the program and a definition introducessome code.

If we declare a struct, we are only declaring a pattern to tell the compiler how to storedata later when we define one or more variables of that type. But when we definesome variables of that type, we are actually declaring their names for use by thecompiler, 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 thesame time.

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

Page 20: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter I - Simple things––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––1.8

A BETTER for LOOP

_________________________________________________________________

Take careful notice of the for loop defined in line 20. This loop is a little clearer thanthe for loop that is available in ANSI- C, because the loop index is defined in the forloop itself. The scope of this loop index is from its declaration to the end of theenclosing block. In this case its scope extends to line 29 since the closing brace in line29 corresponds to the most recent opening brace prior to the declaration of thevariable. Since the variable is still available, it can be used for another loop index or forany other purpose which an integer type variable can legally be used for. The variablenamed count2 is declared and initialized during each pass through the loop because itis declared within the block controlled by the for loop. Its scope is only the extent of theloop so that it is automatically deallocated each time the loop is completed. It istherefore declared, initialized, used and deallocated five times, once for each passthrough the loop.

You will notice that the variable count2 is assigned a numerical value in line 22 butwhen it is printed out, a character value is actually output. This is because C++(version 2.0 and later) is careful to use the correct type.

Finally, as mentioned earlier, the static variable named goofy is declared andautomatically initialized to zero in line 26. Its scope is from the point of its declaration tothe end of the block in which it is declared, line 29.

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 madehere to define it. There is a small difference when some operators are overloadedwhich we will learn to do later in this tutorial. Some of the operators act slightly differentwhen 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 afterwe have studied a few more topics.

Page 21: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter I - Simple things––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––1.9

PROGRAMMING EXERCISES

_________________________________________________________________

1. Write a program that displays your name and date of birth on the monitor three times using the cout function. 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 will give you.

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

Page 22: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 2 - Compound types––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––2.1

Chapter 2

COMPOUND TYPES

ENUMERATED TYPES

_________________________________________________________________

Examine the file named ENUM.CPP for an example ==============that uses an enumerated type variable. ENUM.CPP ==============

The enumerated type is used in C++ in exactly the same way it was used in ANSI-C with one small exception, the keyword enum is not required to be used again whendefining a variable of that type, but it can be used if desired. It may be clearer to you touse the keyword when defining a variable in the same manner that it is required to beused 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 illustrateto you that it is indeed optional. The remainder of this program should be no problemfor you to understand. After studying it, be sure to compile and execute it and examinethe output.

A SIMPLE STRUCTURE

_________________________________________________________________

Examine the example program named STRUCTUR.CPP ================for an illustration using a very simple STRUCTUR.CPPstructure. ================

This structure is no different from that used in ANSI-C except for the fact that thekeyword struct is not required to be used again when defining a variable of that type.Lines 11 and 12 illustrate the declaration of variables without the keyword, and line 13indicates that the keyword struct can be included if desired. It is up to you to choosewhich style you prefer to use in your C++ programs.

You should take note of the fact that this is a valid ANSI-C program except for the factthat it uses the stream library, the C++ comments, and the lack of use of the keywordstruct in two of the lines.

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 newconstruct not available in standard C, the class.

Page 23: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 2 - Compound types––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––2.2

A VERY SIMPLE CLASS

_________________________________________________________________

Examine the example program named CLASS1.CPP for ==============our first example of a class in C++. CLASS1.CPP ==============

This is the first class example, but it will not be the last, since the class is the majorreason for using C++ over ANSI-C or some other programming language. You willnotice the keyword class used in line 4, in exactly the same way that the keyword structwas used in the last program, and they are in fact very similar constructs. There aredefinite differences, as we will see, but for the present time we will be concerned morewith their similarities.

The word animal in line 4 is the name of the class, and when we declare variables ofthis type in lines 12 through 14, we can either omit the keyword class or include it if wedesire as illustrated in line 14. In the last program, we declared 5 variables of astructure type, but in this program we declare 5 objects. They are called objectsbecause they are of a class type. The differences are subtle, and in this case thedifferences are negligible, but as we proceed through this tutorial, we will see that theclass construct is indeed very important and valuable. The class was introduced hereonly to give you a glimpse of what is to come later in this tutorial.

The class is a type which can be used to declare objects in much the same way that astructure is a type that can be used to declare variables. Your dog named King is aspecific instance of the general class of dogs, and in a similar manner, an object is aspecific instance of a class. It would be well to take note of the fact that the class issuch a generalized concept that there will be libraries of prewritten classes available inthe marketplace soon. You will be able to purchase classes which will perform somegeneralized operations such as managing stacks, queues, or lists, sorting data,managing windows, etc. This is because of the generality and flexibility of the classconstruct. In fact, a few class libraries are available now.

The new keyword public in line 5, followed by a colon, is necessary in this casebecause the variables in a class are defaulted to a private type and we could notaccess them at all without making them public. Don't worry about this program yet, wewill cover all of this in great detail later in this tutorial.

Be sure to compile and run it 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 essentiallynothing concerning the use of this powerful C++ construct.

Page 24: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 2 - Compound types––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––2.3

THE FREE UNION OF C++

_________________________________________________________________

Examine the program named UNIONEX.CPP for an ===============example of a free union. UNIONEX.CPP ===============

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 isembedded within a simple structure and you will notice that there is not a variable namefollowing the declaration of the union in line 11. In ANSI-C, we would have to name theunion 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 withonly a doubly dotted name as illustrated in lines 18, 22, 26, 28, and 29.

You will recall that a union causes all the data contained within the union to be stored inthe same physical memory locations, such that only one variable is actually available ata 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 tothe programmer to keep track of which variable is stored there at any given time. Youwill notice that the transport is assigned a value for pallets in line 26, then a value forfuel_load in line 28. When the value for fuel_load is assigned, the value for pallets iscorrupted and is no longer available since it was stored where fuel_load is currentlystored. The observant student will notice that this is exactly the way the union is used inANSI-C except for the way components are named.

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

C++ TYPE CONVERSIONS

_________________________________________________________________

Examine the program named TYPECONV.CPP for a few ================examples of type conversions in C++. TYPECONV.CPP ================

The type conversions are done in C++ in exactly the same manner as they are done inANSI-C, but C++ gives you another form for doing the conversions.

Lines 10 through 18 of this program use the familiar "cast" form of type conversionsused in ANSI-C, and there is nothing new to the experienced C programmer. You willnotice that lines 10 through 13 are actually all identical to each other. The onlydifference is that we are coercing the compiler to do the indicated type conversionsprior 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 theresulting float will be converted to type char prior to being assigned to the variable c.

Page 25: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 2 - Compound types––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––2.4

Additional examples of type coercion are given in lines 15 through 18 and all four ofthese lines are essentially the same.

he examples given in lines 20 through 28 are unique to C++ and are not valid in ANSI-C. In these lines the type coercions are written as though they are function callsinstead of the "cast" method as illustrated earlier. Lines 20 through 28 are identical tolines 10 through 18.

You may find this method of type coercion to be clearer and easier to understand thanthe "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.

Page 26: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 2 - Compound types––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––2.5

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.

Page 27: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 3 - Pointers––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––3.1

Chapter 3

POINTERS

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

POINTER REVIEW

_________________________________________________________________

Examine the program named POINTERS.CPP for a ================simple example of the use of pointers. POINTERS.CPP ================

This is a pointer review and if you are comfortable with the use of pointers, you canskip this example program completely. A pointer in either ANSI-C or C++ is declaredwith an asterisk preceding the variable name. The pointer is then a pointer to avariable 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 anyother type. Of course, an experienced C programmer knows that it is simple to coercethe pointer to be used with some other type by using a cast, but he must assume theresponsibility for its correct usage.

In line 12 the pointer named pt_int is assigned the address of the variable named pigand line 13 uses the pointer named pt_int to add the value of dog to the value of pigbecause the asterisk dereferences the pointer in exactly the same manner as standardC. The address is used to print out the value of the variable pig in line 14 illustrating theuse of a pointer with the stream output operator cout. Likewise, the pointer to floatnamed pt_float is assigned the address of x, then used in a trivial calculation in line 18.

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

Page 28: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 3 - Pointers––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––3.2

CONSTANT POINTERS AND POINTERS TO CONSTANTS

_________________________________________________________________

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

Either of these constructs can be used to provide additional compile time checking andimprove the quality of your code. If you know a pointer will never be moved due to itsnature, you should define it as a constant pointer. If you know that a value will not bechanged, it can be defined as a constant and the compiler will tell you if you everinadvertently 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 iscommented upon here. A pointer to void can be assigned the value of any otherpointer type. You will notice that the pointer to void named general is assigned anaddress of an int type in line 15 and the address of a float type in line 20 with no castand no complaints from the compiler. This is a relatively new concept in C and C++. Itallows a programmer to define a pointer that can be used to point to many differentkinds of things to transfer information around within a program. A good example is themalloc() function which returns a pointer to void. This pointer can be assigned to pointto 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 thesimple predefined types available in C++, or in ANSI-C for that matter. They will alsoalign with any compound types the user can define since compound types arecomposed of the simpler types.

Be sure to compile and execute this program.

Page 29: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 3 - Pointers––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––3.3

DYNAMIC ALLOCATION AND DEALLOCATION

_________________________________________________________________

Examine the program named NEWDEL.CPP for our ================first example of the new and delete operators. NEWDEL.CPP ================

The new and delete operators do dynamic allocation and deallocation in much thesame manner that malloc() and free() do in your old favorite C implementation.

During the design of C++, it was felt that since dynamic allocation and deallocation aresuch a heavily used part of the C programming language and would also be heavilyused in C++, it should be a part of the language, rather than a library add-on. The newand delete operators are actually a part of the C++ language and are operators, muchlike 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 14 and 15 illustrate the use of pointers in the tradition of C and line 16 illustratesthe use of the new operator. This operator requires one modifier which must be a typeas illustrated here. The pointer named point2 is now pointing at the dynamicallyallocated integer variable which exists on the heap, and can be used in the same waythat any dynamically allocated variable is used in ANSI-C. Line 18 illustrates displayingthe value on the monitor which was assigned in line 17.

Line 20 allocates another new variable and line 21 causes point2 to refer to the samedynamically allocated variable as point1 is pointing to. In this case, the reference to thevariable that point2 was previously pointing to has been lost and it can never be usedor deallocated. It is lost on the heap until we return to the operating system when it willbe reclaimed for further use, so this is obviously not good practice. Note that point1 isdeallocated with the delete operator in line 25, and point2 can not actually be deleted.Since the pointer point1 itself is not changed, it is actually still pointing to the originaldata on the heap. This data could probably be referred to again using point1, but itwould be terrible programming practice since you have no guarantee what the systemwill do with the pointer or the data. The data storage is returned to the free list to beallocated 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 legalto ask the system to delete the data pointed to by a pointer with the value of NULL, butnothing will actually happen. It is actually wasted code. The delete operator can onlybe used to delete data allocated by a new operator. If the delete is used with any otherkind of data, the operation is undefined and anything can happen. According to theANSI standard, even a system crash is a legal result of this illegal operation, and canbe defined as such by the compiler writer.

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

Page 30: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 3 - Pointers––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––3.4

Some examples of the use of a structure are given in lines 35 through 41 and shouldbe self explanatory.

Finally, since the new operator requires a type to determine the size of the dynamicallyallocated block, you may wonder how you can allocate a block of arbitrary size. This ispossible by using the construct illustrated in line 47 where a block of 37 char sizedentities, which will be 37 bytes, is allocated. A block of 133 bytes greater than the sizeof the date structure is allocated in line 49. It is therefore clear that the new operatorcan be used with all of the flexibility of the malloc() function which you are familiar with.

The standard functions which you have been using in C for dynamic memorymanagement, malloc(), calloc(), and free(), are also available for use in C++ and can beused in the same manner they were used in C. The new and delete operators shouldnot be intermixed with the older function calls since the results may be unpredictable. Ifyou are updating code with the older function calls, continue to use them for anyadditions to the code. If you are designing and coding a new program you should usethe newer constructs because they are a built in part of the language rather than anadd on and are therefore more efficient.

Be sure to compile and execute this program.

POINTERS TO FUNCTIONS

_________________________________________________________________

Examine the program named FUNCPNT.CPP for an ===============example of using a pointer to a function. FUNCPNT.CPP ===============

It must be pointed out that there is nothing new here, the pointer to a function isavailable in ANSI-C as well as in C++ and works in the manner described here for bothlanguages. It is not regularly used by most C programmers, so it is defined here as arefresher. If you are comfortable with the use of pointers to functions, you can skip thisdiscussion entirely.

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

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

Page 31: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 3 - Pointers––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––3.5

Since we assigned the name of a function to a function pointer, and did not get anassignment error, the name of a function must be a pointer to that function. This isexactly the case. A function name is a pointer to that function, but it is a pointerconstant and cannot be changed. This is exactly the case we found when we studiedarrays in ANSI-C at some point in our C programming background. An array name is apointer constant to the first element of the array.

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

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

Be sure to compile and execute this program.

Page 32: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 3 - Pointers––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––3.6

PROGRAMMING EXERCISES

_________________________________________________________________

1. When dynamically allocated data is deleted, it is still actually in memory, stored on the heap. Repeat the output statement from line 23 of NEWDEL.CPP immediately following the delete in line 25 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.

Page 33: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 4 - Function––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––4.1

Chapter 4

FUNCTIONS

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

Prototyping allows the compiler to do additional type checking for your function callswhich can detect some programming errors. The first two example programs in thischapter are designed to teach prototyping and what it will do for you. Prototyping is arelatively new addition to C, so even some experienced C programmers are not familiarwith it. If you have experience with prototyping you can skip directly to the sectionnamed PASS BY REFERENCE on page 4-4 of this chapter.

PROTOTYPES

_________________________________________________________________

Examine the file named PROTYPE1.CPP for our ================first look at a prototype and an illustration PROTYPE1.CPPof how it is used. ================

The prototyping used in C++ is no different than that used in ANSI-C. Actually, many Cprogrammers take a rather dim view of prototyping and seem reluctant to use it, butwith 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, thefull 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 checkthe calls to the function for the proper number of parameters and the correct types ofparameters. Each call to the function named do_stuff() must have exactly threeparameters or the compiler will give an error message. In addition to the correctnumber of parameters, the types must be compatible or the compiler will issue an errormessage. Notice that when the compiler is working on lines 12 and 13, the typechecking can be done based on the prototype in line 4 even though the function itself isnot yet defined. If the prototype is not given, the number of parameters will not bechecked, nor will the types of the parameters be checked. Even if you have the wrongnumber of parameters, you will get an apparently good compile and link, but theprogram 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 theprogram and append a semicolon to the end as a signal to the compiler that this is nota function but a prototype. The variable names given in the prototype are optional and

Page 34: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 4 - Function––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––4.2

act merely as comments to the program reader since they are completely ignored bythe compiler. You could replace the variable name wings in line 4 with your first nameand there would be no difference in compilation. Of course, the next person that had toread 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 correctso 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 asa number rather than as a character. The cast to int in line 20 is required to force theprintout of the numerical value rather than an ASCII character. The next exampleprogram is similar but without the cast to int.

COMPATIBLE TYPES

_________________________________________________________________

We mentioned compatible types earlier so we should review them just a bit in order tomake our discussion of prototyping complete. Compatible types are any simple typesthat can be converted from one to another in a meaningful way. For example, if youused an integer as the actual parameter and the function was expecting a float type asthe formal parameter, the system would do the conversion automatically, withoutmentioning it to you. This is also true of a float changing to a char, or a char changingto an int. There are definite conversion rules which would be followed. These rules aregiven in great detail in section 3.2 of the draft of the ANSI-C standard and are alsogiven 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 integeras the formal parameter in the function, the conversion would not be made becausethey are two entirely different kinds of values. Likewise, a structure would not beconverted automatically to a long float, an array, or even to a different kind of structure,they are all incompatible and cannot be converted in any meaningful manner. Theentire issue of type compatibility as discussed in chapter 2 of this tutorial appliesequally well to the compatibility of types when calling a function. Likewise, the typespecified as the return type, in this case void, must be compatible with the expectedreturn 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 whatkinds of error messages you get when you do certain wrong things. Change the actualparameters in line 12 to read (12.2, 13, 12345) and see what the compiler says aboutthat change. It will probably say nothing because they are all type compatible. If youchange it to read (12.0, 13), it will issue a warning or error because there are notenough arguments given. Likewise you should receive an error message if you change

Page 35: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 4 - Function––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––4.3

one of the parameters in line 13 to an address by putting an ampersand in front of oneof the variable names. Finally, change the first word in line 4 from void to int and seewhat kind of error message is given. You will first be required to make the functionheader in line 16 agree with the prototype, then you will find that there is not a variablereturned from the function. You should have a good feeling that prototyping is doingsomething good for you after making these changes.

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

A LITTLE MORE PROTOTYPING

_________________________________________________________________

Examine the next example program named ================PROTYPE2.CPP for a little more information on PROTYPE2.CPPprototyping. 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 merely as anillustration that they are interpreted as comments by the C++ compiler. The functionheader is formatted differently to allow for a comment alongside each of the actualparameters. This should make the function header a little more self explanatory.However, you should remember that comments should not be used to replace carefulselection of variable names. In this particular case, the comments add essentiallynothing to the clarity of the program.

WHAT DOES PROTOTYPING COST ?

_________________________________________________________________

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

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

Be sure to compile and execute this example program. You will find that it is identicalto the last example program.

Page 36: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 4 - Function––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––4.4

PASS BY REFERENCE

_________________________________________________________________

Examine the file named PASSREF.CPP for an ===============example of a pass by reference, a construct PASSREF.CPPwhich is not available in ANSI-C. ===============

The reference variable was mentioned in chapter 1 and it was recommended there thatyou don't use it in the manner illustrated there. This example program illustrates asituation where it can be used to your advantage. The pass by reference allows thepassing of a variable to a function and returning the changes made in the function tothe main program. In ANSI-C the same effect can be seen when a pointer to a variableis 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 ofthe variable name. The ampersand instructs the compiler to treat this variable just likeit were passed a pointer to the variable since the actual variable from the main programwill be used in the function. In the function itself, in lines 21 through 24, the variable in2is used just like any other variable but we are using the variable passed to this functionfrom the main program not a copy of it. The other variable named in1 is treated just likeany other normal variable in ANSI-C. In effect, the name in2 is a synonym for thevariable named index in the main program.

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

void fiddle(int, int&);

If you are a Pascal programmer, you will recognize that the variable named in1 istreated just like a normal parameter in a Pascal call, a call by value. The variablenamed in2 however, is treated like a variable with the reserved word VAR used in frontof it usually referred to as a call by reference. The reference variable is actually a selfdereferencing pointer which refers to, or points to, the original value.

When you compile and execute this program, you will find that the first variable gotchanged in the function but was returned to its original value when we returned to themain program. The second variable however, was changed in the function and the newvalue was reflected back into the variable in the main program which we can see whenthe values are listed on the monitor.

Page 37: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 4 - Function––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––4.5

DEFAULT PARAMETERS

_________________________________________________________________

Examine the file named DEFAULT.CPP for an ===============example of the use of default parameters in C++. DEFAULT.CPP ===============

This program really looks strange since it contains default values for some of theparameters in the prototype, but these default values are very useful as we will seeshortly.

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

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

There are a few rules which should be obvious but will be stated anyway. Once aparameter is given a default value in the list of formal parameters, all of the remainingmust 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 ofthe correct types or a compiler error will be issued. The default values can be given ineither the prototype or the function header, but not in both. If they are given in bothplaces, the compiler must not only use the default value, but it must carefully check tosee that both values are identical. This could further complicate an already verycomplicated problem, that of writing a C++ compiler.

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

Page 38: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 4 - Function––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––4.6

WHY IS THE OUTPUT SCRAMBLED ?

_________________________________________________________________

When the compiler finds a cout statement, the complete line of code is initially scannedfrom right to left to evaluate any functions, then the data is output field by field from leftto right. Therefore in line 11, get_value() is evaluated with its internal output displayedfirst. 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_value() is output in int format,the type of the returned value. The end result is that the output is not in the expectedorder when lines 11 through 13 are executed. (The output is not what you wouldintuitively expect to happen so appears to be a deficiency in the language. A call toBorland International, the writers of Turbo C++ and Borland C++, verified that this isoperating correctly.)

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 thefunny output order will appear again later in this tutorial.

VARIABLE NUMBER OF ARGUMENTS

_________________________________________________________________

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

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

You will note that the main program consists of three calls to the function, each with adifferent number of parameters, and the system does not balk at the differences in thefunction 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 andrun it for you. Of course the compiler is ignoring all type checking beyond the firstparameter so it is up to you to make sure you use the correct parameter types in thiscall.

Page 39: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 4 - Function––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––4.7

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

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

FUNCTION NAME OVERLOADING

_________________________________________________________________

Examine the file named OVERLOAD.CPP for an ================example of a program with the function names OVERLOAD.CPPoverloaded. ================

This is not possible in ANSI-C, but is perfectly legal and in fact used quite regularly inC++. At first this will seem a bit strange, but it is one of the keystones of objectoriented programming. You will see its utility and purpose very clearly in later chaptersof this tutorial.

You will notice in this example program that there are three functions, in addition to themain 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 theanswer is, the function that has the correct number of formal parameters of the correcttypes. If do_stuff() is called with an integer value or variable as its actual parameter,the function beginning in line 23 will be called and executed. If the single actualparameter is of type float, the function beginning in line 28 will be called, and if twofloats are specified, the function beginning in line 34 will be called.

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

The keyword overload used in line 4 tells the system that you really do intend tooverload the name do_stuff, and the overloading is not merely an oversight. This isonly required in C++ version 1.2. C++ version 2.0 and greater do not require thekeyword overload but allows it to be used optionally in order to allow the existing bodyof C++ code to be compatible with newer compilers. It is not necessary to use thiskeyword because, when overloading is used in C++, it is generally used in a context inwhich it is obvious that the function name is overloaded.

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

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

Page 40: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 4 - Function––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––4.8

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

Page 41: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 4 - Function––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––4.9

PROGRAMMING EXERCISES

_________________________________________________________________

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.

Page 42: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 5 - Encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––5.1

Chapter 5

ENCAPSULATION

As mentioned in Chapter 1, object oriented programming will seem very unnatural to aprogrammer with a lot of procedural programming experience. This chapter is thebeginning of the definition of object oriented programming, and we will study the topicof encapsulation which is a "divide and conquer" technique. As we stated earlier, thereare a lot of new terms used with object oriented programming. Don't be intimidated bythe 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 thischapter. An encapsulated object is often called an abstract data type and it is whatobject oriented programming is all about. Without encapsulation, which involves theuse of one or more classes, there is no object oriented programming. Of course thereare 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 weproperly encapsulate some code, we actually build an impenetrable wall to protect thecontained code from accidental corruption due to the silly little errors that we are allprone to make. We also tend to isolate errors to small sections of code to make themeasier to find and fix. We will have a lot more to say about the benefits ofencapsulation as we progress through the tutorial.

NO INFORMATION HIDING

_________________________________________________________________

The program named OPEN.CPP is a really stupid ==============program because it does next to nothing, but it OPEN.CPPwill be the beginning point for our discussion ==============of encapsulation, otherwise known as informationhiding.

Information hiding is an important part of object oriented programming and you shouldhave a good grasp of what it is by the time we finish this chapter.

A very simple structure is defined in lines 4 through 6 which contains a single int typevariable within the structure. This is sort of a silly thing to do but it will illustrate the

Page 43: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 5 - Encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––5.2

problem we wish to overcome in this chapter. Three variables are declared in line 10,each of which contains a single int type variable and each of the three variables areavailable anywhere within the main function. Each variable can be assigned,incremented, read, modified, or have any number of operations performed on it. A fewof the operations are illustrated in lines 13 through 21 and should be self explanatory toanyone with a little experience with the C programming language.

An isolated local variable named piggy is declared and used in the same section ofcode to illustrate that there is nothing magic about this code.

Study this simple program carefully because it is the basis for beginning our study ofencapsulation. Be sure to compile and execute this program, then we will go on to thenext example program.

INFORMATION HIDING

_________________________________________________________________

Examine the program named CLAS.CPP for our first ==============example of a program with a little information CLAS.CPPhiding contained in it. ==============

This program is identical to the last one except for the way it does a few of itsoperations. We will take the differences one at a time and explain what is happeninghere. Keep in mind that this is a trivial program and the safeguards built into it are notneeded for such a simple program but are used here to illustrate how to use thesetechniques in a larger much more complicated program.

The first difference is that we have a class instead of a structure beginning in line 4 ofthis program. The only difference between a class and a structure is that a classbegins with a private section whereas a structure has no private section automaticallydefined. 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 andtwo functions, one named set() and the other named get_value(). A more completedefinition of a class is a group of variables and one or more functions that can operateon that data. Stay with us, we will tie this all together in a meaningful and useful wayvery soon.

WHAT IS A PRIVATE SECTION ?

_________________________________________________________________

A private section of a class is a section of data which cannot be accessed outside ofthe class, it is hidden from any outside access. Thus, the variable named data_storewhich is a part of the object (an object will be defined completely later) named dog1declared in line 23 is not available for use anywhere in the main program. It is as if wehave built a "brick wall" around the variables to protect them from accidental corruption

Page 44: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 5 - Encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––5.3

by outside programming influences. It seems a little dumb to declare a variable in themain program that we cannot use, but that is exactly what we did.

Figure 5-1 is a graphical representation of the class with its "brick wall" built around thedata to protect it. You will notice the small peep holes we have opened up to allow theuser to gain access to the functions. The peep holes were opened by declaring thefunctions in the public section of the class.

WHAT IS A PUBLIC SECTION ?

_________________________________________________________________

A new keyword, public, is introduced in line 6 which states that anything following thiskeyword can be accessed from outside of this class. Because the two functions aredefined following the keyword public, they are both public and available for use in thecalling function or any other function that is within the scope of the calling function.This opens two small peepholes in the solid wall of protection. You should keep inmind that the private variable is not available to the calling program. Thus, we can onlyuse the variable by calling one of the two functions defined as a 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 eachfunction will actually do. This is done in lines 11 through 19 where they are eachdefined in the normal way, except that the class name is prepended onto the functionname and separated from it by a double colon. These two function definitions arecalled the implementation of the functions. The class name is required because we canuse the same function name in other classes and the compiler must know with whichclass to associate each function implementation.

One of the key points to be made here is that the private data contained within theclass is available within the implementation of the member functions of the class formodification or reading in the normal manner. You can do anything with the privatedata within the function implementations which are a part of that class, but the privatedata of other classes is hidden and not available within the member functions of thisclass. This is the reason we must prepend the class name to the function names of thisclass when defining them.

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

In C++ we have three scopes of variables, local, file and class. Local variables arelocalized to a single function and file variables are available anywhere in a file followingtheir definition. A variable with class scope is available anywhere within the scope of aclass and nowhere else.

Page 45: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 5 - Encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––5.4

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

MORE NEW TERMINOLOGY

_________________________________________________________________

As with most new technologies, developers seem to delight in making up new namesfor all aspects of their new pet. Object oriented programming is no different, so wemust learn new names for some of our old familiar friends if we are going to learn howto effectively use it. To help you learn this new programming terminology, we will list afew of them here and begin using them in the text to get you used to seeing and usingthem.

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

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

A method is a function contained within the class.You will find the functions used within a class referredto as methods.

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

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

This is a small point but it could be easily overlooked. Lines 7 and 8 of this programare actually the prototypes for the two methods, and is our first example of the use of aprototype within a class. This is the reason we spent so much time on prototypes in thelast chapter. You will notice line 7 which says that the method named set requires oneparameter of type int and returns nothing, hence the return type is void. The methodnamed get_value() however, according to line 8, has no input parameters but returnsan int type value to the caller.

Page 46: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 5 - Encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––5.5

SENDING A MESSAGE

_________________________________________________________________

Following all of the definitions in lines 1 through 19, we finally come to the programwhere we actually use the class. In line 23 we declare three objects of the classone_datum and name the objects dog1, dog2, and dog3. Each object contains a singledata point which we can set through use of one method or read its value through use ofthe other method, but we cannot directly set or read the value of the data pointbecause it is hidden within the "block wall" around the class. In line 26, we send amessage to the object named dog1 instructing it to set its internal value to 12, and eventhough this looks like a function call, it is properly called sending a message to amethod. Remember that the object named dog1 has a method associated with it calledset() 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 astructure. You mention the name of the object with a dot connecting it to the name ofthe method. In a similar manner, we send a message to each of the other two objectsdog2 and dog3 to set their values to those indicated.

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

The other method defined for each object is used in lines 34 through 36 to illustratehow it can be used. In each case, another message is sent to each object and thereturned 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 exampleprogram that illustrates that a normal variable can be intermixed with the objects andused in the normal manner. The use of this variable should pose no problem to you, soafter you understand the program, be sure to compile and execute it. It would be agood exercise for you to remove the comments from lines 31 and 32 to see what kindof error message your compiler issues.

This program illustrates information hiding but it will not be clear to you that it reallydoes anything worthwhile until we study the next two programs. Be sure to compile andexecute this program before continuing on to the next example program.

Page 47: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 5 - Encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––5.6

A PROGRAM WITH PROBLEMS

_________________________________________________________________

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

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

Based on your experience with ANSI-C, you should have no problem understandingexactly what this program is doing, but you may be a bit confused at the meaning of theresult found in line 38 where we multiply the height of the square with the width of thebox. This is perfectly legal to do in ANSI-C or C++, but the result has no earthlymeaning because the data are for two different entities. Likewise, the result calculatedin line 40 is even sillier because the product of the height of the square and the depthof the flagpole has absolutely no meaning in any real world physical system we canthink up.

Wouldn't it be neat if we had a way to prevent such stupid things from happening in alarge production program. If we had a good program that defined all of the things wecan do with a square and another program that defined everything we could do with apole, and if the data could be kept mutually exclusive, we could prevent these sillythings from happening.

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

OBJECTS PROTECT DATA

_________________________________________________________________

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

In this program the rectangle is changed to a class with the same two variables whichare now private, and two methods to handle the private data. One method is used toinitialize the values of the objects created and the other method to return the area ofthe object. The two methods are defined in lines 12 through 21 in the mannerdescribed earlier in this chapter. The pole is left as a structure to illustrate that the twocan be used together and that C++ is truly an extension of ANSI-C.

Page 48: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 5 - Encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––5.7

In line 33 we declare two objects, once again named box and square, but this time wecannot assign values directly to their individual components because they are privateelements of the class. Lines 36 through 38 are commented out for that reason and themessages are sent to the objects in lines 40 and 41 to tell them to initialize themselvesto the values input as parameters. The flag_pole is initialized in the same manner as inthe previous program. Using the class in this way prevents us from making the sillycalculations we did in the last program. The compiler is now being used to prevent theerroneous calculations. The end result is that the stupid calculations we did in the lastprogram are not possible in this program so lines 50 through 53 have been commentedout. Once again, it is difficult to see the utility of this in such a simple program. In alarge program, using the compiler to enforce the rules can pay off in a big way.

Figure 5-2 is a graphical illustration of the two objects available for use within the callingprogram. Even though the square and the box are both objects of class rectangle, theirprivate data is hidden from each other such that neither can purposefully or accidentallychange the others data.

This is the abstract data type mentioned earlier in this chapter, a model with anallowable set of variables for data storage and a set of allowable operations that can beperformed on that stored data. The only operations that can be performed on the dataare those defined by the methods which prevents many kinds of erroneous or sillyoperations. 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 thedivide and conquer technique in which an object is separated from the rest of the codeand carefully developed in complete isolation from it. Only then is it integrated into therest of the code with a few very simple interfaces.

HAVE YOU EVER USED THIS TECHNIQUE BEFORE ?

_________________________________________________________________

A good example of the use of this technique is in the file commands you have beenusing with ANSI-C. The data in the file is only available through the predefinedfunctions provided by your compiler writer. You have no direct access to the actualdata because it is impossible for you to address the actual data stored on the disk. Thedata is therefore private data, as far as you are concerned, but the available functionsare very much like methods in C++. There are two aspects of this technique that reallycount when you are developing software. First, you can get all of the data you reallyneed from the file system because the interface is complete, but secondly, you cannotget any data that you do not need. You are prevented from getting into the filehandling system and accidentally corrupting some data stored within it. You are alsoprevented from using the wrong data because the functions available demand a serialaccess to the data.

Another example is in the monitor and keyboard handling routines. You are preventedfrom getting into the workings of them and corrupting them accidentally, or on purposeif you have such a bent, but once again, you are provided with all of the data interfacesthat you really need.

Page 49: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 5 - Encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––5.8

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 flagpoleprogram was stored on your hard disk as the height of the flagpole, nor would you wishto use the cursor position as the flagpole thickness or color. All code for the flagpole isdeveloped alone, and only when it is finished, is it available for external use. Whenusing 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 athing when you are working at midnight to try to meet a schedule. Once again, this isreferred to as information hiding and is one of the primary advantages of objectoriented programming over procedural techniques.

Based on the discussion given above you can see that object oriented programming isnot really new, since it has been used in a small measure for as long as computershave been popular. The newest development, however, is in allowing the programmerto partition his programs in such a way that he too can practice information hiding andreduce the debugging time.

WHAT DOES THIS COST ?

_________________________________________________________________

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

This is obviously such a small program that it is silly to try to see any gain with thistechnique. In a real project however, it could be a great savings if one persondeveloped all of the details of the rectangle, programmed it, and made it available toyou to simply use. This is exactly what has been done for you if you consider the videomonitor an object. There is a complete set of preprogrammed and debugged routinesyou can use to make the monitor do anything you wish it to do, all you have to do isstudy the interface to the routines and use them, expecting them to work. As wementioned earlier, it is impossible for you to multiply the size of your monitor screen bythe depth of the flag pole because that information is not available to you to use in acorruptible way.

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

Page 50: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 5 - Encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––5.9

CONSTRUCTORS AND DESTRUCTORS

_________________________________________________________________

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

This example program is identical to the last example except that a constructor hasbeen added as well as a destructor. The constructor always has the same name as theclass itself and is declared in line 8, then defined in lines 14 through 18. Theconstructor is called automatically by the C++ system when the object is declared andcan therefore be of great help in preventing the use of an uninitialized variable. Whenthe object named box is declared in line 46, the constructor is called automatically bythe system. The constructor sets the values of height and width each to 6 in the objectnamed box. This is printed out for reference in lines 49 and 50. Likewise, when thesquare is declared in line 46, the values of the height and the width of the square areeach 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 bothare named rectangle. The constructor cannot have a return type associated with itsince it is not permitted to have a user defined return type. It actually has a predefinedreturn type, a pointer to the object itself, but we will not be concerned about this untilmuch later in this tutorial. Even though both objects are assigned values by theconstructor, they are initialized in lines 58 and 59 to new values and processingcontinues. Since we have a constructor that does the initialization, we should probablyrename the method named initialize() something else but it illustrates the conceptinvolved here.

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

A destructor is declared in line 11 and defined in lines 31 through 35. In this case thedestructor only assigns zeros to the variables prior to their being deallocated, sonothing is really accomplished. The destructor is only included for illustration of how itis used. If some blocks of memory were dynamically allocated within an object, adestructor should be used to deallocate them prior to losing the pointers to them. Thiswould 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 tothe main program, otherwise known as globally, the constructor will actually beexecuted prior to the execution of the main program. In like manner, if a destructor isdefined for such a variable, it will execute following the completion of execution of themain program. This will not adversely affect your programs, but it is interesting to makenote of.

Page 51: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 5 - Encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––5.10

OBJECT PACKAGING

_________________________________________________________________

Examine the file named BOXES1.CPP for an example ==============of how not to package an object for universal BOXES1.CPPuse. ==============

This packaging is actually fine for a very small program but is meant to illustrate to youhow to split your program up into smaller more manageable files when you aredeveloping a large program or when you are part of a team developing a large system.The next three example programs in this chapter will illustrate the proper method ofpackaging a class.

This program is very similar to the last one with the pole structure dropped and theclass named box. The class is defined in lines 4 through 12, the implementation of theclass is given in lines 15 through 34, and the use of the class is given in lines 37through 50. With the explanation we gave about the last program, the diligent studentshould have no problem understanding this program in detail.

INLINE IMPLEMENTATION

_________________________________________________________________

The method in line 10 contains the implementation for the method as a part of thedeclaration because it is very simple, and because it introduces another new topicwhich you will use often in C++ programming. When the implementation is included inthe declaration, it will be assembled inline wherever this function is called leading tomuch faster code. This is because there is no overhead to accomplish the call to themethod. In some cases this will lead to code that is both smaller and faster. This is yetanother illustration of the efficiency built into the C++ programming language.

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

THE CLASS HEADER FILE

_________________________________________________________________

If you examine BOX.H carefully, you will see ===============that it is only the class definition. BOX.H ===============

No details are given of how the various methods are implemented except of course forthe inline method named get_area(). This gives the complete definition of how to usethe class with no implementation details. You would be advised to keep a hardcopy of

Page 52: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 5 - Encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––5.11

this file available as we study the next two files. You will notice that it contains lines 4through 12 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

_________________________________________________________________

Examine the file named BOX.CPP for the ===============implementation of the methods declared in the BOX.CPPclass header file. ===============

Notice that the class header file is included into this file in line 2 which contains all ofthe prototypes for its methods. The code from lines 15 through 34 of BOXES1.CPP iscontained in this file which is the implementation of the methods declared in the classnamed box.

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

The separation of the definition and the implementation is a major step forward insoftware engineering. The definition file is all the user needs in order to use this classeffectively in a program. He needs no knowledge of the actual implementation of themethods. If he had the implementation available, he may study the code and find a trickhe could use to make the overall program slightly more efficient, but this would lead tononportable software and possible bugs later if the implementor changed theimplementation without changing the interface. The purpose of object orientedprogramming is to hide the implementation in such a way that the implementation cannot 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 nextexample program.

Page 53: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 5 - Encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––5.12

USING THE BOX OBJECT

_________________________________________________________________

Examine the file named BOXES2.CPP and you will ================find that the class we defined previously is BOXES2.CPPused within this file. ================

In fact, these last three programs taken together are identical to the program namedBOXES1.CPP studied earlier.

The BOX.H file is included here, in line 3, since the definition of the box class is neededto declare three objects and use their methods. You should have no trouble seeingthat 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 callingfunctions and changing the terminology a little to say we are sending messages. Thereis an inherent difference in the two operations. Since the data for each object is tightlybound up in the object, there is no way to get to the data except through the methodsand we send a message to the object telling it to perform some operation based on itsinternally stored data. However, whenever we call a function, we take along the data forit to work with as parameters since it doesn't contain its own data.

Be sure to compile and execute this program, but when you come to the link step, youwill be required to link this program along with the result of the compilation when youcompiled the class named box. The file is probably named BOX.OBJ that must belinked with this file. You may need to consult the documentation for your C++ compilerto learn how to do this. Even if it seems to be a lot of trouble to learn how to linkseveral files together, it will be worth your time to do so now because we will be linkingseveral more multifile C++ programs in the remainder of this tutorial.

If you are using Turbo C++, this is your first opportunity to use a project file. If you areusing Zortech C++ or one of the other implementations, you can use the "make" facilityincluded with your compiler. Regardless of which C++ compiler you are using, it wouldpay you to stop and learn how to use the multifile technique provided with your compilerbecause you will need to use it several times before the end of this tutorial. The natureof C++ tends to drive the programmer to use many files for a given programmingproject and you should develop the habit early.

INFORMATION HIDING

_________________________________________________________________

The last three example programs illustrate a method of information hiding that can havea significant impact on the quality of software developed for a large project. Since theonly information the user of the class really needs is the class header, that is all heneeds to be given. The details of implementation can be kept hidden from him toprevent him from studying the details and possibly using a quirk of programming to

Page 54: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 5 - Encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––5.13

write some rather obtuse code. Since he doesn't know exactly what the implementordid, he must follow only the definition given in the header file. This can have asignificant impact on a large project. As mentioned earlier, accidental corruption ofdata is prevented also.

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

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

ABSTRACT DATA TYPES

_________________________________________________________________

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

The methods, on the other hand, are coupled to the outside world through theinterface, but there are a limited number of contacts with the outside world andtherefore a weak coupling with the outside. The object is therefore said to be looselycoupled 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 maintenancemay be the greatest benefit of object oriented programming.

It may bother you that even though the programmer may not use the private variablesdirectly outside of the class, they are in plain sight and he can see what they are andcan probably make a good guess at exactly how the class is implemented. Thevariables could have been hidden completely out of sight in another file, but becausethe designers of C++ wished to make the execution of the completed application asefficient as possible, the variables were left in the class definition where they can beseen but not used.

Page 55: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 5 - Encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––5.14

FRIEND FUNCTIONS

_________________________________________________________________

A function outside of a class can be defined to be a friend function by the class whichgives the friend free access to the private members of the class. This in effect, opens asmall hole in the protective shield of the class, so it should be used very carefully andsparingly. There are cases where it helps to make a program much moreunderstandable and allows controlled access to the data. Friend functions will beillustrated in some of the example programs later in this tutorial. It is mentioned herefor 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 friendstatus if needed in a program. Neither a constructor nor a destructor can be a friendfunction.

THE struct IN C++

_________________________________________________________________

The struct is still useable in C++ and operates just like it does in ANSI-C with oneaddition. You can include methods in a structure that operate on data in the samemanner as in a class, but all methods and data are automatically defaulted to be publicin a structure. Of course you can make any of the data or methods private by defininga private section within the structure. The structure should be used only for constructsthat are truly structures. If you are building even the simplest objects, you are advisedto use classes to define them.

A VERY PRACTICAL CLASS

_________________________________________________________________

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

Examine the file named DATE.H which is the ==============header file for the date class. This file is so DATE.Hwell 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 problemunderstanding this class. The first thing that is new to you is the reserved wordprotected which is used in line 12. We will define this word in a couple of chapters.

Page 56: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 5 - Encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––5.15

Until then, pretend that it means the same thing as private and you will be close enoughfor this present example. The code in lines 8 and 9 along with line 55 will be explainedshortly. For the present time, simply pretend those lines of code are not there. Alsothe keyword static as used in lines 16 and 17 will be explained later.

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

The file named DATE.CPP is the implementation ==============for the date class and once again, there is DATE.CPPnothing unusual or difficult about this code. ==============

It uses very simple logic to store and format the date in a usable manner. You shouldstudy this code until you understand it completely before going on to the next examplewhich will use the date class in a main program.

The very simple program named USEDATE.CPP is a ===============main program that uses the date class to list USEDATE.CPPthe current date and another date on the ===============monitor.

Once again, you should have no problem understanding this program so nothing morewill be said about it.

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

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

Page 57: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 5 - Encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––5.16

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.

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.

If this is carefully planned, it could be useful to you someday.

Page 58: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 6 - More encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––6.1

Chapter 6

MORE ENCAPSULATION

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

In order to have a systematic study, we will use the program named BOXES1.CPP fromthe last chapter as a starting point and we will add a few new constructs to it for eachexample program. You will recall that it was a very simple program with the classdefinition, the class implementation, and the main calling program all in one file. Thiswas selected as a starting point because we will eventually make changes to all partsof the program and it will be convenient to have it all in a single file for illustrativepurposes. It must be kept in mind however that the proper way to use these constructsis to separate them into the three files as was illustrated in BOX.H, BOX.CPP, andBOXES2.CPP in the last chapter. This allows the implementor of box to supply theuser with only the interface, namely BOX.H. Not giving him the implementation filenamed 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 threeseparate files, and it is sort of silly. The last chapter of this tutorial will illustrate aprogram large enough to require dividing the program up into many separate files.

AN ARRAY OF OBJECTS

_________________________________________________________________

Examine the file named OBJARRAY.CPP for our ================first example of an array of objects. OBJARRAY.CPP ================

This file is nearly identical to the file named BOX1.CPP until we come to line 44 wherean array of 4 boxes are declared.

Recalling the operation of the constructor you will remember that each of the four boxobjects will be initialized to the values defined within the constructor since each box willgo through the constructor as they are declared. In order to declare an array of objects,a constructor for that object must not require any parameters. (We have not yetillustrated 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 allelements of an array of objects to the same value. We will see the results of executingthe constructor when we compile and execute the file later.

Page 59: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 6 - More encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––6.2

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

Another fine point should be pointed out. The integer variable named index is declaredin line 49 and is still available for use in line 56 since we have not yet left the enclosingblock which begins in line 43 and extends to line 65.

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 7, it is an externalvariable and only one copy of this variable will ever exist. All seven objects of this classshare 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 isnot defined. A declaration says the variable will exist and gives it a name, but thedefinition actually defines a place to store it somewhere in the computers memoryspace. By definition, a static variable can be declared in a class header but it cannotbe defined there, so it is defined somewhere outside of the header, usually in theimplementation file. In this case it is defined in line 16 and can then be usedthroughout the class.

Line 23 of the constructor sets the single global variable to 1 each time an object isdeclared. Only one assignment is necessary so the other six are actually wasted code.To illustrate that there is only one variable shared by all objects of this class, themethod to read its value also increments it. Each time it is read in lines 60 through 64,it is incremented and the result of the execution proves that there is only a singlevariable shared by all objects of this class. You will also note that the method namedget_extra() is defined within the class declaration so it will be assembled into the finalprogram as inline code.

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

Page 60: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 6 - More encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––6.3

A STRING WITHIN AN OBJECT

_________________________________________________________________

Examine the program named OBJSTRNG.CPP for our ================first example of an object with an embedded OBJSTRNG.CPPstring. ================

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 7 contains a pointer to a string named line_of_text. Theconstructor contains an input parameter which is a pointer to a string which will becopied to the string named line_of_text within the constructor. We could have definedthe variable line_of_text as an actual array in the class, then used strcpy() to copy thestring into the object and everything would have worked the same, but we will leavethat as an exercise for you at the end of this chapter. It should be pointed out that weare not limited to passing a single parameter to a constructor. Any number ofparameters can be passed, as will be illustrated later.

You will notice that when the three boxes are declared this time, we supply a stringconstant as an actual parameter with each declaration which is used by the constructorto assign the string pointer some data to point to. When we call get_area() in lines 48through 53, we get the message displayed and the area returned. It would be prudentto put these operations in separate methods since there is no apparent connectionbetween printing the message and calculating the area, but it was written this way toillustrate that it can be done. What this really says is that it is possible to have amethod 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 studiedDEFAULT.CPP, the order of evaluation is sort of funny, so we broke each line into twolines.

After you understand this program, compile and execute it.

AN OBJECT WITH AN INTERNAL POINTER

_________________________________________________________________

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

In line 7 we declare a pointer to an integer variable, but it is only a pointer, there is nostorage associated with it. The constructor therefore allocates an integer type variableon the heap for use with this pointer in line 21. It should be clear to you that the threeobjects created in line 45 each contain a pointer which points into the heap to threedifferent locations. Each object has its own dynamically allocated variable for its ownprivate use. Moreover each has a value of 112 stored in its dynamically allocated data

Page 61: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 6 - More encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––6.4

because line 22 stores that value in each of the three locations, once for each call tothe constructor.

In such a small program, there is no chance that we will exhaust the heap, so no test ismade for unavailable memory. In a real production program, it would be expedient totest that the value of the returned pointer is not NULL to assure that the data actuallydid get allocated.

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

The three areas are displayed followed by the three stored values in the dynamicallyallocated variables, and we finally have a program that requires a destructor in order tobe completely proper. If we simply leave the scope of the objects as we do when weleave the main program, we will leave the three dynamically allocated variables on theheap with nothing pointing to them. They will be inaccessible and will thereforerepresent wasted storage on the heap. For that reason, the destructor is used to deletethe variable which the pointer named point is referencing as each object goes out ofexistence. In this case, lines 37 and 38 assign values to variables that will beautomatically deleted. Even though these lines of code really do no good, they are legalstatements.

Actually, in this particular case, the variables will be automatically reclaimed when wereturn to the operating system because all program cleanup is done for us at that time.If this were a function that was called by another function however, the heap spacewould be wasted. This is an illustration of good programming practice, that of cleaningup after yourself when you no longer need some dynamically allocated variables.

One other construct should be mentioned once again, that of the inline methodimplementations in line 11 and 12. As we mentioned in chapter 5 and repeated earlierin this chapter, inline functions can be used where speed is of the utmost in importancesince the code is assembled inline rather than by actually making a method call. Sincethe code is defined as part of the declaration, the system will assemble it inline, and aseparate implementation for these methods is not needed. If the inline code is tooinvolved, the compiler is allowed to ignore the inline request and will actually assembleit as a separate method, but it will do it invisibly to you and will probably not even tellyou about it.

Remember that we are interested in using information hiding and inline code preventshiding of the implementation, putting it out in full view. Many times you will be moreinterested in speeding up a program than you are in hiding a trivial implementation.Since most inline methods are trivial, feel free to use the inline code construct.

Be sure to compile and execute this program.

Page 62: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 6 - More encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––6.5

A DYNAMICALLY ALLOCATED OBJECT

_________________________________________________________________

Examine the file named OBJDYNAM.CPP for our ================first look at a dynamically allocated object. OBJDYNAM.CPP ================

This is not any different than any other dynamically allocated object, but an example isalways helpful.

In line 39 we declare a pointer to an object of type box and since it is only a pointer withnothing to point to, we dynamically allocate an object for it in line 44, with the objectbeing created on the heap just like any other dynamically allocated variable. When theobject is created in line 44, the constructor is called automatically to assign values tothe two internal storage variables. Note that the constructor is not called when thepointer is declared since there is nothing to initialize. It is called when the object isallocated.

Reference to the components of the object are handled in much the same way thatstructure references are made, through use of the pointer operator as illustrated in lines50 through 52. Of course you can use the pointer dereferencing method without thearrow such as (*point).set(12, 12); as a replacement for line 51 but the arrow notation ismuch more universal and should be used. Finally, the object is deleted in line 54 andthe program terminates. If there were a destructor for this class, it would be called aspart 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 differentfrom the use of structures. Be sure to compile and execute this program after you havestudied it thoroughly.

AN OBJECT WITH A POINTER TO ANOTHER OBJECT

_________________________________________________________________

The program named OBJLIST.CPP contains an object ===============with an internal reference to another object of OBJLIST.CPPits own class. ===============

This is the standard structure used for a singly linked list and we will keep the use of itvery simple in this program.

The constructor contains the statement in line 21 which assigns the pointer the value ofNULL to initialize the pointer. This is a good idea for all of your programming, don'tallow any pointer to point off into space, but initialize all pointers to something. Byassigning the pointer within the constructor, you guarantee that every object of thisclass will automatically have its pointer initialized. It will be impossible to overlook theassignment of one of these pointers.

Page 63: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 6 - More encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––6.6

Two additional methods are declared in lines 12 and 13 with the one in line 13 having aconstruct we have not yet mentioned in this tutorial. This method returns a pointer toan object of the box class. As you are aware, you can return a pointer to a struct instandard C, and this is a parallel construct in C++. The implementation in lines 48through 51 returns the pointer stored within the object. We will see how this is usedwhen we get to the actual program.

An extra pointer named box_pointer is declared in the main program for use later and inline 66 we make the embedded pointer within the small box point to the medium box,and in line 67 we make the embedded pointer within the medium box point to the largebox. We have effectively generated a linked list with three elements. In line 69 wemake the extra pointer point to the small box. Continuing in line 70 we use it to refer tothe small box and update it to the value contained in the small box which is the addressof the medium box. We have therefore traversed from one element of the list toanother by sending a message to one of the objects. If line 70 were repeated exactlyas shown, it would cause the extra pointer to refer to the large box, and we would havetraversed the entire linked list which is only composed of three elements.

ANOTHER NEW KEYWORD this

_________________________________________________________________

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

class_name *this;

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

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

Page 64: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 6 - More encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––6.7

A LINKED LIST OF OBJECTS

_________________________________________________________________

The next example program in this chapter is ===============named OBJLINK.CPP and is a complete example of OBJLINK.CPPa 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 mainprogram. You will recall that in the last program the only way we had to set or use theembedded pointer was through use of the two methods named point_at_next() andget_next() which are listed in lines 40 through 51 of the present program. We will usethese to build up our linked list then traverse and print the list. Finally, we will delete theentire list to free the space on the heap.

In lines 56 to 58 we declare three pointers for use in the program. The pointer namedstart will always point to the beginning of the list, but temp will move down through thelist as we create it. The pointer named box_pointer will be used for the creation of eachobject. We execute the loop in lines 61 through 69 to generate the list where line 62dynamically allocates a new object of the box class and line 63 fills it with nonsensedata for illustration. If this is the first element in the list, the start pointer is set to point tothis element, but if elements already exist, the last element in the list is assigned topoint to the new element. In either case, the temp pointer is assigned to point to thelast element of the list, in preparation for adding another element if there is anotherelement to be added.

In line 72, the pointer named temp is pointed to the first element and it is used toincrement its way through the list by updating itself in line 75 during each pass throughthe loop. When temp has the value of NULL, which it gets from the last element of thelist, we are finished traversing the list.

Finally, we delete the entire list by starting at the beginning and deleting one elementeach time we pass through the loop in lines 79 through 84.

A careful study of the program will reveal that it does indeed generate a linked list often elements, each element being an object of class box. The length of this list islimited by the practicality of how large a list we desire to print out, but it could belengthened to many thousands of these simple elements provided you have enoughmemory available to store them all.

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

Page 65: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 6 - More encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––6.8

NESTING OBJECTS

_________________________________________________________________

Examine the program named NESTING.CPP for an =================example of nesting classes which results in NESTING.CPPnested objects. =================

A nested object could be illustrated with your computer in a rather simple manner. Thecomputer itself is composed of many items which work together but work entirelydifferently, such as a keyboard, a disk drive, and a power supply. The computer iscomposed of these very dissimilar items and it is desireable to discuss the keyboardseparately from the disk drive because they are so different. A computer class couldbe composed of several objects that are dissimilar by nesting the dissimilar classeswithin the computer class.

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

This example program contains a class named box which contains an object of anotherclass embedded within it in line 16, the mail_info class. This object is available for useonly within the class implementation of box because that is where it is defined. Themain program has objects of class box defined but no objects of class mail_info, so themail_info class cannot be referred to in the main program. In this case, the mail_infoclass object is meant to be used internally to the box class and one example is given inline 21 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 ofhow they can be called.

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

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

Page 66: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 6 - More encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––6.9

OPERATOR OVERLOADING

_________________________________________________________________

The example file named OPOVERLD.CPP contains ================examples of overloading operators. OPOVERLD.CPP ================

This allows you to define a class of objects and redefine the use of the normaloperators. The end result is that objects of the new class can be used in as natural amanner as the predefined types. In fact, they seem to be a part of the language ratherthan your own add-on.

In this case we overload the + operator and the * operator, with the declarations in lines10 through 12, and the definitions in lines 16 through 40. The methods are declared asfriend functions so we can use the double parameter functions as listed. If we did notuse the friend construct, the function would be a part of one of the objects and thatobject would be the object to which the message was sent. Including the friendconstruct allows us to separate this method from the object and call the method withinfix notation. Using this technique, it can be written as object1 + object2 rather thanobject1.operator+(object2). Also, without the friend construct we could not use anoverloading with an int type variable for the first parameter because we can not send amessage to an integer type variable such as int.operator+(object). Two of the threeoperator overloadings use an int for the first parameter so it is necessary to declarethem as friend functions.

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

The header in line 16 illustrates the first overloading where the + operator is overloadedby giving the return type followed by the keyword operator and the operator we wish tooverload. The two formal parameters and their types are then listed in the parenthesesand the normal function operations are given in the implementation of the function inlines 18 through 21. The observant student will notice that the implementation of thefriend functions are not actually a part of the class because the class name is notprepended onto the method name in line 16. There is nothing unusual about thisimplementation, it should be easily understood by you at this point. For purposes ofillustration, some silly mathematics are performed in the method implementation, butany desired operations can be done.

The biggest difference occurs in line 56 where this method is called by using the infixnotation instead of the usual message sending format. Since the variables small andmedium 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+ methodwe have just discussed. The operations within the method implementation can beanything we need them to be, and they are usually much more meaningful than the sillymath included here.

In line 58 we ask the system to add an int type constant to an object of class box, sothe system finds the other overloading of the + operator beginning in line 25 to performthis operation. Also in line 60 we ask the system to use the * operator to do something

Page 67: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 6 - More encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––6.10

to an int constant and an object of class box, which it satisfies by finding the method inlines 34 through 40. Note that it would be illegal to attempt to use the * operator theother way around, namely large * 4 since we did not define a method to use the twotypes in that order. Another overloading could be given with reversed types, and wecould use the reverse order in a program.

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

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

OPERATOR OVERLOADING CAVEATS

_________________________________________________________________

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

The logical and (&&) and the logical or (||) operators can be overloaded for the classesyou define, but they will not operate as short circuit operators. All members of thelogical construction will be evaluated with no regard concerning the outcome. Ofcourse the normal predefined logical operators will continue to operate as short circuitoperators as expected, but not the overloaded ones.

If the increment (++) or decrement (--) operators are overloaded, the system has noway of telling whether the operators are used as preincrement or postincrement (orpredecrement or postdecrement) operators. Which method is used is implementationdependent, 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 nextexample program.

Page 68: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 6 - More encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––6.11

FUNCTION OVERLOADING IN A CLASS

_________________________________________________________________

Examine the program named FUNCOVER.CPP for an ================example of function name overloading within a FUNCOVER.CPPclass. ================

In this program the constructor is overloaded as well as one of the methods to illustratewhat can be done.

This file illustrates some of the uses of overloaded names and a few of the rules fortheir use. You will recall that the function selected is based on the number and types ofthe formal parameters only. The type of the return value is not significant in overloadresolution.

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

In the case of the other overloaded methods, the number and type of parameters isclearly used to select the proper method. You will notice that one method uses a singleinteger and another uses a single float type variable, but the system is able to selectthe correct one. As many overloadings as desired can be used provided that all of theparameter 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'tbeen the least confused over it. It is the cout operator which operates as anoverloaded function since the way it outputs data is a function of the type of its inputvariable or the field we ask it to display. Many programming languages haveoverloaded 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 forANSI-C separate compilation. As expected, separately compiled files can be linkedtogether. However, since classes are used to define objects, the nature of C++separate compilation is considerably different from that used for ANSI-C. This isbecause the classes used to create the objects are not considered as externalvariables, but as

Page 69: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 6 - More encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––6.12

included classes. This makes the overall program look different from a pure ANSI-Cprogram. Your programs will take on a different appearance as you gain experience inC++.

ANOTHER PRACTICAL EXAMPLE

_________________________________________________________________

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

In the last chapter we studied the date class ================and in this chapter we will study a simple time TIME.Hclass. ================

You should begin by studying the file named TIME.H which will look very similar to thedate class header. The only major difference in this class from the date class is theoverloaded constructors and methods. The program is a very practical example thatillustrates very graphically that many constructor overloadings are possible.

The implementation for the time class is given ================in the file named TIME.CPP. TIME.CPP ================

Once again, the code is very simple and you should have no problem understandingthis example in its entirety. It should be pointed out that three of the four overloadingsactually call the fourth so that the code did not have to be repeated four times. This isa perfectly good coding practice and illustrates that other member functions can becalled from within the implementation.

The example program named USETIME.CPP is a very ===============simple program that uses the time class in a USETIME.CPPvery rudimentary way as an illustration for you. ===============

You should be able to understand this program in a very short time. It will be to youradvantage to completely understand the practical example programs given at the endof the last chapter and the end of this chapter. As mentioned above, we will use thetime class and the date class as the basis for both single and multiple inheritance in thenext three chapters.

Page 70: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 6 - More encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––6.13

WHAT SHOULD BE THE NEXT STEP ?

_________________________________________________________________

At this point you have learned enough C++ to write meaningful programs and it wouldbe 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 wouldbe required if you are learning a completely new language. You have learned enoughto study and completely understand the example program given in chapter 12, theFlyaway adventure game. You should begin studying this program now.

One of your biggest problems is learning to think in terms of object orientedprogramming. It is not a trivial problem if you have been programming in procedurallanguages 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. Yourfirst project should use only a small number of objects and the remainder of code canbe completed in standard procedural programming techniques. As you gainexperience, you will write more of the code for any given project using classes andobjects 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 inthe tutorial, you can continue on to the next few chapters which will discuss inheritanceand virtual functions.

Page 71: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 6 - More encapsulation––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––6.14

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 61 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 74 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. You should also add a test to assure that the memory did not become exhausted after each dynamic allocation.

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.

Page 72: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 7 - Inheritance––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––7.1

Chapter 7

INHERITANCE

One reason to use inheritance is that it allows you to reuse code from a previousproject but gives you the flexibility to slightly modify it if the old code doesn't do exactlywhat you need for the new project. It doesn't make sense to start every new projectfrom scratch since some code will certainly be repeated in several programs and youshould strive to build on what you did previously. Moreover, it is easy to make an error ifwe try to modify the original class, but we are less likely to make an error if we leave theoriginal alone and only add to it. Another reason for using inheritance is if the projectrequires 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 itinto a program. A better illustration of why you would use inheritance will be given inlater chapters where we will discuss some practical applications of object orientedprogramming.

The principle of inheritance is available with several modern programming languagesand is handled slightly differently with each. C++ allows you to inherit all or part of themembers and methods of a class, modify some, and add new ones not available in theparent 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

_________________________________________________________________

Examine the file named VEHICLE.H for a simple =================class which we will use to begin our study of VEHICLE.Hinheritance in this chapter. =================

There is nothing unusual about this class header, it has been kept very simple. Itconsists of four simple methods which can be used to manipulate data pertaining to ourvehicle. What each method does is not especially important at this time. We willeventually refer to this as a base class or parent class, but for the time being, we willsimply use it like any other class to show that it is indeed identical to the classesalready studied. Note that we will explain the added keyword protected shortly.

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

Page 73: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 7 - Inheritance––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––7.2

THE IMPLEMENTATION FOR VEHICLE

_________________________________________________________________

Examine the file named VEHICLE.CPP and you will ===============find that it is the implementation of the VEHICLE.CPPvehicle class. ===============

The initialize() method assigns the values input as parameters to the wheels and weightvariables. We have methods to return the number of wheels and the weight, andfinally, 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, butat this point, we are more interested in learning how to set up the interface to theclasses, 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 thistime in preparation for the next example program, but you cannot execute it becausethere is no entry point.

USING THE VEHICLE CLASS

_________________________________________________________________

The file named TRANSPRT.CPP uses the vehicle ================class in exactly the same manner as we TRANSPRT.CPPillustrated in the last chapter. ================

This should be an indication to you that the vehicle class is truly nothing more than anormal class as defined in C++. We will make it a little special, however, by using itunmodified 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 declaresfour objects of the vehicle class, initializes them, and prints out a few of the data pointsto illustrate that the vehicle class can be used as a simple class because it is a simpleclass. We are referring to it as a simple class as opposed to calling it a base class orderived 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.

Page 74: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 7 - Inheritance––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––7.3

OUR FIRST DERIVED CLASS

_________________________________________________________________

Examine the file named CAR.H for our first example ==============of the use of a derived class or child class. CAR.H ==============

The vehicle class is inherited due to the ": public vehicle" added to line 4. This derivedclass named car is composed of all of the information included in the base classvehicle, and all of its own additional information. Even though we did nothing to theclass named vehicle, we made it into a base class because of the way we are using ithere. To go a step further, even though it will be used as a base class in an exampleprogram later in this chapter, there is no reason it cannot continue to be used as asimple class in the previous example program. In fact, it can be used as a single classand a base class in the same program. The question of whether it is a simple class ora base class is answered by the way it is used.

A discussion of terminology is needed here. When discussing object orientedprogramming in general, a class that inherits another is often called a derived class or achild class, but the most proper term as defined for C++ is a derived class. Since theseterms are very descriptive, and most writers tend to use the terms interchangeably, wewill also use these terms in this tutorial. Likewise the proper C++ terminology for theinherited class is to call it a base class, but parent class and super class are sometimesused.

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 classnamed C++, then we could use the base class to define Pascal, Ada, C++, or any otherprogramming 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, thederived class named C++ could define the use of classes, but it could not be used todescribe the other languages because it is too narrow. A base class tends to be moregeneral, and a derived class is more specific.

In this case, the vehicle base class can be used to declare objects that representtrucks, cars, bicycles, or any number of other vehicles you can think up. The classnamed car however can only be used to declare an object that is of type car becausewe have limited the kinds of data that can be intelligently used with it. The car class istherefore more restrictive and specific than the vehicle class. The vehicle class is moregeneral than the car class.

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

Page 75: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 7 - Inheritance––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––7.4

HOW DO WE DECLARE A DERIVED CLASS ?

_________________________________________________________________

Enough generalities about classes, let's get down to the specifics. A derived class isdefined by including the header file for the base class as is done in line 2, then thename of the base class is given following the name of the derived class separated by acolon as is illustrated in line 4. Ignore the keyword public immediately following thecolon in this line. It is optional and we will study it in detail in the next chapter. Allobjects declared as being of class car therefore are composed of the two variablesfrom the class vehicle because they inherit those variables, and the single variabledeclared in the class car named passenger_load.

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

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

THE CAR CLASS IMPLEMENTATION

_________________________________________________________________

Examine the file named CAR.CPP which is the ===============implementation file for the car class. CAR.CPP ===============

The first thing you should notice is that this file has no indication of the fact that it is aderived class of any other file, that can only be determined by inspecting the header filefor the class. Since we can't tell if it is a derived class or not, it is written in exactly thesame way as any other class implementation file.

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

Page 76: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 7 - Inheritance––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––7.5

ANOTHER DERIVED CLASS

_________________________________________________________________

Examine the file named TRUCK.H for an example of ===============another class that uses the vehicle class and TRUCK.Hadds to it. ===============

Of course, it adds different things to it because it will specialize in those things thatpertain to trucks. In fact it adds two more variables and three methods. Once again,ignore the keyword public following the colon in line 7 for a few minutes and we willcover it in detail in the next chapter of this tutorial. See figure 7-2.

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

Note that both the car and the truck classes have methods named passengers() butthis causes no problems and is perfectly acceptable. If classes are related in someway, and they certainly are if they are both derived classes of a common base class,you would expect them to be doing somewhat similar things. In this situation there is agood possibility that a method name would be repeated in both child classes.

THE TRUCK IMPLEMENTATION

_________________________________________________________________

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

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

USING ALL THREE CLASSES

_________________________________________________________________

Examine the example program named ALLVEHIC.CPP ================for an example that uses all three of the ALLVEHIC.CPPclasses we have been discussing in this chapter. ================

It uses the parent class vehicle to declare objects and also uses the two child classes todeclare objects. This was done to illustrate that all three classes can be used in asingle program.

Page 77: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 7 - Inheritance––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––7.6

All three of the header files for the classes are included in lines 3 through 5 so theprogram can use the components of the classes. Notice that the implementations of thethree classes are not in view here and do not need to be in view. This allows the codeto be used without access to the source code for the actual implementation of theclass. 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 asmany as desired could be declared and used in order to accomplish the programmingtask at hand. You will notice how clean and uncluttered the source code is for thisprogram since the classes were developed, debugged, and stored away previously,and the interfaces were kept very simple. There is nothing new here so you shouldhave no trouble understanding the operation of this program.

Compiling and executing this program will take a bit of effort but the process is notcomplicated. The three classes and the main program can be compiled in any orderdesired. 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 therequired 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 becauseof 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 the Borland implementation ofC++, the "project" capability will make this a snap.

WHY THE #ifndef VEHICLE_H ?

_________________________________________________________________

We promised to return to the strange looking preprocessor directive in lines 4, 5 and 17in 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 classsince car is a derived class of vehicle and must know all about its parent. We do thatby 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 thesame reason.

When we get to the main 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 ofALLVEHIC.CPP, but this leads to a problem. When the preprocessor gets to the carclass, it includes the vehicle class because it is listed in the car class header file, butsince the vehicle class was already included in line 3 of ALLVEHIC.CPP, it is includedtwice and we attempt to redefine the class vehicle. Of course it is the same definition,but the system doesn't care, it simply doesn't allow redefinition of a class. We allow thedouble inclusion of the file and at the same time prevent the double inclusion of theclass by building a bridge around it using the word VEHICLE_H. If the word is alreadydefined, the definition is skipped, but if the word is not defined, the definition is includedand the word is defined at that time. The end result is the actual inclusion of the classonly once, even though the file is included more than once. You should have notrouble understanding the logic of the includes if you spend a little time studying thisprogram sequence.

Page 78: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 7 - Inheritance––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––7.7

Even though ANSI-C allows multiple definitions of entities, provided the definitions areidentical, C++ does not permit this. The primary reason is because the compiler wouldhave great difficulty in knowing if it has already made a constructor call for theredefined entity, if there is one. A multiple constructor call for a single object couldcause great havoc, so C++ was defined to prevent any multiple constructor calls bymaking 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, withthe period replaced by the underline. If the name of the file is used systematically in allof your class definitions, you cannot have a name clash because the filename of everyclass must be unique. It would be good for you to get into the practice of building theoptional skip around all of your classes. All class definition files in the remainder of thistutorial will include this skip around to prevent multiple inclusions and to be an examplefor you. You should get into the practice of adding the skip around to all of your classheaders no matter how trivial they may seem to be.

OUR FIRST PRACTICAL INHERITANCE

_________________________________________________________________

Continuing where we started in chapter 5, we ===============will inherit the date class into the file named NEWDATE.HNEWDATE.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 isavailable in the structure returned from the system call in the date class. However, weare more interested in illustrating inheritance in a practical example than we are indeveloping a perfect class, so we will live with this inefficiency. You will note that weadd one variable and one method to create our new class.

The program named NEWDATE.CPP contains the ===============implementation for the added method and should NEWDATE.CPPbe simple for the student to understand. ===============

This class implementation uses the array days[] from the date class implementationsince it was defined as a global variable there. The method named get_time_of_day()involves very simple logic but still adjusts for leap years.

Finally, the example program named TRYNDATE.CPP ================will use the new class in a very simple way to TRYNDATE.CPPillustrate that the derived class is as easy to ================use as the base class and in fact the mainprogram has no way of knowing that it is usinga 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 classas well as the object code from the newdate class and the main program.

Page 79: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 7 - Inheritance––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––7.8

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 the optional skip around the header files of the classes named car and truck. Then recompile all four files and relink them to get an executable file.

3. 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 answer directory on the distribution disk for this tutorial.

4. 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.

Page 80: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 8 - More inheritance––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––8.1

Chapter 8

MORE INHERITANCE

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

REORGANIZED FILE STRUCTURE

_________________________________________________________________

A close examination of the file named ================INHERIT1.CPP will reveal that it is identical to INHERIT1.CPPthe program developed in chapter 7 named ================ALLVEHIC.CPP except that the program text isrearranged.

The biggest difference is that some of the simpler methods in the classes have beenchanged to inline code to shorten the file considerably. In a practical programmingsituation, methods that are this short should be programmed inline since the actualcode to return a simple value is shorter than the code required to send a message to anon-inline method.

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

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

Page 81: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 8 - More inheritance––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––8.2

After you have convinced yourself that this program is truly identical to the programnamed ALLVEHIC.CPP from chapter 7, compile and execute it with your compiler toassure 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 thiscode. This is to make it easy to compile and execute the example programs in thischapter.

THE SCOPE OPERATOR

_________________________________________________________________

Because the method initialize() is defined in the derived car class, it hides the methodof the same name which is part of the base class, and there may be times you wish tosend 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 mainprogram;

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

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

HIDDEN METHODS

_________________________________________________________________

Examine the file named INHERIT2.CPP carefully ================and you will notice that it is a repeat of the INHERIT2.CPPlast example program with a few minor changes. ================

You will notice that the derived classes named car and truck do not have the keywordpublic prior to the name of the base class in the first line of each. The keyword public,when included prior to the base class name, makes all of the methods defined in thebase class available for use in the derived class just as if they were defined as part ofthe derived class. Therefore, in the previous program, we were permitted to call themethods defined as part of the base class from the main program even though we wereworking with an object of one of the derived classes. One example of when we did this,was when we sent a message to the sedan to get its weight in an output statement ofthe main program.

In the present program, without the keyword public prior to the base class name, theonly methods available for objects of the car class, are those that are defined as part ofthe class itself, and therefore we only have the methods named initialize() andpassengers() available for use with objects of class car. In this program, the onlyinheritance is that of variables since the two variables are inherited into objects of classcar.

Page 82: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 8 - More inheritance––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––8.3

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 namedpassenger_load and the two that are part of its parent class, wheels and weight. Allare available for direct use within its methods because of the use of the keywordprotected in the base class. The variables are a part of an object of class car when it isdeclared and are stored as part of the object. We will show you the details of access tothe parent class variables within derived classes shortly in this chapter. For now, wewill return to the use of the subclasses in this example program.

The observant student will notice that several of the output statements have beencommented out of the main program since they are no longer legal or meaningfuloperations. Lines 57 through 59 have been commented out because the methodsnamed get_weight() and wheel_loading() are not inherited into the car class without thekeyword public in the car class definition. You will notice that initialize() is still availablebut this is the one in the car class, not the method of the same name in the vehicleclass.

Moving on to the use of the truck class in the main program, we find that lines 63 and65 are commented out for the same reason as given above, but lines 66 and 67 arecommented out for an entirely different reason. Even though the method namedefficiency() is available and can be called as a part of the truck class, it cannot be usedbecause we have no way to initialize the wheels or weight of the truck objects. We canget the weight of the truck objects, as we have done in line 106, but since the weighthas no way to be initialized, the result is meaningless and lines 66 and 67 arecommented out.

As you have surely guessed by now, there is a way around all of these problems andwe will cover them shortly. In the meantime, be sure to compile and execute thisexample program to see that your compiler gives the same result. It would be a goodexercise for you to reintroduce some of the commented out lines to see what sort of anerror message your compiler issues for these errors.

INITIALIZING ALL DATA

_________________________________________________________________

If you will examine the example program named ================INHERIT3.CPP, you will find that we have fixed INHERIT3.CPPthe initialization problem that we left dangling ================in the last example program.

The method named init_truck() now contains all four of the parameters as input datawhich get transferred to the four variables. Following the initialization, it is permissibleto call the semi.efficiency() method in line 67 and 68 of the main program.

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

Page 83: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 8 - More inheritance––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––8.4

WHAT IS PROTECTED DATA ?

_________________________________________________________________

Examine the program named INHERIT4.CPP for an ================example we will use to define protected data. INHERIT4.CPP ================

Just to make the program more versatile, we have returned to the use of the keywordpublic prior to the name of the parent classes in lines 18 and 29 of the class definitions.

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

In the present example program, the keyword protected is given in line 5 so that all ofthe data of the vehicle class can be directly imported into any derived classes but arenot available outside of the class or derived classes. All data are automaticallydefaulted to private type if no specifier is given. The keyword private can be used asillustrated in lines 19 and 30 but adds nothing due to the fact that class membersdefault to private by definition.

You will notice that the variables named wheels and weight are available to use in themethod named initialize() in lines 85 through 91 just as if they were declared as a partof the car class itself. We can now state the rules for the three means of definingvariables 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.

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 theother keywords is used.

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

Page 84: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 8 - More inheritance––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––8.5

WHAT IS PRIVATE DATA ?

_________________________________________________________________

Examine the file named INHERIT5.CPP where the ================data is allowed to use the private default. INHERIT5.CPP ================

In this program, the data is not available for use in the derived classes, so the only waythe data in the base class can be used is through use of messages to methods in thebase class.

It seems a little silly to have to call methods in the base class to get to the data which isactually a part of the derived class, but that is the way C++ is defined to work. Thiswould indicate to you that you should spend some time thinking about how any classyou define will be used. If you think somebody may wish to inherit your class into anew class and expand it, you should make the data members protected so they can beeasily used in the new class. Be sure to compile and execute this program.

INHERITING CONSTRUCTORS

_________________________________________________________________

Examine the example program named INHERIT6.CPP ================for yet another variation to our basic program, INHERIT6.CPPthis time adding constructors. ================

The vehicle class has a constructor to initialize the number of wheels and the weight tothe indicated values and has no surprising constructs. The car and truck classes eachhave a constructor also to initialize their unique variables to some unique values. If youjump ahead to the main program, you will find that the initializing statements arecommented out for each of the objects so we must depend on the constructors toinitialize the variables. The most important thing to glean from this example program isthe fact that when one of the constructors is called for a derived class, the constructoris also called for the parent class. In fact, the constructor for the parent class will becalled before the constructor for the derived class is called. All of the data will beinitialized, including the data inherited from the parent class.

We will say much more about constructors used with inheritance in the next chapter ofthis tutorial. Be sure to compile and execute this example program.

Page 85: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 8 - More inheritance––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––8.6

POINTERS TO AN OBJECT AND AN ARRAY OF OBJECTS

_________________________________________________________________

Examine the example program named INHERIT7.CPP ================for examples of the use of an array of objects INHERIT7.CPPand a pointer to an object. ================

In this program, the objects are instantiated from an inherited class and the intent ofthis program is to illustrate that there is nothing magic about a derived class.

The program is identical to the first program in this chapter until we get to the mainprogram where we find an array of 3 objects of class car declared in line 52. It shouldbe obvious that any operation that is legal for a simple object is legal for an object thatis part of an array, but we must be sure to tell the system which object of the array weare interested in by adding the array subscript as we do in lines 56 through 62. Theoperation of this portion of the program should be very easy for you to follow, so we willgo on to the next construct of interest.

You will notice, in line 65, that we do not declare an object of type truck but a pointer toan object of type truck. In order to use the pointer, we must give it something to pointat which we do in line 67 by dynamically allocating an object. Once the pointer has anobject to point to, we can use the object in the same way we would use any object, butwe must use the pointer notation to access any of the methods of the object. This isillustrated for you in lines 68 through 72, and will be further illustrated in the exampleprogram of chapter 12 in this tutorial.

Finally, we deallocate the object in line 73. You should spend enough time with thisprogram to thoroughly understand the new material presented here, then compile andexecute 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 toadd to this series. Your assignment is to develop the newtime class which inherits thetime class and adds a new member variable named seconds_today and a method tocalculate the value of seconds since midnight to fill the variable.

A complete solution to this problem will be found in the ANSWERS directory on thedistribution disk. The files named NEWTIME.H, NEWTIME.CPP, and TRYNTIME.CPPare the solution files. It would be a good exercise for you to attempt to write this newclass before you look at the example solution.

Page 86: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 8 - More inheritance––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––8.7

PROGRAMMING EXERCISES

_________________________________________________________________

1. Remove the comment delimiters from lines 65 through 67 of INHERIT2.CPP to see what kind of results are returned. Remove them from line 57 to see what kind of an error is reported by the compiler for this error.

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

Page 87: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 9 - Multiple inheritance and future directions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––9.1

Chapter 9

MULTIPLE INHERITANCE AND FUTURE DIRECTIONS

C++ version 2.0 was released by AT&T during the summer of 1989, and the majoraddition to the language is multiple inheritance, the ability to inherit data and methodsfrom more than one class into a subclass. Multiple inheritance and a few of the otheradditions to the language will be discussed in this chapter along with some of theexpected future directions of the language.

Several companies have C++ compilers available in the marketplace, and many othersare sure to follow. Because the example programs in this tutorial are designed to be asgeneric as possible, most should be compilable with any good quality C++ compilerprovided it follows the AT&T definition of version 2.1 or newer. Many of theseexamples will not work with earlier definitions because the language was significantlychanged with the version 2.1 update.

After completing this tutorial, you should have enough experience with the language tostudy additional new constructs on your own as they are implemented by the variouscompiler writers. We will update the entire tutorial as soon as practical followingprocurement of any new compiler, but hopefully the language will not change rapidlyenough now to warrant an update oftener than annually. Please feel free to contact usfor information on updates to the Coronado Enterprises C++ tutorial.

MULTIPLE INHERITANCE

_________________________________________________________________

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

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

Page 88: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 9 - Multiple inheritance and future directions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––9.2

SIMPLE MULTIPLE INHERITANCE

_________________________________________________________________

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

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

In line 30, we define another class named driven_truck which inherits all of the data andall 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 moreclasses, the same technique is used except that we use a list of inherited classesseparated by commas as illustrated in line 30. The observant student will notice thatwe use the keyword public prior to the name of each inherited class in order to be ableto freely use the methods within the subclass. In this case, we didn't define any newvariables, but we did introduce two new methods into the subclass in lines 32 through39.

We declared an object named chuck_ford which presumably refers to someone namedChuck who is driving a Ford moving van. The object named chuck_ford is composed offour variables, three from the moving_van class, and one from the driver class. Any ofthese four variables can be manipulated in any of the methods defined within thedriven_truck class in the same way as in a singly inherited situation. A few examplesare given in lines 47 through 56 of the main program and the diligent student should beable to add additional output messages to this program if he understands the principlesinvolved.

All of the rules for private or protected variables and public or private methodinheritance 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(), andboth of these are inherited into the subclass with no difficulty. However, if we attemptto send a message to one of these methods, we will have a problem, because thesystem does not know which we are referring to. This problem will be solved andillustrated in the next example program.

Page 89: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 9 - Multiple inheritance and future directions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––9.3

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

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

MORE DUPLICATE METHOD NAMES

_________________________________________________________________

The second example program in this chapter named ================MULTINH2.CPP, illustrates the use of classes MULTINH2.CPPwith 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 theclasses named cost_per_full_day(). This was done intentionally to illustrate how thesame method name can be used in all three classes. The class definitions are noproblem at all, the methods are simply named and defined as shown. The problemcomes when we wish to use one of the methods since they are all the same name andthey have the same numbers and types of parameters and identical return types. Thisprevents some sort of an overloading rule to disambiguate the message sent to one ormore of the methods.

The method used to disambiguate the method calls are illustrated in lines 60, 64, and68 of the main program. The solution is to prepend the class name to the methodname with the double colon as used in the method implementation definition. This isreferred to as qualifying the method name. Qualification is not necessary in line 68since it is the method in the derived class and it will take precedence over the othermethod names. Actually, you could qualify all method calls, but if the names areunique, 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 observantstudent will notice that there is a slight discrepancy in the results given in lines 79through 81, since the first two values do not add up to the third value exactly. This isdue to the limited precision of the float variable but should cause no real problem.

Page 90: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 9 - Multiple inheritance and future directions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––9.4

DUPLICATED VARIABLE NAMES

_________________________________________________________________

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

According to the rules of inheritance, an object of the driven_truck class will have twovariables with the same name, weight. This would be a problem if it weren't for the factthat C++ has defined a method of accessing each one in a well defined way. You haveprobably guessed that we will use qualification to access each variable. Lines 38 and45 illustrate the use of the variables. It may be obvious, but it should be explicitlystated, that there is no reason that the subclass itself cannot have a variable of thesame name as those inherited from the parent classes. In order to access it, noqualification would be required.

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

PRACTICAL MULTIPLE INHERITANCE

_________________________________________________________________

Examine the example program named DATETIME.H ================for a practical example using multiple DATETIME.Hinheritance. ================

You will notice that we are returning to our familiar date and time classes from earlierchapters.

There is a good deal to be learned from this very short header file since it is our firstexample of member initialization. There are two constructors for this class, the firstbeing a very simple constructor that does nothing in itself as is evident from anexamination of line 12. This constuctor allows the constructors to be executed for theclasses new_date and time_of_day. In both cases a constructor will be executed thatrequires no parameters, and such a constructor is available for each of these twoclasses.

The second constuctor is more interesting since it does not simply use the defaultconstructor, but instead passes some of the input parameters to the inherited classconstructors. Following the colon in line 13 are two member initializers which are usedto initialize members of this class. Since the two parent classes are inherited, they arealso members of this class and can be initialized as shown. Each of the memberinitializers is actually a call to a constructor of the parent classes and it should beevident that there must be a constructor with the proper number of input parameters torespond to the

Page 91: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 9 - Multiple inheritance and future directions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––9.5

messages given. You will note that in line 14, we are actually calling the constructorwith no parameters given explicitly. If we chose, we could simply let the system callthat constructor automatically, but this gives us an explicit comment on what ishappening.

MORE ABOUT MEMBER INITIALIZERS

_________________________________________________________________

Actually, we can use the member initializer to initialize class members also. If we had aclass member of type int named member_var, we could initialize it also by mentioningthe name of the member followed by the value we desired to initialize it to inparentheses. If we wished to initialize it to the value 13, we could use the following lineof code in the member initializer list;

member_var(13);

Following all member initialization, the normal constructor code is executed which inthis case is given in line 16.

ORDER OF MEMBER INITIALIZATION

_________________________________________________________________

The order of member initialization may seem a bit strange, but it does follow a fewsimple rules. The order of member initialization does not follow the order given by theinitialization list, but another very strict order over which you have complete control. Allinherited classes are initialized first in the order they are listed in the class header. Iflines 14 and 15 were reversed, class new_date would still be initialized first because itis mentioned first in line 8. It has been mentioned that C++ respects its elders andinitializes its parents prior to itself. That should be a useful memory aid in the use ofmember initializers.

Next, all local class members are initialized in the order in which they are declared inthe class, not the order in which they are declared in the initialization list. Actually, itwould probably be good practice to not use the member initializer to initialize classmembers but instead to initialize them in the normal constructor code.

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

Page 92: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 9 - Multiple inheritance and future directions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––9.6

USING THE NEW CLASS

_________________________________________________________________

The example program named USEDTTM.CPP uses ===============the datetime class we just built, and like USEDTTM.CPPour 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 theconstructor with the member initializers is used with the objects named birthday andspecial.

The diligent student should have no trouble understanding the remaining code in thisexample.

FUTURE DIRECTIONS OF C++

_________________________________________________________________

An ANSI committee has been formed to write an ANSI standard for C++. They first metin the Spring of 1990 and are expected to complete the standard in about three years.Until the new standard is released, the C++ language is expected to stay fairly stable.However, due to the nature of compiler writers and their desire to slightly improve theirofferings over their competitors, you can bet that the language will not remain staticduring this three year period.

Many small changes have been added during the past year that barely affect thecasual programmer, or even the heavy user of the language. You can be sure that thelanguage will evolve slowly and surely into a very usable and reliable language. Thereare two areas, however, that should be discussed in a little detail because they will addso much to the language in future years. Those two topics are parameterized typesand exception handling.

FUTURE DIRECTIONS - PARAMETERIZED TYPES

_________________________________________________________________

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

Page 93: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 9 - Multiple inheritance and future directions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––9.7

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 providesprogrammers with prewritten and thoroughly debugged software routines that work withmany different types. When this is generally available in C++, there will be acomponents industry for C++ and precoded, debugged and efficient source code will beavailable off the shelf to perform many of the standard operations. These operationswill include such things as sorts, queues, stacks, lists, etc.

Bjarne Stroustrup has announced that parameterized types, otherwise known astemplates or generics, will be available in a future version of C++. He has presented apaper with details of one way to implement them, but this is only a suggestion, not aspecification.

Borland International has included templates in version 3.0 of Borland C++, andhopefully their implementation will be very close to the final definition of templates. Thenext three example programs will illustrate the use of templates with Borland's compiler,but may not work with other compilers.

THE FIRST TEMPLATE

_________________________________________________________________

The example program named TEMPLAT1.CPP is the ================first example of the use of a template. TEMPLAT1.CPP ================

This program is so simple it seems silly to even bother with it but it will illustrate the useof the parameterized type.

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

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

The diligent student should realize that nearly the same effect can be achieved throughuse 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.

Page 94: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 9 - Multiple inheritance and future directions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––9.8

A CLASS TEMPLATE

_________________________________________________________________

The example program named TEMPLAT2.CPP is a ================little more involved since it provides a TEMPLAT2.CPPtemplate 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 isan entire class definition. The diligent student will recognize that this is a very weakstack class since there is nothing to prevent popping data from an empty stack, andthere is no indication of a full stack. Our intent, however, is to illustrate the use of theparameterized 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 astack designed to store integers, and another object named float_stack in line 26 whichis designed to store float type values. In both cases, we enclose the type we desire thisobject to work with in "<>" brackets, and the system creates the object by first replacingall 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 lines13 and 14 use the assignment operator on the parameterized type.

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

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

REUSING THE STACK CLASS

_________________________________________________________________

The program named TEMPLAT3.CPP uses the same ================class with the template as defined in the last TEMPLAT3.CPPprogram 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 stackrather than just the pointer to it. To do so however, would be very inefficient since theentire class would be copied into the stack each time it is pushed and the entire classwould be copied out again when it was popped. Use of the pointer is a little moregeneral, so it was illustrated here for your benefit.

Page 95: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 9 - Multiple inheritance and future directions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––9.9

All three of the previous programs can be compiled and executed if you have a copy ofBorland C++ version 3.0. Other compilers may not work with these programs sinceparameterized types are not yet a part of the C++ specification.

FUTURE DIRECTIONS - EXCEPTION HANDLING

_________________________________________________________________

A future version of C++ will have some form of exception handling to allow theprogrammer to trap errors and prevent the system from completely shutting down whena fatal error occurs. The Ada language allows the programmer to trap any error thatoccurs, even system errors, execute some recovery code, and continue on with theprogram execution in a very well defined way. Bjarne Stroustrup, working inconjunction with the ANSI-C++ committee, has announced that some form of exceptionhandling will be implemented but he has not stated what form it would take as of thiswriting.

WHAT SHOULD BE YOUR NEXT STEP ?

_________________________________________________________________

Again, we have reached a major milestone in C++ programming. With the ability to useinheritance, you have nearly all of the tools you need to effectively use the objectoriented programming techniques of C++ and you would do well to stop studying againand begin programming. The only topic left with C++ is virtual methods which are usedfor 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 inattempting to force it into every program, you could wind up with an unreadable mess,so you should approach it slowly.

Page 96: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 10 - Virtual functions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––10.1

Chapter 10

VIRTUAL FUNCTIONS

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

One term which must be defined is polymorphism, a rather large word that simplymeans similar when used in the context of object oriented programming. Objects arepolymorphic if they have some similarities but are still somewhat different. We will seehow it is used in the context of object oriented programming as we proceed through thischapter.

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 usedto refer to two or more things. The use of virtual functions can be a great aid inprogramming some kinds of projects as you will see in these two chapters.

A SIMPLE PROGRAM WITH INHERITANCE

_________________________________________________________________

Examine the example program named VIRTUAL1.CPP ================for the basic program outline we will use for VIRTUAL1.CPPall discussion in this chapter. ================

Since this program has nothing to do with virtual functions, the name may be somewhatmisleading. It is named VIRTUAL1.CPP because it is part of a series of programsintended to illustrate the use of virtual functions. The last program in this chapter willillustrate the proper use of virtual functions.

The first program is very simple and you will recognize it as being somewhat similar tothe programs studied in the last chapter except that this program is greatly simplified inorder to effectively instruct you in the use of a virtual function. You will notice thatmany of the methods from the last chapter have been completely dropped from thisexample for simplicity, and a new method has been added to the parent class, themethod named message() in line 8.

Throughout this chapter we will be studying the operation of the method namedmessage() in the base class and the derived classes.

Page 97: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 10 - Virtual functions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––10.2

For that reason, there is a method named message() in the car class as well as in thenew class named boat in lines 27 through 32.

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 youprefer, you can refer to it as a virtual function. You will recall that the method namedmessage() from the base class is available in the truck class because the method fromthe base class is inherited with the keyword public included in line 19. You will alsonotice that the use of the keyword public in lines 12 and 27 actually do nothing becausethe only method available in the base class is also available in the derived classes.There are no methods actually inherited. Leaving the keyword in the header poses noproblem however, so it will be left there for your study.

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

The main program is as simple as the classes, one object of each of the classes isdeclared in lines 37 through 40 and the method named message() is called once foreach object. The result of executing the program indicates that the method for each iscalled except for the object named semi, which has no method named message(). Asdiscussed in the last chapter, the method named message() from the parent class iscalled 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 defaultto private type and none is inherited into the derived classes. Some of the data is left inthe example program simply to make the classes look like classes. Based on yourexperience with C++ by now, you realize that the data could be removed since it is notused.

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

ADDING THE KEYWORD VIRTUAL

_________________________________________________________________

As you examine the next example program named ================VIRTUAL2.CPP, you will notice that there is one VIRTUAL2.CPPsmall change in line 8. ================

The keyword virtual has been added to the declaration of the method namedmessage() in the parent class.

It may be a bit of a disappointment to you to learn that this program operates nodifferently than the last example program. This is because we are using objects directlyand virtual methods have nothing to do with objects, only with pointers to objects as wewill see soon. There is an additional comment in line 46 illustrating that since all fourobjects are of different classes, it is impossible to assign any object to any other object

Page 98: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 10 - Virtual functions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––10.3

in this program. We will soon see that some pointer assignments are permittedbetween objects.

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

USING OBJECT POINTERS

_________________________________________________________________

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

In this program the keyword virtual has been removed from the method declaration inthe parent class in line 8, and the main program declares pointers to the objects ratherthan declaring the objects themselves in lines 37 through 40. Since we only declaredpointers to the objects we find it necessary to allocate the objects before using them byusing the new operator in lines 42 through 49. Upon running the program, we find thateven though we are using pointers to the objects we have done nothing different thanwhat we did in the first program. Upon execution, we find that the program operates inexactly the same manner as the first example program in this chapter. This should notbe surprising because a pointer to a method can be used to operate on an object in thesame manner as an object can be manipulated.

Be sure to compile and execute this program before continuing on to the next exampleprogram. The observant student will notice that we failed to deallocate the objects priorto terminating the program. As always, in such a simple program, it doesn't matterbecause the heap will be cleaned up automatically when we return to the operatingsystem.

A POINTER AND A VIRTUAL FUNCTION

_________________________________________________________________

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

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

Page 99: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 10 - Virtual functions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––10.4

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 notdo. The next two will show you what virtual functions do.

A SINGLE POINTER TO THE PARENT CLASS

_________________________________________________________________

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

You will notice that this is another copy of our program with the keyword virtual omittedfrom line 8 and with a totally different main program. In this program, we only declare asingle pointer to a class and the pointer is pointing to the base class of the classhierarchy. We will use the single pointer to refer to each of the four classes andobserve 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 beendeclared to point to one class, to actually refer to another class. If we referred to avehicle (in the real world, not necessarily in this program), we could be referring to acar, a truck, a motorcycle, or any other kinds of transportation, because we arereferring to a very general form of an object. If however, we were to refer to a car, weare excluding trucks, motorcycles, and all other kinds of transportation, because we arereferring to a car specifically. The more general term of vehicle can therefore refer tomany kinds of vehicles, but the more specific term of car can only refer to a single kindof vehicle, namely a car.

We can apply the same thought process in C++ and say that if we have a pointer to avehicle (remembering that a pointer is actually a reference), we can use that pointer torefer to any of the more specific objects, and that is indeed legal in C++ according tothe definition of the language. In a like manner, if we have a pointer to a car, wecannot use that pointer to reference any of the other classes including the vehicle classbecause the pointer to the car class is too specific and restricted to be used on any ofthe other classes.

THE C++ POINTER RULE

_________________________________________________________________

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

Page 100: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 10 - Virtual functions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––10.5

This is exactly what we do in the main program. We declare a single pointer whichpoints to the vehicle class and use it to point to objects of each of the classes in thesame order as in the last four programs. In each case, we allocate the object, send amessage to the method named message() and deallocate the object before going on tothe next class. You will notice that when we send the four messages, we are sendingthe message to the same method, namely the method named message() which is apart of the vehicle base class. This is because the pointer has a class associated withit. 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 parent classbecause the pointer is of the type of the parent class.

The next program will finally do something you have not seen in any C program or inany C++ program in this tutorial up to this point. After you compile and execute thecurrent program, we will go on to study our first virtual function.

AN ACTUAL VIRTUAL FUNCTION

_________________________________________________________________

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

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

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

You will notice that in lines 40, 44, 48, and 52, even though the code is identical in eachline, the system is making the decision of which method to actually call based on thetype of the pointer when each message is sent. The decision of which method to call isnot 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. Infact, there are only three different calls made because the class named truck does nothave a method named message(), so the system simply uses the method from the

Page 101: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 10 - Virtual functions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––10.6

base class to satisfy the message passed. For this reason, a virtual function must havean implementation available in the base class which will be used if there is not oneavailable in one or more of the derived classes. Note that the message is actually sentto a pointer to the object, but this is splitting hairs and should not be overly emphasizedat this time.

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

IS THIS REALLY SIGNIFICANT ?

_________________________________________________________________

This program probably does not seem to do much when you first approach it, but thedynamic binding is a very useful construct and will be illustrated in the next chapter witha rather simple program that uses the technique of dynamic binding to implement apersonnel 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 wordsactually mean is that with late binding, the compiler does not know which method willactually respond to the message because the type of the pointer is not known atcompile time. With early binding, however, the compiler decides at compile time whatmethod will respond to the message sent to the pointer.

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

Page 102: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 10 - Virtual functions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––10.7

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.

Page 103: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 11 - More virtual functions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––11.1

Chapter 11

MORE VIRTUAL FUNCTIONS

This chapter will actually be a continuation of the topics covered in the last chapter butthis will be a fuller explanation of what virtual functions are and how they can be usedin a program. We will present a simple database program with a virtual function toshow how it can be used, then we will go on to illustrate a more complex use of thevirtual 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 programmingby identifying an object, or in this case a class of objects and even some subordinateobjects, which we completely define. When we get to the main program we then havea simple job with the remaining needs and they are completed using standardprocedural programming techniques which we are familiar with. This is the way tobegin any object oriented programming project, by first identifying a few objects thatcan be separated conveniently from the rest of the code, programming them, thenwriting 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 gainingexperience with object oriented programming techniques, use more objects on futureprojects. Most programmers use too many objects for their first project and write veryobtuse, unreadable code.

THE PERSON HEADER FILE

_________________________________________________________________

Examine the file named PERSON.H for the ================definition file for the person class. This PERSON.Hclass 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 isused for the variables so that they are readily available in the derived classes which willinherit this class.

Page 104: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 11 - More virtual functions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––11.2

THE PERSON IMPLEMENTATION

_________________________________________________________________

The implementation for the person class is given ================here and it is a little strange in the way it is PERSON.CPPwritten and used. ================

The intent of this program is that the virtual method named display() in this file willnever be used, but it is required by the C++ compiler to be used for a default in casesome of the subclasses do not have this function available. In the main program wewill be careful to never call this function due to the nature of the program we are writing.Keep in mind that C++ requires an implementation of all virtual functions even if theyare never used. In this case the message is obviously intended to be output as anerror message.

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

THE SUPERVISOR HEADER

_________________________________________________________________

The file named SUPERVSR.H contains the class ================definitions for the three derived classes, SUPERVSR.Hsupervisor, programmer, and secretary. ================

These were all placed in a single file for two reasons. The first reason is to simplyillustrate to you that this can be done, and secondly, to allow some of the files to becombined on the disk and to require fewer compilations by you prior to executing theresulting program. This is actually a good way to combine these files since they are allderived 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() and allhave the same return value of void, and all have the same number of parameters asthe parent class's method of the same name. All of this equality is required becausethey will all be called by the same call statement. You will also notice that the othermethod in each class has the same name, but different numbers and types of formalparameters 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 andunderstand it completely. Once again, this file cannot be compiled or executed.

Page 105: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 11 - More virtual functions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––11.3

THE SUPERVISOR IMPLEMENTATION

_________________________________________________________________

The file named SUPERVSR.CPP contains the ================implementation for the three classes. SUPERVSR.CPP ================

If you spend a little time studying the code, you will find that each of the methodsnamed init_data() simply initializes all fields to those passed in as the actual argumentsin a very simple manner.

The method named display(), however, outputs the stored data in different ways foreach class since the data is so different in each of the classes. Even though theinterface 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 sovisible 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 programwhich will use all four classes as defined in these four files.

THE FIRST CALLING PROGRAM

_________________________________________________________________

The file named EMPLOYEE.CPP is the first program ================that uses the classes developed in this chapter, EMPLOYEE.CPPand 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 recallfrom the last chapter, this is very important when using virtual functions, the pointermust point to the base class. The pointers that will be stored in this array will all point toobjects of the derived classes however. When we use the resulting pointers to refer tothe methods, the system will choose the method at run time, not at compile time asnearly all of our other programs have been doing.

We allocate six objects in lines 16 through 39, initialize them to some values using themethods named init_data(), then assign the pointers to the members of the array ofpointers to person. Finally, in lines 41 and 42, we call the methods named display() todisplay the stored data on the monitor. You will notice that even though we only useone method call in line 42, we actually send messages to each of the three methodsnamed display() in the subclasses. This is true dynamic binding because if we were tochange the values of some of the pointers in the array, we would then call differentmethods with the same pointers.

Page 106: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 11 - More virtual functions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––11.4

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

A PURE VIRTUAL FUNCTION

_________________________________________________________________

The pure virtual function is also available in the C++ toolbox of possible constructs.You can use a pure virtual function in the present example program by changing line 10of PERSON.H to read as follows;

virtual void display(void) = 0;

You must then eliminate PERSON.CPP from the project or make sequence. Animplementation for a pure virtual function cannot exist in the base class.

Every derived class must include a function for each pure virtual function which isinherited into the derived class. This assures that there will be a function available foreach call and none will ever need to be answered by the base class. You are notpermitted to create an object of any class which contains one or more pure virtualfunctions because there is nothing to answer a message if one is sent to the purevirtual method. The compiler will enforce the two rules mentioned in this paragraph.

THE LINKED LIST CLASS

_________________________________________________________________

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

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

There are two interesting constructs used here that must be pointed out before goingon to the next program. The first is the partial declaration given in line 8 which allowsus to refer to the class named employee_list before we actually define it. The completedeclaration for the class is given in lines 22 through 29. The second construct ofinterest is the friend class listed in line 17 where we give the entire class namedemployee_list free access to the variables which are a part of the employee_element

Page 107: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 11 - More virtual functions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––11.5

class. This is necessary because the method named add_person() must access thepointers contained in employee_element. We could have defined an additional methodas a part of employee_element and used this method to refer to the pointers but it wasfelt that these two classes work so well together that it is not a problem to open awindow between the classes. We still have complete privacy from all other programsand classes declared as parts of this program.

Note that the single method included in the employee_element class is implemented ininline code. Two of the methods of employee_list are still open so we need animplementation for this class.

THE LINKED LIST IMPLEMENTATION

_________________________________________________________________

The file named ELEMLIST.CPP is the ================implementation for the linked list classes and ELEMLIST.CPPshould 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 itsimple but a sorting mechanism could be added to sort the employees by name ifdesired.

The method to display the list simply traverses the list and calls the method nameddisplay() 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 ofthe existence of the three derived classes, only the base class named person ismentioned. 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 asthey are passed through this logic. That is exactly what dynamic binding is, and we willhave a little more to say about it after we examine the calling program.

THE LINKED LIST IMPLEMENTATION

_________________________________________________________________

At this time you should examine the final ================example program in this chapter named EMPLOYE2.CPPEMPLOYE2.CPP for our best example of dynamic ================binding in this tutorial, yet the program iskept very simple.

This program is very similar to the example program named EMPLOYEE.CPP with afew changes to better illustrate dynamic binding. In line 7 we declare an object of theclass employee_list to begin our linked list. This is the only copy of the list we will needfor this program. For each of the elements, we allocate the data, fill it, and send it tothe linked list to be added to the list where we allocate another linked list element to

Page 108: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 11 - More virtual functions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––11.6

point to the new data, and add it to the list. The code is very similar to the last programdown through line 40.

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

If you changed PERSON.H to use a pure virtual function, it will still work with thisprogram just as we discussed earlier.

WHAT GOOD IS ALL OF THIS

_________________________________________________________________

Now that we have the program completely debugged and working, suppose that wewished to add another class to the program, for example a class named consultantbecause we wished to include some consultants in our business. We would have towrite the class of course and the methods within the classes, but the linked list doesn'tneed to know that the new class is added, so it does not require any changes in orderto update the program to handle consultant class objects. In this particular case, thelinked list is very small and easy to understand, but suppose the code was very longand complex as with a large database. It would be very difficult to update everyreference to the subclasses and add another subclass to every list where they werereferred to, and this operation would be very error prone. In the present exampleprogram, the linked list would not even have to be recompiled in order to add the newfunctionality.

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 wasexecuting 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 theinventory for a large retail store, or even for an airlines reservation system. Youprobably have little difficulty understanding the use of dynamically allocated memory fordata, but dynamically allocating classes or types is new and difficult to grasp, but thepossibility is there with dynamic binding.

Page 109: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 11 - More virtual functions––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––11.7

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.

Page 110: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 12 - Flyaway adventure game––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––12.1

Chapter 12

FLYAWAY ADVENTURE GAME

Now that you have learned lots of things about C++, and know how to write and use asingle isolated class, you have the problem of how to build a program with severalclasses that work together to accomplish some task. After some amount of thought, itseems that an adventure game would be a good candidate for a relatively largeexample program. It has lots of input and output and requires a good deal of flexibilitywhile running since there are so many things that can be included in the game asobstacles, mazes, items to find, and puzzles to solve.

The adventure game presented in this chapter is unique as far as I know, since I havenever heard of another adventure game featuring an airport. The location is not nearlyas important as the code used to get through the airport. You are advised to play thegame 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 ofwhether you understand its operation.

PLAYING THE GAME

_________________________________________________________________

Prior to studying the source code for this game, ===============it would be to your advantage to spend some time FLYAWAY.EXEplaying the game to get familiar with what the ===============game does.

Load the file FLYAWAY.EXE and begin the adventure through the airport. Theexecutable file is precompiled for you so you can begin executing the program beforeyou have to compile and link the whole thing. The entire program is composed of 15files and will take a little effort on your part to properly compile and link it, but that willcome later.

If you have played adventure games before, sometimes called interactive fiction, youshould begin trying various commands to find your way through the airport to yourproper plane. If you have not played before, a few hints are in order concerning how toplay the game.

The object of the game is to get to your proper plane on time so you can fly away toyour vacation. Of course there a few obstacles and problems along the way and theywill be brought up at the appropriate time. It will be up to you to solve the puzzlesassociated 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

Page 111: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 12 - Flyaway adventure game––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––12.2

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 itnecessary to restart the game many times before you arrive at your destinationunscathed and on time.

THE METHOD OF PLAY

_________________________________________________________________

The method of play is extremely simple. You simply wander around the airport lookingfor things to do and places to go. You move around the airport by giving the systemcommands to go in a direction with four choices available, north, south, east, or west.You can abbreviate any of these four direction commands to the first letter only, andyou can use either upper or lower case. The system may move you to another area ofthe airport, or it may tell you that you can't go that way. Try loading the game now andtyping the four directions once each to see what happens. If this is not clear, enter theword help to get you started.

In addition to moving around, you can pick up items or ask for more information in anyof the rooms. Try telling the system to look around the room and see what additionalinformation it gives you for each room, some of the clues for solving the puzzle aregiven in the clues issued in response to a look command. Another important commandis 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 canbe given in either order, since the system is smart enough to know the difference, andadditional words may be given following the legal words. If you give the system acommand that is not in its limited vocabulary, it will tell you it doesn't understand thatword. Try telling the system to drop an item you possess, or get an item that is locatedin the room you are currently in.

Several friends have played this game with no more knowledge than you have beengiven. 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 codefor the game. The entire source code for the game is on your distribution disk. Thegame was purposely kept small so the code could be easily grasped by a programmingstudent. There is no reason the game could not have been made much larger by theaddition of more rooms, items, and traps. You may choose to do just that to gainexperience in working with C++.

Page 112: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 12 - Flyaway adventure game––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––12.3

A FEW SPECIAL CONSTANTS

_________________________________________________________________

The file named FLYAWAY.H contains the ===============definitions for TRUE and FALSE as well as the FLYAWAY.Henumerated 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 theword in question was not in the library and hence not a legal word for use with thegame.

The #ifndef in line 5 is required because this header file is included in many of the otherfiles and if it is included more than once, there will be a multiple definition, and hencean error. A class only needs to be defined once, so after it is defined by one of theincludes, the name ITEMS_H will be defined and any other defines will be ignored.This is necessary because of the separate compilation capability of C++. This wasdescribed in more detail near the end of chapter 7.

THE FIRST CLASS - clock

_________________________________________________________________

Examine the file named CLOCK.H for the ===============definition of the clock class. This is the CLOCK.Hclass 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, andfour methods. The first method is the constructor used to initialize the clock to 8:51 asyou can see if you refer to the implementation of this class in the file namedCLOCK.CPP. The next two methods are used to get the current values of the twovariables. The final method is much more interesting since it does more. It updates thetime of day clock and outputs the user prompt to ask for the next command. This maynot be the best place to output the user prompt since this class is devoted to the time ofday and associated operations, but this was chosen as the place to do it since the timeof 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 thecoding later, when we need to decide if we made it to the plane on time, the time wasincremented at the beginning of each game move. The time is therefore the samewhen the command is entered and when it is executed, hence the time is incrementedprior to even the first output.

The clock class is by far the simplest class in the adventure game and should be simplefor you to understand. After you are sure you understand it, we will go on to the nextclass.

Page 113: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 12 - Flyaway adventure game––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––12.4

INPUT COMMAND PARSING

_________________________________________________________________

The input command parsing routines are defined ===============within the words class and the code for the WORDS.Hclass is in WORDS.CPP. ===============

The code is straightforward and simple to understand if you study it, so only a fewcomments will be made about this class.

The method get_command() reads two words from the keyboard by calling the functionread_a_line() and stores the words in the class members verb and noun. It stores zerofor 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 userinput. This allows any code that has visibility of the object based on this class to findout what the player would like to do.

There are four methods beginning with is_ in this class that are used to determine if aword is a verb, a noun, a direction, or an operation. These are called upon fromvarious places within the program. What 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 ofthe code.

Finally the simple method named stop_game() is used to set the verb to the value ofquit so the game will be ended by the control logic in the main programFLYAWAY.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 tostudy it to whatever depth you desire.

THE SECOND CLASS - items

_________________________________________________________________

If you examine the files named ITEMS.H and ===============ITEMS.CPP, you will find the complete ITEMS.Hdefinitions 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 orcarried by yourself, the keys, the candy, the ticket, and the money. The keys and themoney keep you from getting through security and the ticket and candy are required toget 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 sincethat is the only required indication. A TRUE means the item is located here, and a

Page 114: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 12 - Flyaway adventure game––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––12.5

FALSE means the item is not here. The values of TRUE and FALSE are defined inFLYAWAY.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 toeither get a specific item, or drop one. The fourth method is used to tell us if the item islocated 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 desireddepending on whether you are carrying the items, or they are located in a roomsomewhere.

This file, like all other header files, is protected from multiple inclusion by the #ifndefconstruct discussed earlier.

This class is used in line 24 of FLYAWAY.CPP to define an object for the player namedpersonal_items which stores the list of items the player is carrying around. It is alsoused in the class location as an embedded or nested object to store the items that arelocated in each of the 19 locations in the game.

Once again, the implementation for this class is so simple that you will have no difficultyin understanding it.

THE FLIGHT AND GATE CLASS - schedule

_________________________________________________________________

Examine the files named SCHEDULE.H and ================SCHEDULE.CPP for our first example of a rather SCHEDULE.Hlarge 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 thevariables. Instead of a detailed description of each variable and method, we will onlygive a brief overview of the class.

Only one object of this class is declared named flight_info in line 22 of the mainprogram named FLYAWAY.CPP. The constructor initializes the flight possibilities, andthe method named shuffle_gates() shuffles all gates around if the player arrives at hiscorrect gate without reading the monitor in the waiting area. Once the monitor in thewaiting area is read, the flights_frozen variable is made TRUE. Likewise, the playersdestination is changed during every move by the method named shuffle_flights() untilthe 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 dataseen when invoking the command look at one of the gates. Finally, this class containsthe method named check_flight() which searches through the list of requirements tosee if the player has completed all requirements to successfully reach the finaldestination for his vacation.

You will notice that several of the location objects were required to be available withinthis code and are listed as extern in lines 12 through 21 of the implementation of theclass. The only other thing to point out is the rest room requirement prior to boarding

Page 115: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 12 - Flyaway adventure game––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––12.6

the flight. Line 28 is where the global variable is defined and initialized, then in line 77it is set TRUE if the current location is the rest room, since this is called once duringeach player move. Finally, the state of this variable is checked in line 230 of this fileand the appropriate action taken. You will note that the main program is not aware thatthe rest room variable exists or that anything happens as a result of this variable. Inaddition to information hiding, we may coin a new term, something like "InformationIgnorance", since the main program did not even need to be aware that there was arequirement to visit the rest room.

Even though this is a relatively large and complex class, it is well commented so nofurther information will be given concerning the implementation.

THE MOST USED CLASS - location

_________________________________________________________________

The file named LOCATION.H is the header file for ================the class named location. It is the class that LOCATION.Hcontrols 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 thevarious entities. The first four are the locations to which we will go if we move in one ofthe four directions from the current location. You will note that they are pointers tothose four locations. Next we have pointers to two different character stringsassociated with this room. Finally in line 22, we declare the object named list_of_itemswhich is an object of class items defined earlier. Note that this is an embedded class, aclass embedded within the location class. It is not a parent class which we areinheriting something from. In fact we are instantiating an object of class items for usewithin the room since the room is allowed to store any combination of the four itemscontained in the class named items.

There is no constructor used with this class since we choose to initialize the locationsone by one. The method named init() has 6 variable parameters, all of which arepointers, 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 constructorassociated with its class. Referring to lines 40 through 171 of the implementation forthe map class, you will find all of the initialization code for the 19 objects of classlocation. If you drew a map when you played the game, you will see theinterconnections between the various locations embedded in the initializationstatements. Notice there is no way to get back to the car from the passenger drop offarea, 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 waslegal, otherwise it returns a NULL value. The observant student will also notice thatthere are special cases involved with getting out of the snack bar and getting throughsecurity. These are located here because they are part of the move logic. If youplayed the game to the complete conclusion, you surely had trouble with at least one ofthese situations.

Page 116: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 12 - Flyaway adventure game––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––12.7

The rest of the methods in this class should be self explanatory and will not bediscussed any further.

Page 117: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 12 - Flyaway adventure game––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––12.8

THE LOCATION MESSAGES

_________________________________________________________________

Examine the file named MESSAGE.TXT for a ===============complete listing of the messages output to the MESSAGE.TXTmonitor when each location was entered. ===============

You will also find the text for each of the messages output in response to a lookcommand in this file. These were put into a separate file only for the purpose ofreducing the size of the map class implementation file. It does not reduce the compiletime since these messages are not separately compiled. They are included into the fileand compiled each time the map file MAP.CPP is compiled. You will note that a few ofthe messages have no text at all, only the empty quote marks, but are included in orderto have something for the initialization code to work with.

Three other messages are stored here for convenience in lines 5 through 40. Their useand meaning should be self-evident.

THE MAIN PROGRAM

_________________________________________________________________

We finally reach the main program, the one that ===============actually does the top level control. Examine FLYAWAY.CPPthe 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 toairport.initialize(), we enter a single do while loop which terminates when the playerenters the word quit or when the verb quit comes up some other way. There are otherways to set the verb to quit because it is generated internally in some cases such as atend of game.

The loop itself consists of 5 method calls. First we call the function namedinput_words.get_command() to get the players input command in line 30. Next wesend two messages to the object named flight_info to shuffle the flights and gates if theproper actions have not been performed, then we call airport.perform_action() which wewill describe in a few paragraphs. Finally, we send a messages to the object namedflight_info to check if the player has reached one of the gates. Remember that withinmost of the methods we perform checks to see if we need to do the thing requested inthe message, then either perform the action or simply return to the caller or messagesender.

Page 118: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 12 - Flyaway adventure game––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––12.9

THE WORKING METHOD

_________________________________________________________________

The only function we have not mentioned yet is ===============the one that does most of the interesting work, MAP.Hthe 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 actionto be performed. Because of the way we packaged all of the other routines, thisfunction is a snap to implement and to study. If you go through each of the else ifclauses in this function, you will have no trouble understanding what action is taken foreach of the input commands. You will notice that many of the actions have conditionalclauses before the action is taken. For example, it is illegal to buy candy unless theplayer has money, the location has candy, and the location must be the snack_baraccording to the rules of the game.

Finally, at the end of this method in line 277, we have the default case if nothing elsewas accomplished. It is assumed that there was something funny requested such as arequest to get a monitor. Both of these are legal words but they make no sensetogether.

FINAL COMMENTS ON FLYAWAY

_________________________________________________________________

Now that you have played the game for awhile and studied the game in detail, youshould have an appreciation for how this game can be written. Of course, it could bewritten in any of several thousand different ways of packaging and definition. This hasbeen only one of the ways.

Because the student may be left with the sinking feeling that this method simply fell outof the sky or was arrived at in some other esoteric way, it would only be fair to point outthat several earlier attempts at outlining this project were attempted and rejected priorto 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% ofthe code was in classes, but due to additional programing experience, about 98% ofthe flyaway program is now encapsulated in classes.

Object oriented programming requires the same forethought as non- object orientedprogramming, but the object oriented compiler will help you in the coding anddebugging phase since the compiler will find and flag many of the oversight errors weare so good at introducing into our code. It was observed during the coding anddebugging phase of this project that in nearly every case, when the program finally gotthrough the compiler, the program would actually run without bombing out the system.This is not always the case using any standard procedural programming language.

Page 119: CORONADO ENTERPRISES C++ TUTOR - Version 2 · 2006. 5. 28. · C++ TUTOR - Version 2.2 This documentation and the accompanying software, including all of the example C++ programs

Chapter 12 - Flyaway adventure game––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––12.10

YOUR PROGRAMMING PROJECT

_________________________________________________________________

This programming assignment is intended to give you a little experience in working witha relatively large project as opposed to the very small programs we have been workingwith in this tutorial.

Add a suitcase to the game, to be found in the car at arrival, and which must bechecked in at the ticket counter prior to attempting to get through airport security. Thiswill not be trivial since several classes will be affected. Some of the operations you willhave 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 surethat this is all that will be required, but it should be the majority of effort required. Thebottom line of this effort is that if you understand this program enough to perform thismodification, you have a good understanding of how the program works and howobjects work together to perform a task.

Once you understand this program, you should define a programming project foryourself that will use object oriented programming techniques and begin designing andprogramming it. The best way to learn to use OOP is to actually use it.

Good luck in your OOP endeavors.