Supercharge your creative energy by recognizing and utilizing the power of the “flow” Quickly master multi-file programming techniques to help tame project complexity Utilize the project
Trang 1C++ For Artists: The Art, Philosophy, and Science
of Object-Oriented Programming
by Rick Miller ISBN:1932504028Biblio Distribution © 2003 (590pages)
Intended as both a classroom and reference text, this book breaks all molds by being the first book of its kind
specifically designed to help readers tap their creative energy to understand and apply difficult programming concepts.
Table of Contents
C++ For Artists—The Art, Philosophy, and Science of Object-Oriented Programming
Trang 3List of Examples
Trang 4help you smash through the barriers preventing you from mastering the complexities of object-oriented
programming in C++ Start taming complexity now!
Read C++ for Artists today—energize your
programming skills for life!
Supercharge your creative energy by recognizing and utilizing the power of the “flow”
Quickly master multi-file programming techniques
to help tame project complexity
Utilize the project approach strategy to maintain programming project momentum
Use the Student Survival Guide to help tackle any project thrown at you
Learn a development cycle you can actually use at work
Trang 5Learn how to incorporate assembly language
routines in your C++ code
Master three object-oriented design principles that will greatly improve your software architectures Painlessly conquer pointers and references with the help of C++ Man
Packed with over 43 tables, 216 illustrations, and
415 code examples
Reinforce your learning with the help of chapter learning objectives, skill-building exercises,
suggested projects, and self-test questions
All code examples were compiled and executed
before being used in the book to guarantee quality And much, much, more…
About the Author
Rick Miller is a Senior Software Systems Engineer and Web Applications Architect for Science Applications
International Corporation (SAIC), and Assistant
Professor at Northern Virginia Community College,
Annandale Campus, where he teaches C++ and Java programming classes.
Trang 6Publisher Cataloging-in-Publication Data: Prepared by Pulp Free Press
Miller, Rick, 1961 -C++ For Artists: The Art, Philosophy, and Science of Object-OrientedProgramming/Rick Miller
Trang 7C++ For Artists was meticulously crafted on a Macintosh PowerMac G4using Adobe FrameMaker, Adobe Illustrator, Macromedia Freehand,Adobe Photoshop, Adobe Acrobat, Embarcadero Technologies Describe,ObjectPlant, Microsoft Word, Maple, and VirtualPC Photos were takenwith a Nikon F3HP, a Nikon FM, a Nikon CoolPix 800 and a Contax T3.C++ source code examples were prepared using Metrowerks
CodeWarrior for Macintosh, Apple OSX developer tools, and Tenon
Intersystems CodeBuilder Java code examples prepared using Sun’sJava 2 Standard Edition (J2SE) command line tool suite Assembly
language examples prepared using Microsoft Macro Assembler (MASM).ISBN 1-932504-00-1 First eBook/PDF Edition
ISBN 1-932504-01-X First CD ROM Edition
ISBN 1-932504-02-8 First Paperback Edition
Trang 8Preface
Trang 9Thank you for choosing C++ For Artists: The Art, Philosophy, and
Science of Object-Oriented Programming You have selected an
excellent book to augment your C++ and object-oriented programminglearning experience
If you purchased this book because it is required for a course you mayfeel like you had no say in the matter Paying for expensive college booksfeels a lot like having your arm twisted behind your back at the checkoutcounter If it will make you feel better I will let you in on a secret Youbought a keeper
If you are standing in the computer section of your favorite book storereading these lines and trying hard to decide if you should buy this book
or pay the rent I say to you this: If you knew the stuff inside this book youcould easily own your own place The landlord can wait
Trang 10C++ For Artists targets the student who demands more from a C++
programming textbook What do I mean by student? A student is anyonewho holds this book in their hands and by reading it expects to gain C++and object-oriented programming knowledge You may be a studentenrolled in a high school, college, or university — or a practicing
programmer seeking ways to expand your understanding of C++ andobject-oriented programming However you come to hold this book inyour hands — you are my target audience
Trang 11C++ For Artists examines the topic of C++ and object-oriented
programming from three unique perspectives
First, programming is an art It takes lots of skill (gained through studyand training) and practice (gained from writing code) to succeed as aprogrammer Talent separates the good programmers from the reallygreat programmers Just like some people have a knack for painting,some people have a knack for programming
Second, object-oriented programmers can significantly benefit from aguiding philosophy One that shows them how to tap their creativity,conquer challenges, and tame conceptual and physical complexity
associated with large software systems
Lastly, most programming students are not formally exposed to real-life,practical programming techniques and almost no object-oriented
foundational theory during their tenure in the classroom
These three perspectives: 1) programmer as artist, 2) creative approach
philosophy, and 3) object-oriented programming theory, converge in C++
For Artists resulting in a truly unique programming text book.
Trang 12The book is arranged into four parts: Part I: The C++ Student Survival Guide, Part II : Language Fundamentals, Part III: Implementing
Polymorphic Behavior, and Part IV: Intermediate Concepts Each partand its accompanying chapters are described in greater detail below
A complete treatment on how to create C++ projects with twopopular integrated development environments (IDEs) on
Macintosh, Windows, and UNIX platforms,
A step-by-step project walkthrough that applies the project
approach strategy and development cycle to produce a completeworking project
Chapter 1: An Approach To The Art Of Programming
Chapter 1 begins with a discussion of the challenges you will face as youstudy C++ and object-oriented programming It presents a project
approach strategy specifically designed to help you maintain a sense offorward momentum when tackling your first programming projects Thechapter also presents a development methodology, a philosophical
discussion of the concept of the “flow”, and practical advice on how tomanage a programming project’s physical and conceptual complexity Iwill show you how to use three important preprocessor directives: #ifndef,
Trang 13be familiar with all the terms used in the chapter, especially those related
to preprocessor directives and identifier naming, however, you are
encouraged to return to the chapter as required It serves to offer you aglimpse of things to come
Chapter 2: Small Victories: Creating Projects With IDEs
Chapter 2 shows you step-by-step how to create C++ projects using twopopular integrated development environments: Metrowerks CodeWarrior
on the Macintosh, and Microsoft Visual C++ for the Windows platform.The focus of the chapter is the concept of the project and the steps
required to create projects regardless of the IDE employed If you prefer
to use UNIX development tools this chapter also shows you how to usethe make utility and how to create a makefile that can be used to compile,link, and manage multi-file projects
Chapter 3: Project Walkthrough: An Extended Example
Chapter 3 takes you step-by-step through a complete programming
project from specification to final implementation Along the way you areshown how to apply the project approach strategy and the developmentcycle to arrive at an acceptable project solution The #ifndef, #define, and
#endif preprocessor directives are used to create safe header files thatseparate function interface declarations from function implementationcode If you are a novice student I do not expect you to fully comprehendall the material or programming techniques presented in this chapter,rather, the material serves as an excellent reference to which you willreturn periodically as you use bits and pieces of this knowledge in yourprogramming projects
Chapter 4: Computers, Programs, and Algorithms
Chapter 4 presents background information on computer hardware
organization, memory systems, and algorithms The emphasis is on
understanding exactly what a program is from a computer and humanperspective I discuss the four phases of the program execution cycle,how program instructions are differentiated from ordinary data, and how
Trang 14Part II: C++ Language Fundamentals
Part II presents a treatment of the core C++ programming languagefeatures and comprises chapters 5 through 13 This is a critical part ofthe book because it prepares you for further study of intermediate andadvanced C++ and object-oriented concepts The key features and
discussion points of part II include:
The unique ordering of the material For instance, pointers arecovered early so you will understand their use in other languageconstructs,
Pointers are presented as a dialog between a superhero namedC++ Man and a confused student named Perplexed One,
Emphasis on multi-file projects,
Lots of targeted code examples to reinforce key lecture points,Successive chapters build upon knowledge gained from the
previous chapter,
In-depth coverage of tricky concepts normally glossed over oravoided in ordinary C++ texts
Chapter 5: Simple Programs
Chapter 5 shows you how to write simple C++ programs using
fundamental data types and simple expressions I give examples of how
to use all the C++ operators, how to create local and multi-file variablesand constants, and show you how you can limit a variable’s scope to onefile You will learn how to write two versions of the main() function andhow to call functions upon program exit
Chapter 6: Controlling The Flow Of Program Execution
Trang 15statements, and how to write loops that will repeat until explicitly exited
Chapter 7: Pointers And References
Chapter 7 uses a short story to simplify the complex topic of pointers andreferences Perplexed One is a student who falls asleep in class and isawakened by the arrival of C++ Man C++ Man then helps PerplexedOne by answering questions and giving examples of how to declare anduse pointers
Chapter 8: Arrays
Chapter 8 builds upon chapter 7 and shows the relationship betweenpointers and arrays The chapter continues by showing you how to buildsingle and multi-dimensional static and dynamic arrays Lots of codeexamples and diagrams help you visualize how arrays are declared,initialized, and used in programs
support the creation of header files I review and discuss the three
important preprocessor directives: #ifndef, #define, and #endif Othertopics covered include: function variable scoping, static function
variables, passing arrays to functions, passing multi-dimensional arrays
to functions, returning pointers from functions, how to avoid danglingreferences, function overloading, recursion, function pointers, and callback functions
Trang 16Chapter 10: Toward Problem Abstraction: Creating New Data Types
Chapter 10 shows you how to create type synonyms and new data typesusing type definitions, enumerated types, structures, and classes Theemphasis is on problem abstraction and how it is used to map a realworld problem to a set of supporting data structures that can be used in aprogram Structures are compared to classes and the notion of object-oriented programming is introduced The class declaration is discussed
as it relates to the structure declaration and how the notions of
procedural and object-oriented programming differ from each other
Chapter 11: Dissecting Classes
Chapter 11 continues the discussion of classes and how they work Itintroduces the UML class diagram and uses UML class diagrams to
illustrate static class relationships The special member functions arethoroughly discussed These include the constructor, destructor, copyconstructor, and copy assignment operator A brief introduction to theorthodox canonical class form is given in preparation for a deeper
treatment of the subject in chapter 17 Other topics include data
encapsulation, member functions and attributes, access specifiers,
member function overloading, and how to separate class interface fromimplementation
Chapter 12: Compositional Design
Chapter 12 builds upon chapter 11 and shows you how to build complexclass types using simple and complex aggregation The UML class
diagram is extended to model simple and composite aggregate classrelationships The UML sequence diagram is also introduced to illustrateinterobject message passing Other topics discussed include: managingphysical complexity, the use of pointers and references to build simpleand complex aggregate classes, and how to properly use constructorsand destructors in aggregate classes The chapter concludes with a
complex aggregation example
Chapter 13: Extending Class Functionality Through
Trang 17Chapter 13 introduces the topic of inheritance and shows you how toextend class behavior through subclassing and subtyping UML is used
to illustrate simple and complex inheritance hierarchies The
compositional design techniques discussed in chapter 12 are combinedwith inheritance design concepts to provide you with a powerful arsenal
of object-oriented design tools The access specifiers public, protected,and private are discussed in the context of inheritance Other topics
covered include: virtual functions, function hiding, function overloading,pure virtual functions, abstract classes, abstract base classes, multipleinheritance, and virtual inheritance The chapter includes a complex navyfleet simulation example that illustrates the use of inheritance and
compositional design
Part III: Implementing Polymorphic Behavior
Part III gives special coverage to the three types of polymorphic behavior:
ad hoc (operator overloading), static (templates), and dynamic (baseclass pointers to derived class objects) Success as a C++ programmerdemands a thorough understanding of these concepts Key features anddiscussion points of part III include:
In-depth treatment of ad-hoc, static, and dynamic polymorphismand how each type of polymorphic behavior is achieved using theC++ language,
An example of how to overload almost every operator in the C++language,
How to overload the iostream operators to tailor them to yourclass needs,
How to think about and apply the notion of polymorphic behavior
in your application designs,
How to write generic code using templates,
How to use multiple place holders in template classes and
Trang 18How to use the special template definition syntax to explicitlyspecify template parameter types,
How to design with dynamic polymorphic behavior in mind
Chapter 14: Ad Hoc Polymorphism: Operator Overloading
Chapter 14 is devoted to operator overloading It builds upon the
concepts of function overloading and shows you how to overload nearlyevery operator in the C++ language complete with examples of their use
A complete table of overloadable operators is included along with a
discussion of how to overload the iostream operators to tailor them toyour class needs
Chapter 15: Static Polymorphism: Templates
Chapter 15 shows you how to write generic code using templates It
shows you how to replace overloaded functions with template functionsand how to use template functions in your programs The chapter alsoshows you how to use the special template definition syntax to explicitlyspecify template parameter types A brief overview of the C++ standardtemplate library (STL) is offered along with a discussion of STL
behavior to expect when using dynamic polymorphic programming
techniques The engine component aggregate class created in chapter
12 is revisited and redesigned to employ dynamic polymorphic behavior
Trang 19How to use assembly language in C++ programs,
Coverage of three important object-oriented design concepts toinclude the Liskov substitution principle and Meyer design bycontract programming, the open-closed principle, and the
Keeping the OCCF in mind when you design and write classes forcesyou to consider how those classes will be used in an application Theclass’s possible uses or usage contexts will guide you in your choice ofwhich operators to overload to insure your class objects exhibit
predictable and acceptable behavior
Chapter 18: Mixed Language Programming
Trang 20Chapter 20: Using A UML Modeling Tool
Chapter 20 discusses the importance of using a UML design tool to
assist in the application design process The featured UML tool is
Embarcadero Technologies’s Describe™ The chapter focuses on only afew of Describe’s many features: UML use-case, class, and sequencediagram creation, how to link diagram objects to other diagrams, how togenerate code from class diagrams, how to reverse engineer existingC++ code, and how to generate comprehensive web-based project
reports
Trang 21The flow chart below is intended to give you an idea of how to read C++For Artists If you are a complete novice or first-time reader of C++ ForArtists I recommend starting with part I There you will find much to helpyou undertake significant programming projects Read part II repeatedly
to ensure you have a firm grasp of C++ fundamental language featuresbefore attempting parts III and IV
Trang 22Summary
Trang 23Skill Building Exercises
Skill building exercises are small programming or other activities intended
to strengthen your C++ programming capabilities in a particular area.They could be considered focused micro-projects
Suggested Projects
Suggested projects require the application of a combination of all
knowledge and skills learned up to and including the current chapter tocomplete Suggested projects offer varying degrees of difficulty
Self Test Questions
Self-test questions test your comprehension on material presented in thecurrent chapter Self-test questions are directly related to the chapterlearning objectives Answers to all self-test questions appear in appendix
Trang 24The CD-ROM contains the following goodies:
PDF edition of C++ For Artists,
Adobe Acrobat™ Reader version 6 for Windows and MacintoshDemo version of Embarcadero Technologies Describe™ UMLmodeling tool,
Full working copy of ObjectPlant™ UML modeling tool for theMacintosh™,
Trang 25The C++ For Artists SupportSite™ is located at
[http://pulpfreepress.com/SupportSites/C++ForArtists/] The support siteincludes source code, links to C++ compiler and UML tool vendors, andcorrections and updates to the text
Trang 26Although every possible effort was made to produce a work of superiorquality some mistakes will no doubt go undetected All typos,
misspellings, inconsistencies, or other problems found in C++ For Artistsare mine and mine alone To report a problem or issue with the text
please contact me directly at rick@pulpfreepress.com or report the
problem via the C++ For Artists SupportSite™ I will happily acknowledgeyour assistance in the improvement of this book both online and in
subsequent editions
Trang 27Many thanks to my good friend Jose Pi for many great mornings spent surfing California waves, and to Michael Leahy, a merchant mariner of
talented people
I want to thank Apple™ Computer Inc., for providing product images of the PowerMac™, Motorola, Inc for providing images of the PowerPC
7400 and related architecture diagrams, Embarcadero Technologies,
Inc., for granting me a full-use license of Describe™, and Michael
Archtadeous for working in the trenches to produce ObjectPlant™.
Lastly, without the fathomless patience of Coralie Miller, an amazing
Trang 28Falls Church, Virginia
7 July 2003
Trang 29Part I: The C++ Student Survival Guide
Trang 31Chapter 1: An Approach To The Art Of Programming
Trang 32Identify and overcome the difficulties encountered by studentswhen learning how to program
List and describe the two types of C++ comments
Trang 33Programming is an art; there’s no doubt about it Good programmers areartists in every sense of the word They are a creative bunch, althoughsome would believe themselves otherwise out of modesty Like any artyou can learn the secrets of the craft That is what this chapter is all
about
Perhaps the most prevalent personality trait I have noticed in good
programmers is a knack for problem solving Problem solving requirescreativity, and lots of it When you program a computer you are solving aproblem with a machine You transfer your knowledge of a particular
problem into code, transform the code into a form understandable by amachine, and run the result on a machine Doing this requires lots ofcreativity, especially when you find yourself stumped by a particular
problem
The material presented here is wrought from experience Believe it ornot, the hardest part about learning to program a computer, in any
programming language, is not the learning of the language itself, rather, it
is learning how to approach the art of problem solving with a computer
To this end the material in this chapter is aimed squarely at the beginner.However, I must issue a word of warning If you are truly a novice, thensome of what you read in this chapter will make less sense to you than tosomeone already familiar with C or C++ Do not worry, it is that way bydesign If you feel like skipping parts of this chapter now, then go rightahead The material will be here when you need it In fact, you will grow
to appreciate this chapter more as you gain experience as a programmer
The Difficulties You Will Encounter Learning C++
During your studies of the C++ programming language you will face
many challenges and frustrations However, the biggest problem you willencounter is not the learning of the language itself, but the many otherskills and tools you must learn before writing programs of any
significance or gaining any measure of proficiency in solving problems
Trang 34professional returning to the classroom to upgrade your skills, you havethe advantage of experience You can concentrate on learning the syntaxand nuances of C++ and very quickly apply its powers to problems athand If you are an absolute beginner, however, you have much to learn
Required Skills
In addition to the syntax and semantics of the C++ language you willneed to master the following skills and tools:
A development environment, which could be as simple as a texteditor and compiler combination or a commercial product thatintegrates editing, compiling, and project management
Trang 35a great feeling!
How This Chapter Will Help You
This chapter will give you the information you need to bring the planetsinto alignment sooner rather than later It presents an abbreviated
software development methodology that formalizes the three primaryroles you play as a programming student It will discuss some
philosophical topics related to tapping into your creative energies It willoffer several strategies to help you manage project complexity,
something you will not need for very small projects but should get into thehabit of doing as soon as possible
I recommend you read this chapter at least once in its entirety and referback as necessary as you progress through the text and attempt
increasingly difficult programming assignments
Trang 36Three Software Development Roles
You will find yourself assuming the duties and responsibilities of threesoftware development roles: Analyst, Architect, and Programmer
Analyst
When you are handed a class programming project you may or may notunderstand what the instructor is actually asking you to program Hey, ithappens! Whatever the case may be, you, as the student, must read theassignment and design and implement a solution
You can think of a project assignment as a requirements specification.They will come in several flavors Some instructors go into painful detailabout how they want the student to execute the project Others prefer togenerally describe the type of program they want thus leaving the details,and the creativity, up to you There is no one correct method of writing aproject assignment; each has its benefits and limitations
A detailed assignment takes a lot of the guesswork out of what outcomethe instructor expects On the other hand, having every design decisionmade for you may prevent you from solving the problem in a unique,
creative way
A general project assignment delegates a lot of decision making to thestudent while also adding the responsibility of determining what projectfeatures will satisfy the assignment
Both types of assignments model the real world to some extent
Sometimes requirements are well defined and there is little doubt whatshape the final product will take and how it must perform However, moreoften than not requirements are ill or vaguely defined As an analyst youmust clarify what is being asked of you In an academic setting, do this bytalking to the instructor and have them clarify the assignment A clearunderstanding of the assignment will yield valuable insight into possible
Trang 37Architect
Once you understand the assignment you must design a solution If yourproject is extremely small you could perhaps skip this step with no
problem However, if your project contains several objects that interactwith each other, then your design, and the foundation it sets, could makethe difference between success and failure A well-designed project
reflects a subliminal quality that poorly designed projects do not
Two objectives of good design are the ability to accommodate changeand tame complexity Change in this context means the ability to
incrementally add features to your project as it grows without breakingthe code you have already written Several important object-orientedprinciples have been formulated to help tame complexity and will be
discussed later in the book For starters though, begin by imposing agood organization upon your source code files You can use the sourcecode file formats presented below to help in this endeavor
Programmer
As programmer you will execute your design The important thing to notehere is that if you do a poor job as an architect your life as a programmerwill be miserable That doesn’t mean the design has to be perfect I willshow you how to incrementally develop and make improvements to yourdesign as you code
Now that you know what roles you will play as a student let us discusshow you might approach a project
A Project Approach Strategy
Most students have difficulty implementing their first significant
programming assignment, not because they lack brains or talent, butbecause they lack experience If you are a novice and feel overwhelmed
by your first programming project rest assured you are not alone Thegood news is that with practice, and some small victories, you will quickly
Trang 38Even experienced programmers may not immediately know how to solve
a problem or write a particular piece of code when tasked to do so Whatthey do know, however, is how to formulate a strategy to solve the
problem
You Have Been Handed A Project — Now What?
Until you gain experience and confidence in your programming abilitiesthe biggest problem you will face when given a large programming
assignment is where to begin What you need to help you in this situation
is a project approach strategy The strategy is presented below and
discussed in detail I have also summarized the strategy in a checklistlocated in appendix A Feel free to reproduce the checklist and use asrequired
The project approach strategy is a collection of areas of concern to takeinto consideration when you begin a programming project It is not ahard, fast list of steps you must take It is intended to put you in control,
to point you in the right direction, and give you food for thought It is
flexible You will not have to consider every area of concern for everyproject After you have used it a few times to get you started you may notever use it explicitly again As your programming experience grows feelfree to tailor the project approach strategy to suit your needs
Strategy Areas of Concern
The project approach strategy is formulated around areas of concern.These include requirements, problem domain, language features, anddesign When you use the strategy to help you solve a programmingproblem your efforts become focused and organized rather than ad hocand confused You will feel like you are making real progress rather thandrowning in a sea of confusion
Requirements
A requirement is an assertion that specifies a particular aspect of
Trang 39understand the project specification Seek clarification if you do not know,
or if you are not sure, what problem the project specification is asking you
to solve In my academic career I have seen projects so badly written that
I thought I had a comprehension problem I’d read the thing over andover again until struck by a sudden flash of inspiration But more oftenthan not I would reinforce what I believed an instructor required by
discussing the project with them
Problem Domain
The problem domain is the specific problem you are tasked to solve Iwould say that it is that body of knowledge necessary to implement asoftware solution apart and distinct from the knowledge of programmingitself For instance, “Write a program to simulate elevator usage in a
skyscraper.” You may understand what is being asked of you
(requirements understanding) but not know anything about elevators,skyscrapers, or simulations (problem domain) You need to become
enough of an expert in the problem domain you are solving so that youunderstand the issues involved
Programming Language Features
The source of greatest frustration to novice students at this stage of theproject is knowing what to design but not knowing enough of the
language features to begin the design This is when panic sets in andstudents begin to buy extra books in hopes of discovering the Holy Grail
of project wisdom
To save yourself from panic make a list of the language features you
need to understand and study each one, marking them off as you go.This provides focus and a sense of progress As you read about eachfeature, keep notes on their usage so you can refer to them when you sitdown to formulate your program design
Design
When you are ready to design a solution you will usually be forced to
Trang 40object-oriented
Procedural Design
A procedural design approach is one in which you identify and implementprogram data structures separate from the functions that manipulate
those data structures When taking a procedural approach to a solutionyou will break the problem into small, easily solvable pieces, implementthe solution to each of the pieces, and combine the solved pieces into acomplete problem solution The solvable pieces I refer to here are
functions This methodology is also known as functional decomposition
Object-Oriented Design
Object-oriented design refers to designing with objects and their
interfaces Whereas a procedural design treats data structures separatelyfrom the functions that manipulate them, object-oriented design usesencapsulation to hide an object’s implementation data structures behind
a public interface Data structures and the functions that manipulate themcombine to form classes from which objects can then be created
A problem solved with an object-oriented approach is decomposed into aset of objects and their behavior Design tools such as the Unified
Modeling Language (UML) can be used to help with this task Once theobjects in a system are identified, a set of interface functions is then
identified for each object Classes are declared and defined to implementthe interface functions Once all the program classes have been
designed and written, they are combined and used together to form thefinal program Note that when using the object-oriented approach you arestill breaking a problem into solvable pieces, only now the solvable
pieces are objects that represent the interrelated parts of a system
Once you get the hang of object-oriented design you will never return tofunctional decomposition again However, after having identified the
objects in your program and the interfaces they should have, you willhave to implement your design This means writing class member
functions one line of code at a time