C++ Programming/Print Version
Total Page:16
File Type:pdf, Size:1020Kb
Table of Contents About the book 11 Foreword 11 Authors 12 Getting Started 13 Introducing C++ 13 History 13 Overview 13 Why learn C++? 14 What is a Programming Language? 14 Low-level Languages 15 High-level Languages 15 Translating Programming Languages 15 Programming Paradigms 16 Procedural Programming 17 Object-Oriented Programming 17 Objects and Classes 17 Inheritance 17 Multiple Inheritance 18 Polymorphism 18 Generic Programming 18 Statically Typed 19 Free-form 19 Language Comparisons 19 Garbage Collection 20 Why doesn't C++ include a finally keyword? 20 Mixing Languages 20 C 89/99 20 Java 21 Memory management 23 Libraries 24 Runtime 24 Miscellaneous 24 Performance 25 C# 25 Managed C++ (C++/CLI) 26 The Code 26 File Organization 27 .cpp 27 .h 28 Object files 28 Statements 28 Coding Style Conventions 30 Identifier Naming 30 Leading underscores 30 Reusing existing names 31 Names indicate purpose 31 Capitalization 31 Constants 31 Functions and Member Functions 31 Examples 32 Reduced use of keywords 33 25 lines 80 columns 33 Whitespace and Indentation 33 Placement of braces (curly brackets) 33 Comments 34 C Comments 34 C++ Comments 35 Document your code 37 Why ? 37 Comments Should Be Written For the Appropriate Audience 37 What? 38 Document Decisions 38 Comment Layout 38 How ? 38 Automatic Documentation 39 Comments Should Tell a Story 39 Chapter Summary 40 Fundamentals 40 The Compiler 40 Where to get a compiler 40 GCC 40 On Windows 41 For DOS 41 For Linux 42 Compilation 42 compile time 42 lexical analysis 42 syntax analysis 43 ISO C++ (C++98) Keywords 44 C++ Reserved Identifiers 45 Compiler keywords 45 auto 45 inline 46 extern 46 Storage Class Specifiers 47 Compile Speed 47 The Preprocessor 47 Inclusion of Header Files (#include) 48 #pragma 49 Macros 50 #define and #undef 50 \ (line continuation) 51 Function-like Macros 51 # and ## 53 String Literal Concatenation 53 Conditional compilation 54 #if 55 #ifdef and #ifndef 55 #endif 55 Compile-time warnings and errors 56 #error and #warning 56 Source File Names and Line Numbering 56 Linker 56 Linking 57 Internal storage of data types 57 Bits and Bytes 57 Data and Variables 59 Two's Complement 60 Endian 62 Floating point representation 63 Variables 64 Types 64 Table of Data Types 65 Table of Data Types Footnotes 68 standard types 69 Declaration 69 Type Modifiers 71 const 71 volatile 72 mutable 73 short 74 long 74 unsigned 74 signed 75 Enumeration Types 75 User Input 76 Derived Types 76 Scope 76 The purpose of Scope 77 Scope and control structures 78 Scope using other control structures 79 The scoping of the for control statement in detail 80 Scope and lifetime in C++ 80 Namespace 81 Operators 86 Table of Operators 87 Order of operations 92 Precedence (Composition) 92 Chaining 93 Assignment 93 Arithmetic Operators 94 Compound Assignment 95 Character Operators 95 Derived Types Operators 96 Subscript Operator "[]" 96 Arrays 96 Why no bounds checking on array indexes? 98 address-of operator "&" 99 References 99 Dereferencing Operator "*" 99 Pointers 99 Declaring Pointers 100 Addressing Operator 100 Dereferencing operators 101 null pointer 102 Pointers to functions 102 Pointer Indirection Operator "->" 103 Pointer-to-Member Dereferencing Operator ".*" 103 Pointer-to-Member Indirection Operator "->*" 104 sizeof() 104 Dynamic Memory Allocation 104 new and delete 105 Logical operators 106 AND Operator 108 OR Operator 109 NOT Operator 109 Conditional Operator 109 Type Checking 110 Type Conversion 110 Automatic Type conversions 110 Promotion 111 Demotion 111 Explicit type conversions (casting) 111 The basic form of type cast 111 Advanced type casts 112 const_cast 112 static_cast 112 dynamic_cast 112 reinterpret_cast 112 Older forms of type casts 112 Common usage of type casting 113 Summary of different casts 113 Control Flow Construct Statements 114 Conditionals 114 if (Fork branching) 114 switch (Multiple branching) 116 Loops (iterations) 117 while (Preconditional loop) 118 do-while (Postconditional loop) 119 for (Preconditional and Counter-controlled loop) 120 Other Control Flow Constructs 121 goto 121 Functions 122 Declarations 123 main 123 Parameters 124 Passing by Pointer 125 Passing by Reference 127 Passing by Value 128 Constant Parameters 128 Default values 129 Returning Values 129 Positive Means Success 131 0 means success 132 Composition 133 Recursion 133 Inline 135 Pointers to functions 135 Overloading 136 Overloading resolution 136 Standard C Library 138 Standard C Library Functions (All) 139 Standard C I/O 145 clearerr 145 fclose 145 feof 145 ferror 146 fflush 146 fgetc 146 fgetpos 146 fgets 147 fopen 147 fprintf 148 fputc 148 fputs 148 fread 149 freopen 149 fscanf 149 fseek 149 fsetpos 150 ftell 150 fwrite 150 getc 150 getchar 151 gets 151 perror 151 printf 152 putc 154 putchar 154 puts 154 remove 155 rename 155 rewind 155 scanf 155 setbuf 157 setvbuf 157 sprintf 157 sscanf 158 tmpfile 158 tmpnam 158 ungetc 158 vprintf, vfprintf, and vsprintf 159 Standard C String & Character 159 atof 159 atoi 159 atol 160 isalnum 160 isalpha 161 iscntrl 161 isdigit 161 isgraph 161 islower 162 isprint 162 ispunct 162 isspace 162 isupper 162 isspace 163 memchr 163 memcmp 163 memcpy 164 memmove 164 memset 164 strcat 165 strchr 165 strcmp 165 strcoll 166 strcpy 166 strcspn 166 strerror 166 strlen 167 strncat 167 strncmp 167 strncpy 167 strrchr 168 strspn 168 strstr 168 strtod 169 strtok 169 strtol 169 strtoul 170 strxfrm 170 tolower 170 toupper 170 Debugging 170 What is debugging? 171 Type of errors 171 Common errors 172 Typographical errors (typos) 172 Debugger 173 What is a debugger? 173 How do you start the debugger? 174 Tracing your program 174 Controlling where the debugger pauses 174 Persistence 176 Examining the call stack 176 Conditional Breakpoints 176 Watchpoints 176 Setting Breakpoints in a Visual Debugger 177 Other runtime analyzers 177 Chapter Summary 177 Object Oriented Programming 178 Structures 178 this 182 Unions 182 Writing to Different Bytes 183 Example in Practice: SDL Events 183 this 184 Classes 184 Inheritance ( Derivation ) 185 Multiple inheritance 189 Access Labels 189 Data Members 191 this pointer 191 Member Functions 192 const 193 static 194 Inline 195 Accessors and Modifiers (Setter/Getter) 195 Lazy initialization 195 Overloading 196 Constructors 196 Overloaded Constructors 197 Constructor initialization lists 198 Destructors 199 Dynamic Polymorphism ( Overrides ) 200 Pure virtual member function 201 Virtual Constructors 202 Virtual Destructor 203 Pure Virtual Destructor 203 Covariant return types 203 Subsumption property 204 Ensuring objects of a class are never copied 205 Container class 206 Abstract Classes 206 Pure Abstract Classes 207 What is a "nice" class? 208 Class Declaration 209 Description 209 Copy Constructor 209 Equality Operator 210 Inequality Operator 210 Operator overloading 211 Operators as member functions 212 Overloadable operators 212 Arithmetic operators 212 Bitwise operators 213 Assignment operator 213 Relational operators 215 Logical operators 215 Compound assignment operators 215 Increment and decrement operators 216 Subscript operator 216 Function call operator 216 Address of, Reference, and Pointer operators 217 Comma operator 217 Member access operators 218 Memory management operators 218 Conversion operators 218 Operators which cannot be overloaded 219 Chapter Summary 219 Advanced Features 219 I/O 219 The string class 219 Basic usage 220 Text I/O 220 More advanced string manipulation 220 Size 221 I/O 221 Operators 221 Searching strings 222 Inserting/erasing 222 Backwards compatibility 223 String Formatting 223 Example 223 Advanced use 223 Streams 223 Stream classes 224 Standard input, output, and error 225 Files 225 "safe bool" idiom 226 Output 227 Input 227 Text input until EOF/error/invalid input 228 Making user-created classes compatible with the stream library 229 Exception Handling 230 Partial handling 231 Exception hierarchy 232 Throwing Objects 233 Stack unwinding 234 Writing exception safe code 235 Guards 235 Guide-lines 236 Exceptions in constructors and destructors 236 Templates 237 Advantages and disadvantages 240 Linkage problems 241 Template Metaprogramming Overview 243 History of TMP 243 Example: Compile-time Factorial 244 Example: Compile-time "If" 244 Building Blocks 245 Conventions for "Structured" TMP 245 Run-Time Type Information (RTTI) 245 dynamic_cast 245 typeid 246 Limitations 246 Misuses of RTTI 246 Standard Template Library (STL) 247 Containers 247 Sequence Containers 247 vector 248 vector::Iterators 248 vector::Other Members 248 vector examples 249 Linked lists 250 list examples 250 Associative Containers (key and value) 250 Maps and Multimaps 250 Container Adapters 251 Iterators 251 Iteration over a Container 252 Functors 252 STL Algorithms 253 Allocators 254 Chapter Summary 254 Beyond the Standard (In the real world) 254 Resource Acquisition Is Initialization (RAII) 254 Programming Patterns 257 Creational Patterns 257 Builder 257 Factory Method 258 Abstract Factory 259 Prototype 261 Singleton 264 Structural Patterns 266 Adapter 266 Bridge 266 Composite 266 Decorator 266 Facade 266 Flyweight 266 Proxy 266 Curiously Recurring Template 266 Behavioral Patterns 266 Chain of Responsibility 266 Command 266 Interpreter 267 Iterator 267 Mediator 269 Memento 269 Observer 269 State 270 Strategy 270 Template Method 270 Visitor 270 Model-View-Controller (MVC) 270 Libraries 270 APIs and frameworks 271 What is an API? 271 Static and Dynamic Libraries 271 Binary/Source Compatibility 271 Procedure to use static libraries (Visual