11
C++ from the Ground Up Herbert Schildt Osborne McGraw-Hill Berkeley New York St. Louis San Francisco Auckland Bogota Hamburg London Madrid Mexico City Milan Montreal New Delhi Panama City Paris Säo Paulo Singapore Sydney Tokyo Toronto

C++ from the Ground Up - GBV

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: C++ from the Ground Up - GBV

C++ from the Ground Up

Herbert Schildt

Osborne McGraw-Hill Berkeley New York St. Louis San Francisco Auckland Bogota Hamburg London Madrid Mexico City

Milan Montreal New Delhi Panama City Paris Säo Paulo Singapore Sydney Tokyo Toronto

Page 2: C++ from the Ground Up - GBV

Table of Contents

Introduction xv

1 The Story of C++ 1 The Origins of C++ 2

The Creation of C 2 Understanding the Need For C++ 4 C++ is Born 5

What Is Object-Oriented Programming? 6 Encapsulation 7 Polymorphism 7 Inheritance 8 C++ Implements OOP 8

What You Will Need 9

2mm- An Overview of C++ 11 Your First C++ Program 12

A Line-by-Line Explanation 12 Handling Errors 14 A Second Simple Program 15 A More Practical Example 17 A New Data Type 18 A Quick Review 19 Functions 19

A Program with Two Functions 20 Function Arguments 21

Functions Returning Values 23

Page 3: C++ from the Ground Up - GBV

The main( ) Function 25 The General Form of C++ Functions 25

Some Output Options 26 Two Simple Commands 27

The if Statement 27 The for Loop 28

Blocks of Code 29 Semicolons and Positioning 30 Indentation Practices 31 C++ Keywords 31 Identifiers in C++ 32 The Standard C++ Library 33

3 warn Introducing Variables, Constants, and Operators 35

The Basic Data Types 36 Declaration of Variables 37

Local Variables 37 Formal Parameters 38 Global Variables 39

Some Type Modifiers 40 Constants 43

Hexadecimal and Octal Constants 44 String Constants 44 Backslash Character Constants 45

Variable Initializations 45 Operators 47

Arithmetic Operators 47 Increment and Decrement 48 Relational and Logical Operators 50

Expressions 54 Type Conversion in Expressions 54 Casts 54 Spacing and Parentheses 56

4 n s « Program Control Statements 59 The if Statement 60

The Conditional Expression 61 Nested ifs 62 The if-else-if Ladder 63

Page 4: C++ from the Ground Up - GBV

The for Loop 65 Some Variations on the for Loop 67 Missing Pieces 68 The Infinite Loop 69 Time Delay Loops 69

The switch Statement 70 Nested switch Statements 73

The while Loop 74 The do-while Loop 76 Using continue 77 Using break to Exit Loops 78 Nested Loops 79 Using the goto Statement 80 Putting Together the Pieces 81

5 Arrays a n d Str ings 85 One-dimensional Arrays 86

No Bounds Checking 88 Strings 91

Reading a String from the Keyboard 91 Some String Library Functions 93

strcpy 93 strcat 94 strcmp 94 Strien 96 Using the Null Terminator 98

Two-dimensional Arrays 99 Multidimensional Arrays 101 Array Initialization 101

Unsized Array Initializations 104 Arrays of Strings 105

An Example Using String Arrays 107

6msm Po in ters I l l What Are Pointers? 112 The Pointer Operators 112

The Base Type Is Important 114 Assigning Values Through a Pointer 116

Pointer Expressions 117 Pointer Arithmetic 117

Page 5: C++ from the Ground Up - GBV

Pointer Comparisons 118 Pointers and Arrays 119

Indexing a Pointer 122 Are Pointers and Arrays Interchangeable? 123

String Constants 123 A Comparison Example 124 Arrays of Pointers 125 The Null Pointer Convention 128 Multiple Indirection 129 Problems with Pointers 130

Uninitialized Pointers 131 Invalid Pointer Comparisons 131 Forgetting to Reset a Pointer 132

7 Inas Functions, Part One: The Fundamentals 137 Scope Rules of Functions 138

Local Variables 138 Formal Parameters 142 Global Variables 143

Passing Pointers and Arrays 145 Calling Functions with Pointers 145 Calling Functions with Arrays 147 Passing Strings 150

arge and argv: Arguments to main( ) 151 Passing Numeric Command4ine Arguments 155

They return Statement 156 Returning from a Function 157 Returning Values 158 void Functions 160 Functions that Return Pointers 161

Function Prototypes 162 Header Files: A Closer Look 164 Recursion 166

8 Functions, Part Two: References, Overloading, and Default Arguments 171

Two Approaches to Argument Passing 172 How C++ Passes Arguments 172 Using a Pointer to Create a CalFby-Reference 173

Page 6: C++ from the Ground Up - GBV

Reference Parameters 174 Returning References 179 Creating a Bounded Array 182 Independent References 183 A Few Restrictions When Using References 184

Function Overloading 185 Default Function Arguments 188

Default Arguments Versus Overloading 191 Using Default Arguments Correctly 192

Function Overloading and Ambiguity 192

9 H I More D a t a Types a n d Operators 197 The Access Modifiers 198

const 198 volatile 200

Storage Class Specifiers 201 auto 202 extern 202 static Variables 203 register Variables 207

Enumerations 209 bool 212 typedef 212 More Operators 213 Bitwise Operators 213

AND, OR, XOR, and NOT 214 The Shift Operators 217

The ? Operator 219 C++ Shorthand 221 The Comma Operator 221 Multiple Assignments 222 Using sizeof 223 Dynamic Allocation Using new and delete 224

Initializing Dynamically Allocated Memory 226 Allocating Arrays 227

Precedence Summary 230

10 H M S tructures a n d U n i o n s 233 Structures 234

Accessing Structure Members 236

Page 7: C++ from the Ground Up - GBV

Arrays of Structures 237 A Simple Inventory Example 237 Passing Structures to Functions 245 Assigning Structures 246 Pointers to Structures and the Arrow

Operator 247 References to Structures 251 Arrays and Structures Within Structures 252 Bit-Fields 254

Unions 257 Anonymous Unions 262 Using sizeof to Ensure Portability 263

Moving On to Object-Oriented Programming 264

1 1 H H Introducing the Class 267 Class Fundamentals 268 A Closer Look at Class Member Access 272 Constructors and Destructors 274

Parameterized Constructors 277 Classes and Structures Are Related 282 Unions and Classes Are Related 284 Inline Functions 285

Creating Inline Functions Inside a Class 287 Arrays of Objects 288 Pointers to Objects 290 Object References 292

12 a m A Closer Look at Classes 295 Friend Functions 296 Overloading Constructor Functions 300 Dynamic Initialization 302

Applying Dynamic Initialization to Constructors 302

Assigning Objects 304 Passing Objects to Functions 306

Constructors, Destructors, and Passing Objects 307 A Potential Problem When Passing Objects 308

Returning Objects 312 A Potential Problem When Returning Objects 313

Creating and Using a Copy Constructor 315

Page 8: C++ from the Ground Up - GBV

Copy Constructors and Parameters 317 Copy Constructors and Initializations 319 Using Copy Constructors When an Object Is

Returned 321 The this Keyword 322

13 • • Operator Overloading 325 Operator Overloading Using Member Functions 326

Using Member Functions to Overload Unary Operators 329

Friend Operator Functions 336 Using a Friend to Overload a Unary Operator 340

A Closer Look at the Assignment Operator 344 Overloading new and delete 348 Overloading [ ] 352 Overloading Other Operators 355 Another Example of Operator Overloading 356

14MMI Inheritance 363 Introducing Inheritance 364 Base Class Access Control 367 Using protected Members 369

Using protected for Inheritance of a Base Class 373

Inheriting Multiple Base Classes 375 Constructors, Destructors, and Inheritance 376

When Constructor and Destructor Functions Are Executed 377

Passing Parameters to Base Class Constructors . . . . 380 Granting Access 384 Virtual Base Classes 388

15 a » Virtual Functions and Polymorphism 395 Pointers to Derived Types 396 Virtual Functions 399

Virtual Functions Are Inherited 401 Why Virtual Functions? 404 A Simple Application of Virtual Functions 405 Pure Virtual Functions and Abstract Classes 409

Early Versus Late Binding 412

Page 9: C++ from the Ground Up - GBV

16HHH The C++ I / O Sys tem 4 1 5 C++ Streams 416

The C++ Predefined Streams 417 The C++ Stream Classes 417 Overloading the I/O Operators 417

Creating Inserters 418 Using Friend Functions to Overload Inserters 420 Overloading Extractors 421 C I/O Versus C++ I/O 423

Formatted I/O 424 Formatting with the ios Member Functions 424 Using I/O Manipulators 429 Creating Your Own Manipulator Functions 431

File I/O 433 Opening and Closing a File 433 Reading and Writing Text Files 436 Unformatted Binary I/O 437 Reading and Writing Blocks of Data 439 Detecting EOF 441 A File Comparison Example 441

More Binary I/O Functions 443 Random Access 445 Customized I/O and Files 447

17HBB Templates a n d E x c e p t i o n H a n d l i n g 4 5 1 Generic Functions 452

A Function with Two Generic Types 455 Explicitly Overloading a Generic Function 456 Generic Function Restrictions 457

Generic Classes 459 An Example with Two Generic Data Types 462 Creating a Generic Array Class 463

Exception Handling 465 Using Multiple catch Statements 470

Options for Exception Handling 471 Catching All Exceptions 471 Restricting Exceptions 474 Rethrowing an Exception 475

Page 10: C++ from the Ground Up - GBV

18HHH Misce l laneous C++ Issues 4 7 9 Array-Based I/O 480

The Array-Based Classes 480 Creating an Array-Based Output Stream 480 Using an Array as Input 482 Input/Output Array-Based Streams 486

Using Dynamic Arrays 486 Pointers to Functions 488

Finding the Address of an Overloaded Function 491

Static Class Members 493 Using the asm Keyword 494 Linkage Specification 495 The .* and ->* Pointer-to-Member Operators 496 Creating Conversion Functions 499 C++ Keyword Extensions 501

19 M H T h e C++ Preprocessor 505 #define 506 #error 510 #include 511 Conditional Compilation Directives 511

#if, #else, #elif, and #endif 511 #ifdef and #ifndef 514 #undef 515 Using defined 516

#line 517 #pragma 518 The # and ## Preprocessor Operators 518 Predefined Macro Names 520 Final Thoughts 520

A H M C-Based I /O 5 2 3 C I/O Uses Streams 524 Understanding printf ( ) and scanf() 525

printf ( ) 525 scanf() 527

Page 11: C++ from the Ground Up - GBV

The C File System 532 fopen() 533 fputc() 534 fgetc() 534 feof() 535 fclose() 535 Using fopen( ), fgetc( ), fputc( ) and

fclose() 536 ferror( ) and rewind() 537 fread() and fwrite() 537

fseek() and Random-Access I/O 539 fprintf( ) and fscanf() 540 Erasing Files 540

HUH Index 5 4 1