Академический Документы
Профессиональный Документы
Культура Документы
C++ Programs
• A C++ program is a collection of one or more subprograms, called functions
• A subprogram or a function is a collection of statements that when activated
(executed) accomplishes something
• Every C++ program has a function called main
• The smallest individual unit of a program written in any language is called a
token
Symbols
• Special symbols include:
• +
• -
• *
• /
• .
• ;
• ?
• ,
• <=
• !=
• ==
• >=
Symbols
• Word symbols
• are called reserved words, or keywords
• include: int, float, double, char, void, return
Identifiers
• Consist of letters, digits, and the underscore character (_)
• Must begin with a letter or underscore
C++ is case sensitive—uppercase and lower case letters are different
Start here Page 1
• C++ is case sensitive—uppercase and lower case letters are different
• Some of the predefined identifiers are cout and cin
• Unlike reserved words, predefined identifiers may be redefined, but it would
not be wise to do so
Arithmetic Operators
• C++ Operators
• + addition
• - subtraction
• * multiplication
• / division
• % remainder (mod operator)
• The operators +, -, *, and / can be used with both integral and floating-point
data types
• The % is used only with the integral data type to find the remainder in
ordinary division
• Unary operator - has only one operand
• Binary Operator - has two operands
Order of Precedence
• All operations inside of ( ) are evaluated first
• The operators *, /, and % are at the same level of precedence and are
evaluated next The operators + and – have the same level of precedence
and are evaluated last When operators are all on the same level, they are
performed from left to right
Mixed Expressions
• Mixed expression - an expression that has operands of different data types
• Contains both integers and floating-point numbers
• Examples of mixed expressions:
• 2 + 3.5
• 6 / 4 + 3.9
• 5.4 * 2 – 13.6 + 18 / 2
Assignment Statement
• The assignment statement takes the form:
variable = expression;
• The expression is evaluated and its value is assigned to the variable on the
left side
• In C++ = is called the assignment operator
• A C++ statement like:
I = I + 2;
• Evaluates whatever is in I, adds two to it, and assigns the new value to the
memory location I
Allocating Memory
• Named Constant - memory location whose content is not allowed to change
during program execution Variable - a memory location whose content may
change during program execution
• The syntax to declare a named constant is:
const dataType identifier = value;
• In C++, const is a reserved word
Input Statement
• Using more than one variable in cin allows more than one value to be read at
a time For example, if feet and inch are variables of the type int a statement
like:
cin>>feet>>inch;
• Inputs two integers that are entered at the keyboard and places them in the
memory location feet and inch, respectively
Output
• The syntax of cout together with << is:
cout<<expression or manipulator<<expression or manipulator...;
• This is called an output statement
• The << operator is called the insertion operator or the stream insertion
operator
• Sometimes this is also called a cout statement
Output
• In the example:
cout<<expression or manipulator<<expression or manipulator...;
• expression is evaluated and its value is printed at the current cursor position
on the screen
• manipulator - manipulates the output
• endl - the simplest manipulator which causes the cursor to move to the
beginning of the next line
Output Example
• The output of the C++ statement cout<<a; is meaningful provided the
variable a has been given a value
• For example, the sequence of C++ statements,
a = 45;
cout<<a;
will produce an output of 45
Program Example
int a, b, c, d;
a = 65 ; //Line 1
b = 78 ; //Line 2
cout<<29/4<<endl; //Line 3
Output of Statement
• 7 at Line 3
• 1.5 at Line 4
• Hello there. at Line 5
• 7 at Line 6
• 8 at Line 7
• 3+5 at Line 8
Examples
• Without the new line character:
cout<<"Hello there.";
cout<<"My name is Goofy.";
• Would output:
Hello there.My name is Goofy.
• With the new line character:
cout<<"Hello there.\n";
cout<<"My name is Goofy.";
• Would output
Hello there.
My name is Goofy.
Preprocessor Directives
• Only a small number of operations are explicitly defined in C++
• Many of the functions and symbols that are necessary to run a C++ program
are provided as a collection of libraries
• Every library has a name and is referred to by a header file
• Preprocessor directives are commands supplied to the preprocessor
• All preprocessor commands begin with #
• There is no semicolon at the end of these commands
Header Files
• In Standard C++, header files have the file extension .h
• The descriptions of the functions needed to perform I/O are contained in the
header file iostream.h
• The syntax is:
• #include <iostream.h>
• #include <math.h>
Statements
• Declaration Statements
int a, b, c;
double x, y;
• Variables can be declared anywhere in the program, but they must be
declared before they can be used
Executable Statements have three forms:
Start here Page 9
• Executable Statements have three forms:
a = 4; //assignment statement
cin>>b; //input statement
cout<<a<<endl<<b<<endl; //output statement
Special Characters
• Use of Blanks
• one or more blanks are used to separate numbers when data is input
• blanks are also used to separate reserved words and identifiers from each
other and other symbols
• The blanks between the identifiers in the second statement are meaningless:
• int a,b,c;
• int a, b, c;
• In the statement: inta,b,c;
no blank between the t and a changes the reserved word int and the
identifier a into a new identifier, inta
Semantics
• It is possible to eradicate all syntax errors in a program and still not have it
run
• It is also possible that if it runs it still may not do what you meant it to do
• For example,
2 + 3 * 5 and (2 + 3) * 5
are both syntactically correct expressions, but have different meanings
Documentation
• Comments can be used to document the code
• Single line comments begin with // anywhere in the line
• Multiple line comments are enclosed between /* and */
• Name identifiers with meaningful names
• Run-together-words can be handled either by using capitals for the beginning
of each new word or an underscore just before the new word
Input/Output Streams
• I/O - sequence of bytes (stream of bytes) from source to destination
• The bytes are usually characters, unless the program requires other types of
information
• Stream - sequence of characters from source to destination
• Input Stream - sequence of characters from an input device to the computer
• Output Stream - sequence of characters from the computer to an output
device
Standard Input
The syntax of an input statement using cin and the extraction operator >> is
Reading Data
• When reading data into a char variable, after skipping any leading whitespace
characters, the extraction operator >> finds and stores only the next
character
• reading stops after a single character
• To read data into an int or double variable, after skipping all leading
whitespace characters and reading the plus or minus sign (if any), the
extraction operator >> reads the digits of the number, including the decimal
point for floating-point variables
• reading stops when it finds a whitespace character or a character other than a
digit
Using Predefined Functions
• A function, also called a subprogram, is a set of instructions
• When a function is activated (executed) it accomplishes something
• The function main is executed automatically when a program is executed
• Other functions are executed only when they are called
• C++ comes with a wealth of functions
• Predefined functions are organized as a collection of libraries called header
files
Predefined Functions
File Input/Output
• File - an area in secondary storage used to hold information
• For file I/O, the following steps are necessary
1.Include the header file fstream in the program requiring the
File Input/Output
4.Use the (file) stream variable together with >>, <<, or other
functions for input/output
•The syntax for using >> or << with file variables is exactly
the same as the syntax of cin and cout
5.The syntax for using >> or << with file variables is exactly similar
to the syntax of cin and cout
Finally, close files using:
•inData.close();
•outData.close();
Chapter 4
CONTROL STRUCTURES I
(Selection)
Control Structures
• A computer can proceed:
• in sequence
• selectively (branch) - making a choice
• repetitively (iteratively) - performing a statement over and over, also called a
loop
• Some statements are executed only if certain conditions are met
• A condition is represented by a logical (Boolean) expression that has a value
of either true or false
• A condition is met if it evaluates to true
Relational Operators
• A relational operator allows you to make comparisons in a program
• Equality of real numbers is usually machine dependent so it is possible that on
a particular machine 6.8 + 3.1 == 2.7 + 7.2 might evaluate to false
• Comparing values of different data types may produce unpredictable results
• For example, 8 < '5' should not be done
• C++ returns an integer value of 1 if the logical expression evaluates to true
and the value of 0 otherwise
• In C++, any nonzero value is treated as true
Precedence of Operators
• Relational and logical operators are evaluated from left to right so the
associativity is said to be from left to right
• Parentheses can be used to indicate an order of operation that is different
than the order indicated by order of precedence
• Short-circuit evaluation (of a logical expression) - a process in which the
computer evaluates a logical expression from left to right and stops as soon
as the value of the expression is known
One-Way Selection
Nested if
• When one control statement is within another, it is said to be nested
• An else is associated with the most recent if that has not been paired with an
else
For example:
Start here Page 21
• For example:
if(score >= 90)
cout<<"The grade is A"<<endl;
else if(score >= 80)
cout<<"The grade is B"<<endl;
else
cout<<"The grade is F"<<endl;
switch Structures
• In a switch structure, the expression is evaluated first
• Next, the value of the expression is used to perform the corresponding action
• The expression is usually an identifier
• It is sometimes called the selector
• The expression value can be only integral
• Its value determines which statement is selected for execution
• A particular case value should appear only once
switch Structures
• One or more statements may follow a case label
• Braces are not needed to turn multiple statements into a single compound
statement
• The break statement may or may not appear after each statement
• The break statement has a special meaning and may or may not appear after
each statement
• switch, case, break, and default are reserved words
Chapter 5
CONTROL STRUCTURES II
(Repetition)
Chapter 6
USER-DEFINED FUNCTIONS I
Functions
• Functions are like building blocks
• They allow complicated programs to be divided into manageable pieces
• Some of the advantages of functions are:
• A programmer can focus on just that part of the program and construct it,
debug it, and perfect it
• Different people can work on different functions simultaneously
• If a function is needed in more than one place in a program, or in different
programs, you can write it once and use it many times
Functions
• are often referred to as modules
• are like miniature programs
• can be put together to form a larger program
Standard Functions
• In college algebra a function is defined as a rule or correspondence between
values, called the function’s arguments, and the unique value of the function
associated with the arguments
• If f(x) = 2x + 5, then f(1) = 7, f(2) = 9, and f(3) = 11
• 1, 2, and 3 are arguments
• 7, 9, and 11 are the corresponding values
Standard Functions
• Some of the predefined mathematical functions are:
• sqrt(x)
• pow(x,y)
• floor(x)
• Predefined functions are organized into separate libraries
• I/O functions are contained in the header file iostream
Math functions are contained in the header file cmath
User-Defined Functions
• Void functions - functions that do not have a data type
• Value-returning functions - functions that have a data type
• To use these functions you need to:
• include the correct header file
• know the name of the function
• know the number of parameters, if any
• know the data type of each parameter
• know the data type of the value computed by the function, called the type of
the function
User-Defined Functions
• The first four properties form the heading of the function
• The fifth property is called the body of the function
• These properties form the function definition
• For predefined functions, we only need to be concerned with the first four
properties
• Formal Parameter - A variable declared in the function heading
• Actual Parameter - A variable or expression listed in a call to a function
Value-returning Functions
• The syntax is:
functionType functionName(formal parameter list)
{
statements
}
• functionType - type of the value returned by the function
• functionType - also called the data type of the value-returning function
Syntax
• The syntax of the formal parameter list is:
dataType identifier, dataType identifier, ...
• The syntax for a function call is:
functionName(actual parameter list)
• The syntax for the actual parameter list is:
expression or variable,expression or variable, ...
Functions
• The formal parameter list can be empty
• If the formal parameter list is empty
• the parentheses are still needed
• the function heading of the value-returning function takes either of the
following forms:
• functionType functionName()
• functionType functionName(void)
• in a function call the actual parameter is empty
A call to a value-returning function with an empty formal parameter list is:
Value-Returning Functions
• To call a value-returning function:
• Use its name, with the actual parameters (if any) in parentheses
• There is a one-to-one correspondence between actual and formal parameters
• A value-returning function is called in an expression
• The expression may be part of an assignment statement or an output
statement
• A function call in a program results in the execution of the body of the called
function
Function Prototype
• Function Prototype - function heading without the body of the function
• The syntax is:
functionType functionName(parameter list);
• It is not necessary to specify the variable name in the parameter list The
data type of each parameter must be specified
Flow of Execution
• When the program is executed (run), execution always begins at the first
statement in the function main no matter where it is placed in the program
• Other functions are executed only when they are called
• Function prototypes appear before any function definition, so the compiler
translates these first
• The compiler can then correctly translate a function call
Flow of Execution
• A function call statement results in the transfer of control to the first
statement in the body of the called function
• After the last statement of the called function is executed, the control is
passed back to the point immediately following the function call
• A value-returning function returns a value
• After executing the function when the control goes back to the caller, the
value that the function returns replaces the function call statement
Chapter 7
Void Functions
• Void functions and value-returning functions have similar structures
• Both have a heading part and a statement part
• User-defined void functions can be placed either before or after the function
main The program execution always begins with the first statement in the
function main If user-defined void functions are placed after the function
main, the function prototype must be placed before the function main
Void Functions
• Because a void function does not have a data type, putting functionType in
the heading part and the return statement in the body of the void function are
meaningless
• The return statement can be used without any value; it is typically used to
exit the function early
• May or may not have formal parameters
• A call to a void function is a stand-alone statement
Without Parameters
• Function definition syntax:
void functionName(void)
{
statements
}
• void inside the parentheses is optional
• void is a reserved word
• Function call syntax:
• functionName();
With Parameters
• Function definition syntax:
void functionName(dataType& variable, dataType& variable, …)
{
statements
}
• Value Parameter - a formal parameter that receives a copy of the content of
the corresponding actual parameter
• Reference Parameter - a formal parameter that receives the location (memory
address) of the corresponding actual parameter
Formal Parameters
• If a formal parameter is a value parameter, the value of the corresponding
actual parameter is copied into it The value parameter has its own copy of
the data During program execution, the value parameter manipulates the
data stored in its own memory space
Reference Parameter
• A reference parameter receives the address of the actual parameter
• They can pass one or more values from a function and can change the value
of the actual parameter
• Reference parameters are useful in three situations:
• Returning more than one value
• Changing the actual parameter
• When passing the address would save memory space and time
Scope of an Identifier
• The scope of an identifier refers to where in the program an identifier is
accessible (that is visible)
• Local identifier - identifiers declared within a function (or block)
• Global identifier – identifiers declared outside of every function definition
• C++ does not allow the nesting of functions, this means that the definition of
one function cannot be included in the body of another function
Scope of an Identifier
• Global identifiers (such as variables) are accessible by a function or a block if
• the identifier is declared before the function definition (block)
• the function name is different from the identifier
• all parameters of the function have names different than the name of the
identifier
• all local identifiers (such as local variables) have names different than the
name of the identifier
Scope of an Identifier
• An identifier declared within a block (Nested Block) is accessible
• only within the block from the point it is declared until the end of the block
and
• by those blocks that are nested within that block if the nested block does not
have an identifier with the same name as that of the outside block (the block
that encloses the nested block)
• The scope of a function name is similar to the scope of an identifier declared
outside of any block
Global Variables
• Some compilers initialize global variables to default values
• The operator :: is called the scope resolution operator
• By using the scope resolution operator, a global variable declared before the
definition of a function (block) can be accessed by the function (or block)
even if the function (or block) has an identifier with the same name as the
variable
Global Variables
• C++ provides a way to access a global variable declared after the definition of
a function In this case, the function must not contain any identifier with the
same name as the global variable
Function Overloading
• You can have several functions with the same name
• Every function must have a different set of parameters
• This is overloading a function name
• The types of parameters determine which function to be executed
• It is used when we have the same action for different sets of data
• For it to work, the definition of each of the functions must be given
Default Parameters
• When a function is called, the number of actual and formal parameters must
be the same C++ relaxes this condition for functions with default
parameters You specify the value of a default parameter when the function
name appears for the first time, such as in the prototype
Default Parameters
• If you do not specify the value of a default parameter, the default value is
used All the default parameters must be the rightmost parameters of the
function In a function call where the function has more than one default
parameter and a value to a default parameter is not specified, then you must
omit all of the arguments to its right
Default Parameters
Default values can be constants, global variables, or function calls The caller
Chapter 8
USER-DEFINED SIMPLE DATA
TYPES, NAMESPACES,
AND THE string TYPE
Enumeration Type
• Data type - a set of values together with a set of operations on those values
• To define a new simple data type, called enumeration type, we need three
things:
• a name for the data type
• a set of values for the data type
• a set of operations on the values
• A new simple data type can be defined by specifying its name and the values,
but not the operations
• The values must be identifiers
Enumeration Type
• The syntax for enumeration type is:
enum typeName{value1, value2, ...};
• value1, value2, … are identifiers
• They called enumerators
• value1 < value2 < value3 <...
• Enumeration type is an ordered set of values
• If a value has been used in one enumeration type, it cannot be used by
another in the same block
• The same rules apply to enumeration types declared outside of any blocks
Examples
• The following are illegal enumeration types because none of the values is an
identifier:
enum grades{'A', 'B', 'C', 'D', 'F'};
enum places{1st, 2nd, 3rd, 4th};
• The following are legal enumeration types:
enum grades{A, B, C, D, F};
enum places{first, second, third, fourth};
Declaring Variables
• The syntax for declaring variables is:
dataType identifier, identifier,...;
• The following statement defines an enumeration type sports
enum sports{basketball, football, hockey,
baseball, soccer, volleyball};
The following statement declares variables of the type sports.
Start here Page 37
• The following statement declares variables of the type sports.
sports popularSport, mySport;
Assignment
• The statement:
popularSport = football;
stores the word football in the variable popularSport
• The statement:
mySport = popularSport;
copies the contents of the variable popularSport in the variable mySport
Operations
• No arithmetic operation is allowed on enumeration types
• The following statements are illegal;
mySport = popularSport + 2; //illegal
popularSport = football + soccer; //illegal
popularSport = popularSport * 2; // illegal
• The increment and decrement operations are not allowed on enumeration
types
• The following statements are illegal;
popularSport++; //illegal
popularSport--; //illegal
Operations
• Because an enumeration is an ordered set of values, we can use relational
operators with them
• The cast operator can be used to increment, decrement, and compare the
values which means that they can be used in loops
• Input and output
• are defined only for built-in data types such as int, char, double
• the enumeration type can be neither input nor output (directly)
• you can input and output enumeration indirectly
Functions
• Enumeration type can be passed as parameters to functions either by value or
by reference A function can return a value of the enumeration type
Namespaces
• When a header file, such as iostream, is included in a program, the global
identifiers in the header file also become global identifiers in the program
• If a global identifier in a program has the same name as one of the global
identifiers in the header file, the compiler will generate a syntax error (such as
identifier redefined)
• The same problem can occur if a program uses third party libraries
Namespaces
• To overcome this problem, third party vendors begin their global identifiers
with a special symbol
• Since compiler vendors begin their global identifier with _ (underscore), to
avoid linking errors do not begin identifiers in your program with _
(underscore)
• ANSI/ISO standard C++ attempts to solve this problem of overlapping global
identifier names with the namespace mechanism
Syntax: namespace
• The syntax of the statement namespace is:
namespace namespace_name
{
members
}
where a member is usually a variable declaration, a named constant, a
function, or another namespace
Chapter 9
Data Types
• A data type is called simple if variables of that type can store only one value
at a time A structured data type is one in which each data item is a
collection of other data items
Arrays
• Array - a collection of a fixed number of components wherein all of the
components are of the same data type One-dimensional array - an array in
which the components are arranged in a list form The general form of
declaring a one-dimensional array is:
dataType arrayName[intExp];
where intExp is any expression that evaluates to a positive integer
Declaring an array
• The statement int num[5]; declares an array num of 5 components of the
type int The components are num[0], num[1], num[2], num[3], and num[4]
Array Initialization
• Like any other simple variable, arrays can also be initialized while they are
being declared When initializing arrays while declaring them, it is not
necessary to specify the size of the array The size of the array is determined
by the number of initial values in the braces
• For example:
double sales[] = {12.25, 32.50, 16.90, 23, 45.68};
Partial Initialization
• The statement
int list[10] = {0};
declares list to be an array of 10 components and initializes all
components to zero
• The statement
int list[10] = {8, 5, 12};
declares list to be an array of 10 components, initializes list[0] to 8, list[1]
to 5, list[2] to 12 and all other components are initialized to 0
Partial Initialization
• The statement
int list[] = {5,6,3};
Start here Page 43
int list[] = {5,6,3};
declares list to be an array of 3 components and initializes list[0] to 5,
list[1] to 6, and list[2] to 3
• The statement
int list[25]= {4,7};
declares list to be an array of 25 components. The first two components
are initialized to 4 and 7, respectively and all other components are
initialized to zero
String Comparison
• C-strings are compared character by character using the collating sequence of
the system
• If we are using the ASCII character set
• 1. The string "Air" is smaller than the string "Boat"
• 2. The string "Air" is smaller than the string "An"
• 3. The string "Bill" is smaller than the string "Billy"
Input/Output Files
• Values (strings) of the type string are not null terminated
• Variables of type string can be used to read and store the names of
input/output files
• The argument to the function open must be a null terminated string, that is a
C string
• If we use a variable of the type string to read the name of an input/output file
and then use this variable to open a file, the value of the variable must first
be converted to a C-string (null-terminated string)
Input/Output Files
• The header file string contains the function c_str, which converts a value of
the type string to a null-terminated character array (C-string)
• The syntax to use the function c_str is:
strVar.c_str()
where strVar is a variable of the type string
Parallel Arrays
• Two (or more) arrays are called parallel if their corresponding components
hold related information
• For example:
int studentId[50];
char courseGrade[50];
Initialization
• Like one-dimensional arrays, two-dimensional arrays can be initialized when
they are declared
• To initialize a two-dimensional array when it is declared
• 1. The elements of each row are enclosed within braces and separated by
commas.
• 2. All rows are enclosed within braces.
• 3. For number arrays, if all components of a row are not specified, the
unspecified components are initialized to zero.
Initialization
• This for loop initializes row four to zero:
row = 4;
for(col = 0; col < columns; col++)
matrix[row][col] = 0;
• To initialize the entire matrix, we can also put the first index (row position) in
a loop
These nested for loops initialize each component of matrix to 0:
Start here Page 47
• These nested for loops initialize each component of matrix to 0:
for(row = 0; row < rows; row++)
for(col = 0; col < columns; col++)
matrix[row][col] = 0;
Print
• The following nested for loops print the components of matrix, one row per
line:
for(row = 0; row < rows; row++)
{
for(col = 0; col < columns; col++)
cout<<setw(5)<<matrix[row][col]<<" ";
cout<<endl;
}
Input
• This for loop inputs data in row number 4 of matrix:
row = 4;
for(col = 0; col < columns; col++)
cin>>matrix[row][col];
• By putting the row number in a loop we can input data in each component of
the matrix
for(row = 0; row < rows; row++)
for(col = 0; col < columns; col++)
cin>>matrix[row][col];
Two-dimensional Arrays
• Two-dimensional arrays can be passed as parameters to a function and they
are passed by reference The base address, that is, the address of the first
component of the actual parameter is passed to the formal parameter If
matrix is the name of a two-dimensional array, then matrix[0][0] is the first
component of matrix
Two-dimensional Arrays
• When storing a two-dimensional array in the computer’s memory, the row
order form is used This means that the first row is stored first, followed by
the second row, which is followed by the third row and so on When
declaring a two-dimensional array as a formal parameter, we can omit the
size of the first dimension, but not the second
• The number of columns must be specified
Multi-dimensional Arrays
• Array - a collection of a fixed number of elements (called components)
arranged in n dimensions (n >= 1), called an n-dimensional array The
general syntax of declaring an n-dimensional array is:
dataType arrayName[intExp1][intExp2]...[intExpn];
where intExp1, intExp2, … , and intExpn are constant expressions
yielding positive integer values
Multi-dimensional Arrays
• The syntax of accessing a component of an n-dimensional array is:
arrayName[indexExp1][indexExp2]...[indexExpn]
where indexExp1,indexExp2,..., and indexExpn are expressions yielding
nonnegative integer values. indexExpi gives the position of the array
component in the ith dimension
Multi-dimensional Arrays
• When declaring a multi-dimensional array as a formal parameter in a function,
we can omit the size of the first dimension but not the other dimensions As
parameters multi-dimensional arrays are passed by reference only and a
function cannot return a value of the type array There is no check if the
array indices are within bounds
Chapter 10
RECORDS (Structs)
Records (Structs)
• Struct - a collection of a fixed number of components in which components
are accessed by name is called a struct
• The components may be of different types
• The components of a struct are called the members of the struct A struct is
a definition not a declaration; no memory is allocated
• Memory is allocated when we declare variables
Struct Syntax
• The general form (syntax) of a struct is:
struct typeName
{
dataType1 identifier1;
dataType2 identifier2;
.
.
.
dataTypen identifiern;
};
Input/Output
• There are no aggregate input/output operations on struct Data in a struct
variable must be read one member at a time Contents of a struct must be
written one member at a time
Arrays in Structs
• The two things that are associated with a list are the values (elements) and
the length of the list
• In the searching and sorting functions that we discussed, we needed to pass
these two things separately to the function
• Because the values and the length are both related to a list, we can define a
struct containing both the items
• We need to pass only one parameter, not two
Chapter 11
CLASSES AND DATA ABSTRACTION
Classes
• A class is a collection of a fixed number of components
• The components of a class are called members of the class
• The general syntax of defining a class is:
class classIdentifier
{
classMemberList
Classes
• If a member of a class is a variable, it is declared just like any other variable
• In the definition of the class, you cannot initialize a variable when you declare
it
• If a member of a class is a function, typically the function prototype is used to
define that member
• A missing semicolon, therefore, will result in a syntax error
Classes
• If a member of a class is a function,
• it can (directly) access any member of the class—data members and function
members
• when you write the definition of the member function, you can directly access
any data member of the class without passing it as a parameter
• the only obvious condition is that you must declare an identifier before you
can use it
• Class is a reserved word and it only defines a data type, no memory is
allocated
• The semicolon after the right brace is part of the syntax
Classes
• The members of a class are classified into three categories:
• private
• public
• protected
• Following are some facts about public and private members of a class:
• By default, all members of a class are private
• If a member of a class is private, you cannot access it outside the class
Classes
• A public member is accessible outside the class To make a member of a
class public, you use the label public with a colon In C++, private,
protected, and public are reserved words
Class Scope
• A class object has the same scope as other variables
• A member of a class is local to the class
• We access a class member outside the class by using the class object name
and the member access operator (.)
Constructors
• 1. The name of a constructor is the same as the name of the class
• 2. A constructor:
• even though it is a function, has no type
• it is neither a value-returning function nor a void function
• 3. A class can have more than one constructor, however, all constructors of a
class have the same name
• 4. If a class has more than one constructor, they must have different sets of
parameters
Constructors
• 5. Constructors:
• are automatically executed when a class variable enters its scope
• since they have no types, they cannot be called like other functions
• 6. Which constructor executes depends on the type of values passed to the
class variable when the class variable is declared
Invoking a Constructor
• A constructor is automatically executed when a class variable is declared A
class might have more than one constructor, including the default constructor
Arrays
• If a class has constructors and you declare an array of class objects, the class
must have the default constructor The default constructor is used to
initialize each (array) class object
• For example:
clockType clocks[100];
Destructors
• Like constructors, destructors are also functions
• The name of a destructor is the character '~' followed by the name of the
class
• The name of the destructor for the class clockType is:
~clockType();
• A class can have only one destructor and it has no parameters
• The destructor is automatically executed when the class object goes out of
scope
Information Hiding
• The header file has an extension h
• The implementation file has an extension cpp
• The implementation file must include the header file via the include statement
In an include statement, user-defined header files are enclosed in double
quotes while system-provided header files are enclosed between angular
brackets
Files
• Visual C++, C++ Builder, and CodeWarrior put the editor, compiler, and
linker all into one package
• With one command, the program is compiled and linked with the other
necessary files
• These systems also manage multiple file programs in the form of a project
• A project consists of several files, called the project files
Files
• These systems usually have a command, called build, rebuild, or make
When the build, rebuild, or make command is applied to a project, the
system automatically compiles and links all files required to create the
executable code When one or more files in the project change, you can use
these commands to recompile and relink the files
Chapter 12
INHERITANCE AND COMPOSITION
Inheritance
• Design a class, partTimeEmployee, to implement and process the
characteristics of a part-time employee
• Every part-time employee has a name, pay rate, and number of hours worked
Every part-time employee is a person
Inheritance
• We do not want to make the necessary changes directly to the class
personType—that is, edit the class personType, and add and/or delete
members
• We want to create the class partTimeEmployee without making any physical
changes to the class personType, by adding only the members that are
necessary
• The new class that we create from existing classes is called the derived class
and the existing classes are called the base classes
Inheritance
• Single inheritance- the derived class is derived from a single base class
• Multiple inheritance- the derived class is derived from more than one base
class
• Inheritance can be viewed as a tree-like, or hierarchical, structure wherein a
base class is shown with its derived classes
• The word public in a heading, called the member access specifier, specifies
that all public members of the class shape are inherited as public members by
the class circle
Inheritance
Facts
• The following facts about the base and the derived classes should be kept in
mind:
• 1. The private members of the base class are private to the base class; hence,
the members of the derived class cannot directly access them
• 2. The public members of a base class can be inherited either as public
members or as private members by the derived class
• 3. The derived class can include additional data and/or function members
Facts
Constructors
• A derived class can have its own private data members
• Member functions of the derived class cannot directly access the private
members of the base class
• The constructors of the derived class can (directly) initialize only the private
data members of the derived class
• When a derived class object is declared, it must also automatically execute
one of the constructors of the base class
Constructors
• The execution of a derived class’s constructor must trigger the execution of
one of the base class’s constructors A call to the base class’s constructor is
specified in the heading part of the derived class constructor’s definition
Multiple Inclusions
• Suppose that the header file testA.h includes the file test.h to make use of the
identifiers one and two
• The preprocessor first includes the header file test.h and then the header file
testA.h
• When the header file testA.h is included, because it contains the preprocessor
directive #include "test.h", the header file test.h will be included twice in the
program
• The second inclusion of the header file test.h will result in compile-time
errors, such as identifier one already being declared
• To avoid multiple inclusion of a file in a program we use certain preprocessor
commands in the header file
Stream Classes
Stream Classes
Start here Page 57
Stream Classes
• The class ios is the base class for all stream classes
• Classes istream and ostream are directly derived from the class ios
• The class ifstream is derived from the class istream, and the class ofstream is
derived from the class ostream
• The class ios contains formatting flags and member functions to access
and/or modify the setting of these flags
Stream Classes
• To identify the I/O status, the class ios contains an integer status word This
integer status word provides a continuous update reporting the status of the
stream The classes istream and ostream are responsible for providing the
operations for the data transfer between memory and devices
Stream Classes
• The class istream defines the extraction operator, >>, and functions such as
get and ignore
• The class ostream defines the insertion operator, <<, which is used by the
object cout
• The class ifstream is derived from the class istream to provide the file input
operations
• The class ofstream is derived from the class ostream to provide the file output
operations
Stream Classes
• Objects of the type ifstream are used for file input Objects of the type
ofstream are used for file output The header file fstream contains the
definition of the classes ifstream and ofstream
Inheritance
• 1. If memberAccessSpecifier is public, then
a. The public members of A are public members of B and they can be directly
Inheritance
• 2. If memberAccessSpecifier is protected, then
• a. The public members of A are protected members of B and they can be
accessed by the member functions (and friend functions) of B
• b. The protected members of A are protected members of B and they can be
accessed by the member functions (and friend functions) of B
• c. The private members of A are hidden in B and they can be accessed by the
member functions (and friend functions) of B through the public or protected
members of A
Inheritance
• 3. If memberAccessSpecifier is private, then
• a. The public members of A are private members of B and they can be
accessed by the member functions (and friend functions) of B
• b. The protected members of A are private members of B and they can be
accessed by the member functions (and friend functions) of B
• c. The private members of A are hidden in B and they can be accessed by the
member functions (and friend functions) of B through the public or protected
members of A
Composition
• In composition one or more member(s) of a class is an object of another class
type
• Composition is a ―has-a‖ relation
• The arguments to the constructor of a member-object are specified in the
heading part of the definition of the constructor of the class
• Member-objects of a class are constructed in the order they are declared, not
in the order they are listed in the constructor’s member initialization list, and
before the enclosing class objects are constructed
Chapter 13
POINTERS, CLASSES, LISTS, AND VIRTUAL FUNCTIONS
Pointer Variables
• Pointer variable - a variable whose content is a memory address
• Declaring Pointer Variables
• The general syntax of declaring a pointer variable is
dataType *identifier;
int *p;
char *ch;
Pointer Variables
• The statement int *p; is equivalent to the statement int* p; which is
equivalent to the statement int * p;
• The character * can appear anywhere between the data type name and the
variable name
Pointer Variables
• To avoid confusion, we prefer to attach the character * to the variable name
int *p, q;
• The following statement declares both p and q to be pointer variables of the
type int
int *p, *q;
Dynamic Variables
• Variables that are created during program execution are called dynamic
variables
• With the help of pointers, C++ creates dynamic variables
• New and delete, to create and destroy dynamic variables, respectively
• When a program requires a new variable, the operator new is used
• When a program no longer needs a dynamic variable, the operator delete is
used
• In C++, new and delete are reserved words
Dynamic Arrays
• An array created during the execution of a program is called a dynamic array
• To create a dynamic array, we use the second form of the new operator
• The statement int *p; declares p to be a pointer variable of the type int
• The statement p = new int[10]; allocates 10 contiguous memory locations,
each of the type int, and stores the address of the first memory location into
p
The Destructor
• If the pointer p does not use the delete operator to deallocate the dynamic
array, the memory space of the dynamic array would stay marked as
allocated, even though no one can access it How do we ensure that when p
is destroyed, the dynamic memory created by p is also destroyed?
The Destructor
• If a class has a destructor, the destructor automatically executes whenever a
class object goes out of scope We can put the necessary code in the
destructor to ensure that when objectOne goes out of scope, the memory
created by the pointer p is deallocated
Array-Based Lists
• List - a collection of elements of the same type
• The length of a list is the number of elements in the list
• Operations performed on a list are:
• Create the list and initialize to an empty state
• Determine whether the list is empty
• Determine whether the list is full
• Find the size of the list
• Destroy, or clear the list
Array-Based Lists
• Operations performed on a list are:
• Determine whether an item is the same as a given list element
• Insert an item in the list at the specified location
• Remove an item from the list at the specified location
• Replace an item at the specified location with another item
• Retrieve an item from the list at the specified location
• Search the list for a given item
Lists
• Lists are stored as an array
• The size of the array can be specified when a list object is declared
• To maintain and process the list in an array, we need three variables:
• The array holding the list elements
• A variable to store the length of the list (that is, the number of elements
currently in the array)
• A variable to store the size of the array (that is, the maximum number of
elements that can be stored in the array)
Chapter 14
OVERLOADING AND TEMPLATES
Operator Overloading
• The only built-in operations on classes are the assignment operator and the
member selection operator Therefore, other operators cannot be applied,
directly, on class objects C++ allows the programmer to extend the
Operator Overloading
• C++ allows the user to overload most of the operators to work effectively in a
specific application
• C++ does not allow the user to create new operators
• Most of the existing operators can be overloaded to manipulate class objects
• In order to overload an operator we must write functions
Operator Overloading
• The name of the function that overloads an operator is the reserved word
operator followed by the operator to be overloaded
• The following function name overloads >=
operator>=
• Operator function: The function that overloads an operator
Some Restrictions
• When overloading an operator the following should be kept in mind
• 1. You cannot change the precedence of an operator
• 2. The associativity cannot be changed
• 3. Default arguments cannot be used with an overloaded operator
• 4. You cannot change the number of arguments that an operator takes
Some Restrictions
• 5. You cannot create new operators
• Only existing operators can be overloaded
• The operators that cannot be overloaded are
. .* :: ?: sizeof
• 6. The meaning of how an operator works with built-in types, such as int,
remains the same
• 7. Operators can be overloaded either for objects of the user-defined type, or
for a combination of objects of the user-defined type and objects of the built-
in type
this Pointer
Every object of a class maintains a (hidden) pointer to itself
Operator Functions
• 1. The function that overloads any of the operators (), [], ->, or = for a class
must be declared as a member of the class
• 2. Suppose an operator op is overloaded for a class, say OpOverClass
• a. If the leftmost operand of op is an object of a different type (that is, not of
the type OpOverClass), the function that overloads the operator op for
OpOverClass must be a nonmember—that is, a friend of the class
OpOverClass
Operator Functions
• b. If the operator function that overloads the operator op for the class
OpOverClass is a member of the class OpOverClass, then when applying op
on objects of the type OpOverClass, the leftmost operand of op must be of
the type OpOverClass
• Except for some of the operators, as explained above, most of the operators
can be overloaded either as member functions or as nonmember functions
Binary Operators
• Suppose that the binary operator + is overloaded for the class OpOverClass
Overloading + as a Member Function
• Suppose that + is overloaded as a member function of the class OpOverClass
• The name of the function to overload + for the class OpOverClass is
operator+
Binary Operators
• Since x and y are objects of the type OpOverClass, we can perform the
operation
x+y
Binary Operators
• In the above statement, operator+ has direct access to the private members
of the object x
• The first argument to operator+ is the object that is invoking the function
operator+ and the second argument is passed as a parameter to this function
• Suppose that the operator + adds the corresponding data members of the
objects
• The result of the expression x + y is an object of the type OpOverClass
Binary Operators
• The return type of the operator function operator+ is of the type OpOverClass
• The function prototype of operator+ in the definition of the class OpOverClass
is:
OpOverClass operator+(const OpOverClass&) const;
General Syntax
• Function Prototype (to be included in the definition of the class):
returnType operator op(className);
• op stands for the binary operator to be overloaded
• returnType is the type of the value returned by the function
• className is the name of the class for which the operator is being overloaded
General Syntax
• Function Prototype (to be included in the definition of the class):
friend returnType operator op(const className&,
const className&);
• op stands for the binary operator to be overloaded
• returnType is the type of the value returned by the function
• className is the name of the class for which the operator is being overloaded
General Syntax
• Function Prototype (to be included in the definition of the class):
friend returnType operator op(const className&,
const className&);
• op stands for the binary operator to be overloaded
• returnType is the type of the value returned by the function
• className is the name of the class for which the operator is being overloaded
General Syntax
• Function Prototype (to be included in the definition of the class):
friend bool operator op(const className&,
const className&);
• op is the relational operator that is being overloaded
• className is the name of the class for the operator op is being overloaded
Overloading ++ and --
• The increment operator has two forms, pre-increment (++u) and post-
increment (u++), where u is a variable, say of the type int
With a pre-increment (++u), the value of u is incremented by 1 before using
Overloading the
Post-Increment Operator
• Overload the post-increment operator for the class OpOverClass
• In both cases, pre- and post-increment, the name of the operator function is
the operator++
• To distinguish between pre- and post-increment operator overloading, we use
a dummy parameter (of the type int) in the function heading of the operator
function
• The function prototype for the post-increment operator for the class
OpOverClass is:
OpOverClass operator++(int);
Templates
• By using templates we write a single code for a set of related functions- called
function template and related classes- called class template
• The syntax for templates is:
template <class Type>
declaration;
where Type is the type of the data and declaration is either a function
declaration or a class declaration
Templates
• In C++, template is a reserved word
The word class in the heading refers to any user-defined type or built-in type
Start here Page 71
• The word class in the heading refers to any user-defined type or built-in type
Type is referred to as a formal parameter to the template Just as variables
are parameters to functions, types (that is, data types) are parameters to
templates
Class Templates
• Class templates are used to write a single code segment for a set of related
classes
• Syntax:
template<class Type>
class declaration
• Class templates are called parameterized types because, based on the
parameter type, a specific class is generated
• A template instantiation can be created with either a built-in or user-defined
type
• The function members of a class template are considered function templates
Header File
• Until now, we have placed the definition of the class and the definition of the
member functions in separate files
• The object code was generated from the implementation file and linked with
the user code
• Passing parameters to a function has an effect at run time, whereas passing a
parameter to a class template has an effect at compile time
Header File
• We can no longer compile the implementation file independently of the client
code because
• the actual parameter to a class is specified in the client code
• the compiler cannot instantiate a function template without the actual
parameter to the template
• We could put the class definition and the definitions of the function templates
directly in the client code, or we could put the class definition and the
definitions of the function templates together in the same header file
Header File
• Another alternative is to put the class definition and the definitions of the
functions in separate files, but include a directive to the implementation file at
the end of the header file In either case, the function definitions and the
client code are compiled together We will put the class definition and the
function definitions in the same header file
Chapter 15
EXCEPTION HANDLING
Exceptions
• Exception: undesirable event detectable during program execution
If exceptions occurred during execution
try/catch Block
• Statements that may generate an exception are placed in a try block The try
block also contains statements that should not be executed if an exception
occurs The try block is followed by one or more catch blocks
try/catch Block
• The catch block specifies the type of exception it can catch and contains an
exception handler If the heading of a catch block contains ... (ellipses) in
place of parameters, then this catch block can catch exceptions of all types
try/catch Block
• The general syntax of the try/catch block is:
try/catch Block
• The program searches the catch blocks in order, looking for an appropriate
exception handler
• If the type of thrown exception matches the parameter type in one of the
catch blocks:
• Code of that catch block executes
• Remaining catch blocks are ignored
Throwing an Exception
• For try/catch to work, the exception must be thrown in the try block
• General syntax to throw an exception is:
throw expression;
where expression is a constant value, variable, or object
Throwing an Exception
• The object being thrown can be
• Specific object
• Anonymous object
• In C++, an exception is a value
• In C++, throw is a reserved word
Throwing an Exception
Stack Unwinding
• When an exception is thrown in, say, a function, the function can do the
following:
• Do nothing
• Partially process the exception and throw the same exception or a new
exception
• Throw a new exception
Stack Unwinding
• In each of these cases, the function-call stack is unwound so that the
exception can be caught in the next try/catch block
• When the function call stack is unwound
• The function in which the exception was not caught and/or rethrown
terminates
• Memory for its local variables is destroyed
Stack Unwinding
• The stack unwinding continues until
• A try/catch handles the exception or
• The program does not handle the exception
• If the program does not handle the exception, then the function terminate is
called to terminate the program
C++ Programming:
Program Design Including
Data Structures, Third Edition
Chapter 16: Recursion
Recursive Definitions
•Recursion: solving a problem by reducing it to smaller versions of itself
• 0! = 1 (1)
n! = n x (n-1)! if n > 0 (2)
•The definition of factorial in equations (1) and (2) is called a recursive definition
•Equation (1) is called the base case
•Equation (2) is called the general case
Recursive Functions
•Think of a recursive function as having infinitely many copies of itself
•Every call to a recursive function has
−Its own code
−Its own set of parameters and local variables
•After completing a particular recursive call
−Control goes back to the calling environment, which is the previous call
Infinite Recursion
•Infinite recursion: every recursive call results in another recursive call
−In theory, infinite recursion executes forever
•Because computer memory is finite:
−Function executes until the system runs out of memory
−Results in an abnormal program termination
Memory allocation
•Whenever a function is called
−Memory space for its formal parameters and (automatic) local variables is
allocated
•When the function terminates
−That memory space is then deallocated
Start here Page 79
−That memory space is then deallocated
•Every (recursive) call has its own set of parameters and (automatic) local
variables
Efficiency
•Overhead associated with executing a (recursive) function in terms of
−Memory space
−Computer time
•A recursive function executes more slowly than its iterative counterpart
Efficiency (continued)
•On slower computers, especially those with limited memory space
−The slow execution of a recursive function would be visible
•Today’s computers are fast and have inexpensive memory
−Execution of a recursion function is not noticeable
Efficiency (continued)
•The choice between the two alternatives depends on the nature of the problem
•For problems such as mission control systems
−Efficiency is absolutely critical and dictates the solution method
Efficiency (continued)
•An iterative solution is more obvious and easier to understand than a recursive
solution
•If the definition of a problem is inherently recursive
−Consider a recursive solution