Docsity

c++ from zero to hero, Study Guides, Projects, Research of Compilers

Partial preview of the text

Download c++ from zero to hero and more Study Guides, Projects, Research Compilers in PDF only on Docsity!

A Complete Guide to

Programming in C++

Ulla Kirch-Prinz

Peter Prinz

JONES AND BARTLETT PUBLISHERS

Ulla Kirch-Prinz
Peter Prinz

A Complete Guide to

Programming in C++

Dedicated to our children, Vivi and Jeany

This page intentionally left blank

Each double-page spread in the book is organized to provide a description of the lan- guage elements on the right-hand page while illustrating them by means of graphics and sample programs on the left-hand page. This type of visual representation offered by each spread will provide students and professionals with an unmatched guide throughout the text. The sample programs were chosen to illustrate a typical application for each lan- guage element. In addition, filter programs and case studies introduce the reader to a wide range of application scenarios. To gain command over a programming language, students need a lot of experience in developing programs. Thus, each chapter includes exercises followed by sample solu- tions , allowing the reader to test and enhance his or her performance and understanding of C++. The appendix provides further useful information, such as binary number representa- tion, pre-processor directives, and operator precedence tables, making this book a well- structured and intelligible reference guide for C++ programmers. In order to test and expand your acquired knowledge, you can download sample pro- grams and solutions to the exercises at: http://completecpp.jbpub.com

Content Organization Chapter 1 gives a thorough description of the fundamental characteristics of the object- oriented C++ programming language. In addition, students are introduced to the steps necessary for creating a fully functional C++ program. Many examples are provided to help enforce these steps and to demonstrate the basic structure of a C++ program. Chapter 2 provides a complete introduction to the basic types and objects used by C++ programs. Integral types and constants, fundamental types, and Boolean constants are just a few of the topics discussed. Chapter 3 describes how to declare and call standard functions. This chapter also teaches students to use standard classes, including standard header files. In addition, stu- dents work with string variables for the first time in this chapter. Chapter 4 explains the use of streams for input and output, with a focus on formatting techniques. Formatting flags and manipulators are discussed, as are field width, fill char- acters, and alignment. Chapter 5 introduces operators needed for calculations and selections. Binary, unary, relational, and logical operators are all examined in detail. Chapter 6 describes the statements needed to control the flow of a program. These include loops with while, do-while, and for; selections with if-else, switch, and the condi- tional operator; and jumps with goto, continue, and break. Chapter 7 provides a thorough introduction to the definition of symbolic constants and macros, illustrating their significance and use. Furthermore, a comprehensive exami- nation of standard macros for character handling is included. Chapter 8 introduces implicit type conversions, which are performed in C++ when- ever different arithmetic types occur in expressions. Additionally, the chapter explores an operator for explicit type conversion.

vi ■^ P R E F A C E

Chapter 9 takes an in-depth look at the standard class string, which is used to repre- sent strings. In addition to defining strings, the chapter looks at the various methods of string manipulation. These include inserting and erasing, searching and replacing, com- paring, and concatenating strings. Chapter 10 describes how to write functions of your own. The basic rules are covered, as are passing arguments, the definition of inline functions, overloading functions and default arguments, and the principle of recursion. Chapter 11 gives a thorough explanation of storage classes for objects and functions. Object lifetime and scope are discussed, along with global, static, and auto objects. Namespaces and external and static functions are also included in the discussion. Chapter 12 explains how to define references and pointers and how to use them as parameters and/or return values of functions. In this context, passing by reference and read-only access to arguments are introduced. Chapter 13 provides a complete description of how classes are defined and how instances of classes, or objects, are used. In addition, structs and unions are introduced as examples of special classes. Chapter 14 describes how constructors and destructors are defined to create and destroy objects. Also discussed are how inline methods, access methods, and read-only methods can be used. Furthermore, the chapter explains the pointer this, which is avail- able for all methods, and what you need to pay attention to when passing objects as argu- ments or returning objects. Chapter 15 gives a complete explanation of member objects and how they are initial- ized, and of data members that are created only once for all the objects in a class. In addi- tion, this chapter describes constant members and enumerated types. Chapter 16 takes an in-depth look at how to define and use arrays. Of particular inter- est are one-dimensional and multidimensional arrays, C strings, and class arrays. Chapter 17 describes the relationship between pointers and arrays. This includes pointer arithmetic, pointer versions of functions, pointers as return values and read-only pointers, and pointer arrays. Students learn that operations that use C strings illustrate how to use pointers for efficient programming, and that string access via the command line of an application program is used to illustrate pointer arrays. Chapter 18 explains sequential file access using file streams. Students will develop an understanding of how file streams provide simple and portable file handling techniques. Chapter 19 provides a complete description of the various uses of overloaded opera- tors. Arithmetic operators, comparisons, the subscript operator, and the shift operators for input and output are overloaded to illustrate the appropriate techniques. In addition, the concept of friend functions, which is introduced in this context, is particularly important for overloading operators. Students learn how overloading operators allows them to apply existing operators to objects of class type. Chapter 20 discusses how implicit type conversion occurs in C++ when an expression cannot be compiled directly but can be compiled after applying a conversion rule. The programmer can stipulate how the compiler will perform implicit type conversion for classes by defining conversion constructors and functions. Finally, the chapter discusses ambiguity that occurs due to type conversion and how to avoid it.

PREFACE ■^ vii

discussed. Students learn that templates allow the construction of functions and classes based on types that have not yet been stated. Thus, templates are a powerful tool for automating program code generation. Chapter 33 explains standard class templates used to represent containers for more efficient management of object collections. These include sequences, such as lists and double ended queues; container adapters, such as stacks, queues, and priority queues; associative containers, such as sets and maps; and bitsets. In addition to discussing how to manage containers, the chapter also looks at sample applications, such as bitmaps for raster images, and routing techniques.

Additional Features

Chapter Goals A concise chapter introduction, which contains a description of the chapter’s contents, is presented at the beginning of each chapter. These summaries also provide students with an idea of the key points to look for throughout the chapter.

Chapter Exercises Each chapter contains exercises, including programming problems, designed to test students’ knowledge and understanding of the main ideas. The exercises also provide reinforcement for key chapter concepts. Solutions are included to allow students to check their work immediately and correct any possible mistakes.

Case Studies Every chapter contains a number of case studies that were designed to introduce the reader to a wide range of application scenarios.

Notes This feature provides students with helpful tips and information useful to learning C++. Important concepts and rules are highlighted for additional emphasis and easy access.

Hints These are informative suggestions for easier programming. Also included are common mistakes and how to avoid making them.

Acknowledgements

Our thanks go out to everyone who helped produce this book, particularly to

Ian Travis , for his valuable contributions to the development of this book.

Alexa Doehring , who reviewed all samples and program listings, and gave many valuable hints from the American perspective.

Michael Stranz and Amy Rose at Jones and Bartlett Publishers, who managed the pub- lishing agreement and the production process so smoothly.

Our children, Vivi and Jeany , who left us in peace long enough to get things finished! And now all that remains is to wish you, Dear Reader, lots of fun with C++!

Ulla Kirch-Prinz Peter Prinz

PREFACE ■^ ix

This page intentionally left blank

  • Chapter 1 Fundamentals
    • Development and Properties of C++
    • Object-Oriented Programming
    • Developing a C++ Program
    • A Beginner’s C++ Program
    • Structure of Simple C++ Programs
    • Exercises
    • Solutions
  • Chapter 2 Fundamental Types, Constants, and Variables
    • Fundamental Types
    • Constants
    • Escape Sequences
    • Names
    • Variables
    • The Keywords const and volatile
    • Exercises
    • Solutions
  • Chapter 3 Using Functions and Classes
    • Declaring Functions
    • Function Calls
    • Type void for Functions
    • Header Files
    • Standard Header Files
    • Using Standard Classes
    • Exercises
    • Solutions
  • Chapter 4 Input and Output with Streams
    • Streams
    • Formatting and Manipulators
    • Formatted Output of Integers
    • Formatted Output of Floating-Point Numbers
    • Output in Fields
    • Output of Characters, Strings, and Boolean Values
    • Formatted Input
    • Formatted Input of Numbers
    • Unformatted Input/Output
    • Exercises
    • Solutions
  • Chapter 5 Operators for Fundamental Types
    • Binary Arithmetic Operators
    • Unary Arithmetic Operators
    • Assignments
    • Relational Operators
    • Logical Operators
    • Exercises
    • Solutions
  • Chapter 6 Control Flow
    • The while Statement
    • The for Statement
    • The do-while Statement
    • Selections with if-else
    • Else-if Chains
    • Conditional Expressions
    • Selecting with switch
    • Jumps with break, continue, and goto
    • Exercises
    • Solutions
  • Chapter 7 Symbolic Constants and Macros
    • Macros
    • Macros with Parameters
    • Working with the #define Directive
    • Conditional Inclusion
    • Standard Macros for Character Manipulation
    • Redirecting Standard Input and Output
    • Exercises
    • Solutions
  • Chapter 8 Converting Arithmetic Types
    • Implicit Type Conversions
    • Performing Usual Arithmetic Type Conversions
    • Implicit Type Conversions in Assignments
    • More Type Conversions
    • Exercises
    • Solutions
  • Chapter 9 The Standard Class string
    • Defining and Assigning Strings
    • Concatenating Strings
    • Comparing Strings
    • Inserting and Erasing in Strings
    • Searching and Replacing in Strings
    • Accessing Characters in Strings
    • Exercises
    • Solutions
  • Chapter 10 Functions
    • Significance of Functions in C++
    • Defining Functions
    • Return Value of Functions
    • Passing Arguments
    • Inline Functions
    • Default Arguments
    • Overloading Functions
    • Recursive Functions
    • Exercises
    • Solutions
  • Chapter 11 Storage Classes and Namespaces
    • Storage Classes of Objects
    • The Storage Class extern
    • The Storage Class static
    • The Specifiers auto and register
    • The Storage Classes of Functions
    • Namespaces
    • The Keyword using
    • Exercises
    • Solutions
  • Chapter 12 References and Pointers
    • Defining References
    • References as Parameters
    • References as Return Value
    • Expressions with Reference Type
    • Defining Pointers
    • The Indirection Operator
    • Pointers as Parameters
    • Exercises
    • Solutions
  • Chapter 13 Defining Classes
    • The Class Concept
    • Defining Classes
    • Defining Methods
    • Defining Objects
    • Using Objects
    • Pointers to Objects
    • Structs
    • Unions
    • Exercise
    • Solution
  • Chapter 14 Methods
    • Constructors
    • Constructor Calls
    • Destructors
    • Inline Methods
    • Access Methods
    • const Objects and Methods
    • Standard Methods
    • this Pointer
    • Passing Objects as Arguments
    • Returning Objects
    • Exercises
    • Solutions
  • Chapter 15 Member Objects and Static Members
    • Member Objects
    • Member Initializers
    • Constant Member Objects
    • Static Data Members
    • Accessing Static Data Members
    • Enumeration
    • Exercises
    • Solutions
  • Chapter 16 Arrays
    • Defining Arrays
    • Initializing Arrays
    • Arrays
    • Class Arrays
    • Multidimensional Arrays
    • Member Arrays
    • Exercises
    • Solutions
  • Chapter 17 Arrays and Pointers
    • Arrays and Pointers (1)
    • Arrays and Pointers (2)
    • Pointer Arithmetic
    • Arrays as Arguments
    • Pointer Versions of Functions
    • Read-Only Pointers
    • Returning Pointers
    • Arrays of Pointers
    • Command Line Arguments
    • Exercises
    • Solutions
  • Chapter 18 Fundamentals of File Input and Output
    • Files
    • File Streams
    • Creating File Streams
    • Open Modes
    • Closing Files
    • Reading and Writing Blocks
    • Object Persistence
    • Exercises
    • Solutions
  • Chapter 19 Overloading Operators
    • Generals
    • Operator Functions (1)
    • Operator Functions (2)
    • Using Overloaded Operators
    • Global Operator Functions
    • Friend Functions
    • Friend Classes
    • Overloading Subscript Operators
    • Overloading Shift-Operators for I/O
    • Exercises
    • Solutions
  • Chapter 20 Type Conversion for Classes
    • Conversion Constructors
    • Conversion Functions
    • Ambiguities of Type Conversions
    • Exercise
    • Solution
  • Chapter 21 Dynamic Memory Allocation
    • The Operator new
    • The Operator delete
    • Dynamic Storage Allocation for Classes
    • Dynamic Storage Allocation for Arrays
    • Application: Linked Lists
    • Representing a Linked List
    • Exercises
    • Solutions
  • Chapter 22 Dynamic Members
    • Members of Varying Length
    • Classes with a Dynamic Member
    • Creating and Destroying Objects
    • Implementing Methods
    • Copy Constructor
    • Assignment
    • Exercises
    • Solutions
  • Chapter 23 Inheritance
    • Concept of Inheritance
    • Derived Classes
    • Members of Derived Classes
    • Member Access
    • Redefining Members
    • Constructing and Destroying Derived Classes
    • Objects of Derived Classes
    • Protected Members
    • Exercises
    • Solutions
  • Chapter 24 Type Conversion in Class Hierarchies
    • Converting to Base Classes
    • Type Conversions and Assignments
    • Converting References and Pointers
    • Explicit Type Conversions
    • Exercises
    • Solutions
  • Chapter 25 Polymorphism
    • Concept of Polymorphism
    • Virtual Methods
    • Destroying Dynamically Allocated Objects
    • Virtual Method Table
    • Dynamic Casts
    • Exercises
    • Solutions
  • Chapter 26 Abstract Classes
    • Pure Virtual Methods
    • Abstract and Concrete Classes
    • Pointers and References to Abstract Classes
    • Virtual Assignment
    • Application: Inhomogeneous Lists
    • Implementing an Inhomogeneous List
    • Exercises
    • Solutions
  • Chapter 27 Multiple Inheritance
    • Multiply-Derived Classes
    • Multiple Indirect Base Classes
    • Virtual Base Classes
    • Constructor Calls
    • Initializing Virtual Base Classes
    • Exercises
    • Solutions
  • Chapter 28 Exception Handling
    • Traditional Error Handling
    • Exception Handling
    • Exception Handlers
    • Throwing and Catching Exceptions
    • Nesting Exception Handling
    • Defining Your Own Error Classes
    • Standard Exception Classes
    • Exercises
    • Solutions
  • Chapter 29 More About Files
    • Opening a File for Random Access
    • Positioning for Random Access
    • File State
    • Exception Handling for Files
    • Persistence of Polymorphic Objects
    • Application: Index Files
    • Implementing an Index File
    • Exercises
    • Solutions
  • Chapter 30 More About Pointers
    • Pointer to Pointers
    • Variable Number of Arguments
    • Pointers to Functions
    • Complex Declarations
    • Defining Typenames
    • Application: Dynamic Matrices
    • Exercises
    • Solutions
  • Chapter 31 Manipulating Bits
    • Bitwise Operators
    • Bitwise Shift Operators
    • Bit Masks
    • Using Bit Masks
    • Bit-Fields
    • Exercises
    • Solutions
  • Chapter 32 Templates
    • Function and Class Templates
    • Defining Templates
    • Template Instantiation
    • Template Parameters
    • Template Arguments
    • Specialization
    • Default Arguments of Templates
    • Explicit Instantiation
    • Exercises
    • Solutions
  • Chapter 33 Containers
    • Container Types
    • Sequences
    • Iterators
    • Declaring Sequences
    • Inserting in Sequences
    • Accessing Objects
    • Length and Capacity
    • Deleting in Sequences
    • List Operations
    • Associative Containers
    • Sets and Multisets
    • Maps and Multimaps
    • Bitsets
    • Exercise
    • Solution
    • Appendix
    • Binary Numbers
    • Preprocessor Directives
    • Pre-Defined Standard Macros
    • Binding C Functions
    • Operators Overview
    • Operator Precedence Table
    • ASCII Code Table
    • Screen Control Sequences
    • Literature
    • Index