Docsity

A Complete Guide to Programming in C++, Slides of Advanced Computer Programming

Partial preview of the text

Download A Complete Guide to Programming in C++ and more Slides Advanced Computer Programming in PDF only on Docsity!

A Complete Guide to

Programming in C++

Ulla Kirch-Prinz

Peter Prinz

JONES AND BARTLETT PUBLISHERS

Mr Oddo

xi

  • 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

Fundamentals

This chapter describes the fundamental characteristics of the object-
oriented C++ programming language. In addition, you will be introduced
to the steps necessary for creating a fully functional C++ program.The
examples provided will help you retrace these steps and also
demonstrate the basic structure of a C++ program.

chapter 1

D E V E L O P M E N T A N D P R O P E R T I E S O F C + + ■^ 3

 Historical Perspective

The C++ programming language was created by Bjarne Stroustrup and his team at Bell Laboratories (AT&T, USA) to help implement simulation projects in an object-ori- ented and efficient way. The earliest versions, which were originally referred to as “C with classes,” date back to 1980. As the name C++ implies, C++ was derived from the C programming language: ++ is the increment operator in C. As early as 1989 an ANSI Committee ( A merican N ational S tandards I nstitute) was founded to standardize the C++ programming language. The aim was to have as many compiler vendors and software developers as possible agree on a unified description of the language in order to avoid the confusion caused by a variety of dialects. In 1998 the ISO ( I nternational O rganization for S tandardization) approved a stan- dard for C++ (ISO/IEC 14882).

 Characteristics of C++

C++ is not a purely object-oriented language but a hybrid that contains the functionality of the C programming language. This means that you have all the features that are avail- able in C:

■ universally usable modular programs ■ efficient, close to the machine programming ■ portable programs for various platforms.

The large quantities of existing C source code can also be used in C++ programs. C++ supports the concepts of object-oriented programming (or OOP for short), which are:

■ data abstraction, that is, the creation of classes to describe objects ■ data encapsulation for controlled access to object data ■ inheritance by creating derived classes (including multiple derived classes) ■ polymorphism (Greek for multiform), that is, the implementation of instructions that can have varying effects during program execution.

Various language elements were added to C++, such as references, templates, and excep- tion handling. Even though these elements of the language are not strictly object-ori- ented programming features, they are important for efficient program implementation.

4 ■^ C H A P T E R 1 F U N D A M E N T A L S

function

data

data

function

function

object

Properties

Capacities

object

Properties

Capacities

■ (^) OBJECT-ORIENTED PROGRAMMING

Traditional concept
Object-oriented concept
6 ■^ C H A P T E R 1 F U N D A M E N T A L S

Editor

Compiler

Linker

Executable file

Source file Header file

Standard library

Other libraries, object files

Object file

■ (^) DEVELOPING A C++ PROGRAM

Translating a C++ program

If the source file contains just one syntax error , the compiler will report an error. Additional error messages may be shown if the compiler attempts to continue despite having found an error. So when you are troubleshooting a program, be sure to start with the first error shown.

D E V E L O P I N G A C + + P R O G R A M ■^ 7

✓ NOTE

The following three steps are required to create and translate a C++ program:

  1. First, a text editor is used to save the C++ program in a text file. In other words, the source code is saved to a source file. In larger projects the programmer will nor- mally use modular programming. This means that the source code will be stored in several source files that are edited and translated separately.
  2. The source file is put through a compiler for translation. If everything works as planned, an object file made up of machine code is created. The object file is also referred to as a module.
  3. Finally, the linker combines the object file with other modules to form an exe- cutable file. These further modules contain functions from standard libraries or parts of the program that have been compiled previously.

It is important to use the correct file extension for the source file’s name. Although the file extension depends on the compiler you use, the most commonly found file exten- sions are .cpp and .cc. Prior to compilation, header files , which are also referred to as include files , can be copied to the source file. Header files are text files containing information needed by var- ious source files, for example, type definitions or declarations of variables and functions. Header files can have the file extension .h, but they may not have any file extension. The C++ standard library contains predefined and standardized functions that are available for any compiler. Modern compilers normally offer an integrated software development environment , which combines the steps mentioned previously into a single task. A graphical user interface is available for editing, compiling, linking, and running the application. Moreover, addi- tional tools, such as a debugger, can be launched.

In addition to error messages, the compiler will also issue warnings. A warning does not indicate a syntax error but merely draws your attention to a possible error in the pro- gram’s logic, such as the use of a non-initialized variable.

A B E G I N N E R ’ S C + + P R O G R A M ■^ 9

A C++ program is made up of objects with their accompanying member functions and global functions , which do not belong to any single particular class. Each function fulfills its own particular task and can also call other functions. You can create functions your- self or use ready-made functions from the standard library. You will always need to write the global function main() yourself since it has a special role to play; in fact it is the main program. The short programming example on the opposite page demonstrates two of the most important elements of a C++ program. The program contains only the function main() and displays a message. The first line begins with the number symbol, #, which indicates that the line is intended for the preprocessor. The preprocessor is just one step in the first translation phase and no object code is created at this time. You can type

#include

to have the preprocessor copy the quoted file to this position in the source code. This allows the program access to all the information contained in the header file. The header file iostream comprises conventions for input and output streams. The word stream indicates that the information involved will be treated as a flow of data. Predefined names in C++ are to be found in the std (standard) namespace. The using directive allows direct access to the names of the std namespace. Program execution begins with the first instruction in function main(), and this is why each C++ program must have a main function. The structure of the function is shown on the opposite page. Apart from the fact that the name cannot be changed, this function’s structure is not different from that of any other C++ function. In our example the function main() contains two statements. The first statement

cout << "Enjoy yourself with C++!" << endl;

outputs the text string Enjoy yourself with C++! on the screen. The name cout (console output) designates an object responsible for output. The two less-than symbols, <<, indicate that characters are being “pushed” to the out- put stream. Finally endl (end of line) causes a line feed. The statement

return 0;

terminates the function main() and also the program, returning a value of 0 as an exit code to the calling program. It is standard practice to use the exit code 0 to indicate that a program has terminated correctly. Note that statements are followed by a semicolon. By the way, the shortest statement comprises only a semicolon and does nothing.

10 ■^ C H A P T E R 1 F U N D A M E N T A L S

A program with some functions and comments ******************************************************/

#include using namespace std;

void line(), message(); // Prototypes

int main() { cout << "Hello! The program starts in main()." << endl; line(); message(); line(); cout << "At the end of main()." << endl;

return 0; }

void line() // To draw a line. { cout << "--------------------------------" << endl; }

void message() // To display a message. { cout << "In function message()." << endl; }

■ (^) STRUCTURE OF SIMPLE C++ PROGRAMS

A C++ program with several functions
Screen output

Hello! The program starts in main().

In function message().

At the end of main().