Day2.1 ProgrammingConcepts

Download as pdf or txt
Download as pdf or txt
You are on page 1of 195

Programming Concepts

(Using C++)

Slide 1
Reference:

Slide 2
Object Oriented
Programming
• Abbreviated OOP

• Used for many modern programs

• Program is viewed as interacting objects


– Each object contains algorithms to describe its behavior
– Program design phase involves designing objects and
their algorithms

Slide 3
OOP Characteristics
• Encapsulation
– Information hiding
– Objects contain their own data and algorithms

• Inheritance
– Writing reusable code
– Objects can inherit characteristics from other objects

• Polymorphism
– A single name can have multiple meanings depending
on its context

Slide 4
C++ History
• C developed by Dennis Ritchie at AT&T
Bell Labs in the 1970s.
– Used to maintain UNIX systems
– Many commercial applications written in c
• C++ developed by Bjarne Stroustrup at AT&T
Bell Labs in the 1980s.
– Overcame several shortcomings of C
– Incorporated object oriented programming
– C remains a subset of C++

Slide 5
C++ Basics

Created by David Mann, North Idaho College


Slide 6
2.1

Variables
• Variables are like small blackboards
– We can write a number on them
– We can change the number
– We can erase the number
• C++ variables are names for memory locations
– We can write a value in them
– We can change the value stored there
– We cannot erase the memory location
• Some value is always there
Slide 7
Identifiers
• Variables names are called identifiers
• Choosing variable names
– Use meaningful names that represent data to
be stored
– First character must be
• a letter
• the underscore character
– Remaining characters must be
• letters
• numbers
• underscore character

Slide 8
Keywords
• Keywords (also called reserved words)
– Are used by the C++ language
– Must be used as they are defined in
the programming language
– Cannot be used as identifiers

Slide 9
Declaring Variables
• Before use, variables must be declared

– Tells the compiler the type of data to store


Examples: int number_of_bars;
double one_weight, total_weight;
– int is an abbreviation for integer.
• could store 3, 102, 3211, -456, etc.
• number_of_bars is of type integer
– double represents numbers with a fractional
component
• could store 1.34, 4.0, -345.6, etc.
• one_weight and total_weight are both of type double
Slide 10
Declaring Variables
Two locations for variable declarations

• Immediately prior to use – At the beginning

int main() int main()


{ {
… int sum;
int sum; …
sum = score1 + score 2; sum = score1 + score2;
… …
return 0; return 0;
} }

Slide 11
Declaring Variables
• Declaration syntax:
– Type_name Variable_1 , Variable_2, . . . ;

• Declaration Examples:
– double average, m_score, total_score;
– double moon_distance;
– int age, num_students;
– int cars_waiting;

Slide 12
Assignment Statements

• An assignment statement changes the value of a variable


– total_weight = one_weight + number_of_bars;
• total_weight is set to the sum one_weight + number_of_bars

– Assignment statements end with a semi-colon

– The single variable to be changed is always on the left


of the assignment operator ‘=‘

– On the right of the assignment operator can be


• Constants -- age = 21;
• Variables -- my_cost = your_cost;
• Expressions -- circumference = diameter * 3.14159;

Slide 13
Assignment Statements
• The ‘=‘ operator in C++ is not an equal sign
– The following statement cannot be true in algebra

number_of_bars = number_of_bars + 3;

– In C++ it means the new value of number_of_bars


is the previous value of number_of_bars plus 3

Slide 14
Initializing Variables
• Declaring a variable does not give it a value
– Giving a variable its first value is initializing the variable
• Variables are initialized in assignment statements
double mpg; // declare the variable
mpg = 26.3; // initialize the variable
• Declaration and initialization can be combined
using two methods
– Method 1
double mpg = 26.3, area = 0.0 , volume;
– Method 2
double mpg(26.3), area(0.0), volume;

Slide 15
2.2

Input and Output

• A data stream is a sequence of data


– Typically in the form of characters or numbers

• An input stream is data for the program to use


– Typically originates
• at the keyboard
• at a file

• An output stream is the program’s output


– Destination is typically
• the monitor
• a file

Slide 16
Include Directives
• Include Directives add library files to our programs
– To make the definitions of the cin and cout available to
the program:
#include <iostream>

• Using Directives include a collection of defined


names
– To make the names cin and cout available to our program:
using namespace std;

Slide 17
2.4

Flow of Control

• Flow of control
– The order in which statements are executed

• Branch
– Lets program choose between two alternatives

Slide 18
Implementing the
Branch
• if-else statement is used in C++ to perform a
branch

– if (hours > 40)


gross_pay = rate * 40 + 1.5 * rate * (hours -
40);
else
gross_pay = rate * hours;

Slide 19
Simple Loops
• When an action must be repeated, a loop is
used
• C++ includes several ways to create loops
• Consider the while-loop
• Example: while (count_down > 0)
{
cout << "Hello ";
count_down -= 1;
}
• Output: Hello Hello Hello
when count_down starts at 3
Slide 20
3.2

Predefined Functions
▪ C++ comes with libraries of predefined
functions

▪ Example: sqrt function


▪ the_root = sqrt(9.0);
▪ returns, or computes, the square root
of a number
▪ The number, 9, is called the argument
▪ the_root will contain 3.0

Slide 21
Function Calls
• sqrt(9.0) is a function call
– It invokes, or sets in action, the sqrt function
– The argument (9), can also be a variable or an
expression
• A function call can be used like any expression
– bonus = sqrt(sales) / 10;
– Cout << “The side of a square with area “ << area
<< “ is “
<< sqrt(area);
Slide 22
Function Call Syntax

• Function_name (Argument_List)
– Argument_List is a comma separated list:

(Argument_1, Argument_2, … , Argument_Last)


• Example:
– side = sqrt(area);
– cout << “2.5 to the power 3.0 is “
<< pow(2.5, 3.0);

Slide 23
Function Libraries
• Predefined functions are found in libraries
• The library must be “included” in a program
to make the functions available
• An include directive tells the compiler which
library header file to include.
• To include the math library containing sqrt():

#include <cmath>
• Newer standard libraries, such as cmath, also require
the directive
using namespace std;
Slide 24
Other Predefined
Functions
• abs(x) --- int value = abs(-8);
– Returns absolute value of argument x
– Return value is of type int
– Argument is of type x
– Found in the library cstdlib
• fabs(x) --- double value = fabs(-8.0);
– Returns the absolute value of argument x
– Return value is of type double
– Argument is of type double
– Found in the library cmath
Slide 25
Type Casting
• Recall the problem with integer division:
int total_candy = 9, number_of_people = 4;
double candy_per_person;
candy_per_person = total_candy / number_of_people;
– candy_per_person = 2, not 2.25!
• A Type Cast produces a value of one type
from another type
– static_cast<double>(total_candy) produces a double
representing the integer value of total_candy

Slide 26
Type Cast Example
• int total_candy = 9, number_of_people = 4;
double candy_per_person;
candy_per_person = static_cast<double>(total_candy)
/ number_of_people;
– candy_per_person now is 2.25!
– This would also work:
candy_per_person = total_candy /
static_cast<double>( number_of_people);
– This would not!
candy_per_person = static_cast<double>( total_candy /
number_of_people);

Integer division occurs before type cast


Slide 27
3.3

User-Defined Functions
• Two components of a function definition
– Function declaration (or function prototype)
• Shows how the function is called
• Must appear in the code before the function can be called
• Syntax:
Type_returned Function_Name(Parameter_List);
//Comment describing what function does
;
– Function definition
• Describes how the function does its task
• Can appear before or after the function is called
• Syntax:
Type_returned Function_Name(Parameter_List)
{
//code to make the function work
}

Slide 28
Function Declaration
• Tells the return type
• Tells the name of the function
• Tells how many arguments are needed
• Tells the types of the arguments
• Tells the formal parameter names
– Formal parameters are like placeholders for the actual
arguments used when the function is called
– Formal parameter names can be any valid identifier
• Example:
double total_cost(int number_par, double price_par);
// Compute total cost including 5% sales tax on
// number_par items at cost of price_par each
Slide 29
Function Definition
• Provides the same information as the declaration
• Describes how the function does its task
function header
• Example:
double total_cost(int number_par, double price_par)
{
const double TAX_RATE = 0.05; //5% tax
double subtotal;
subtotal = price_par * number_par;
return (subtotal + subtotal * TAX_RATE);
}
function body
Slide 30
The Return Statement
• Ends the function call
• Returns the value calculated by the function
• Syntax:
return expression;
– expression performs the calculation
or
– expression is a variable containing the
calculated value
• Example:
return subtotal + subtotal * TAX_RATE;
Slide 31
3.5

Local Variables
• Variables declared in a function:
– Are local to that function, they cannot be used
from outside the function
– Have the function as their scope
• Variables declared in the main part of a
program:
– Are local to the main part of the program, they
cannot be used from outside the main part
– Have the main part as their scope
Slide 32
Global Constants
• Global Named Constant
– Available to more than one function as well as the
main part of the program
– Declared outside any function body
– Declared outside the main function body
– Declared before any function that uses it
• Example: const double PI = 3.14159;
double volume(double);
int main()
{…}
– PI is available to the main function and to function volume
Slide 33
Global Variables

• Global Variable -- rarely used when more


than one function must use a common
variable
– Declared just like a global constant except const
is not used
– Generally make programs more difficult to
understand and maintain

Slide 34
Formal Parameters
are Local Variables
• Formal Parameters are actually variables that
are local to the function definition
– They are used just as if they were declared in the
function body
– Do NOT re-declare the formal parameters in the
function body, they are declared in the function
declaration
• The call-by-value mechanism
– When a function is called the formal parameters
are initialized to the values of the
arguments in the function call
Slide 35
Namespaces Revisited
• The start of a file is not always the best place
for
using namespace std;

• Different functions may use different


namespaces
– Placing using namespace std; inside the starting
brace of a function
• Allows the use of different namespaces in different
functions
• Makes the “using” directive local to the function
Slide 36
4.1

void-Functions
• In top-down design, a subtask might produce
– No value (just input or output for example)
– One value
– More than one value
• We have seen how to implement functions
that return one value
• A void-function implements a subtask that
returns no value or more than one value

Slide 37
void-Function
• Two main differences between void-function
definitions and the definitions of functions
that return one value
– Keyword void replaces the type of the value returned
• void means that no value is returned by the function
– The return statement does not include an expression
• Example:
void show_results(double f_degrees, double c_degrees)
{
using namespace std;
cout << f_degrees
<< “ degrees Fahrenheit is euivalent to “ << endl
<< c_degrees << “ degrees Celsius.” << endl;
return;
}

Slide 38
Using a void-Function

• void-function calls are executable statements


– They do not need to be part of another statement
– They end with a semi-colon
• Example:
show_results(32.5, 0.3);

NOT: cout << show_results(32.5, 0.3);

Slide 39
void-Function Calls
• Mechanism is nearly the same as the function
calls we have seen
– Argument values are substituted for the formal
parameters
• It is fairly common to have no parameters in
void-functions
– In this case there will be no arguments in the function call
– Statements in function body are executed
– Optional return statement ends the function
• Return statement does not include a value to return
• Return statement is implicit if it is not included
Slide 40
Converting Temperatures
• The functions just developed can be used in a
program to convert Fahrenheit temperatures
to
Celcius using the formula

C = (5/9) (F – 32)

– Do you see the integer division problem?


Display 4.2 (1)

Display 4.2 (2)

Slide 41
void-Functions
Why Use a Return?
• Is a return-statement ever needed in a
void-function since no value is returned?
– Yes!
• What if a branch of an if-else statement requires
that the function ends to avoid producing more
output, or creating a mathematical error?
• void-function can avoid division by zero
with a return statement

Slide 42
The Main Function
• The main function in a program is used like a
void function…do you have to end the
program with a return-statement?
– Because the main function is defined to return a
value of type int, the return is needed
– C++ standard says the return 0 can be omitted,
but many compilers still require it

Slide 43
4.2

Call-by-Reference
Parameters
• Call-by-value is not adequate when we need
a sub-task to obtain input values
– Call-by-value means that the formal parameters
receive the values of the arguments
– To obtain input values, we need to change the
variables that are arguments to the function
• Recall that we have changed the values of
formal parameters in a function body, but we have not
changed the arguments found in the function call
• Call-by-reference parameters allow us to change
the variable used in the function call
– Arguments for call-by-reference parameters must be
variables, not numbers
Slide 44
Call-by-Reference Example

• void get_input(double& f_variable)


{
using namespace std;
cout << “ Convert a Fahrenheit temperature”
<< “ to Celsius.\n”
<< “ Enter a temperature in Fahrenheit: “;
cin >> f_variable;
}
• ‘&’ symbol (ampersand) identifies f_variable as a
call-by-reference parameter
– Used in both declaration and definition!
Slide 45
Call-By-Reference Details
• Call-by-reference works almost as if the
argument variable is substituted for the
formal parameter, not the argument’s value
• In reality, the memory location of the
argument variable is given to the formal
parameter
– Whatever is done to a formal parameter in the
function body, is actually done to the value at the
memory location of the argument variable
Slide 46
Call Comparisons
Call By Reference vs Value
• Call-by-reference • Call-by-value
– The function call: – The function call:
f(age); Memory f(age);
Name Location Contents

age 1001 34
initial 1002 A
hours 1003 23.5
1004

void f(int& ref_par); void f(int var_par);


Slide 47
Example: swap_values
• void swap(int& variable1, int& variable2)
{
int temp = variable1;
variable1 = variable2;
variable2 = temp;
}
• If called with swap(first_num, second_num);
– first_num is substituted for variable1 in the parameter list
– second_num is substituted for variable2 in the parameter list
– temp is assigned the value of variable1 (first_num) since the
next line will loose the value in first_num
– variable1 (first_num) is assigned the value in variable2 (second_num)
– variable2 (second_num) is assigned the original value of
variable1 (first_num) which was stored in temp
Slide 48
Mixed Parameter Lists
• Call-by-value and call-by-reference parameters
can be mixed in the same function

• Example:
void good_stuff(int& par1, int par2, double& par3);
– par1 and par3 are call-by-reference formal parameters
• Changes in par1 and par3 change the argument variable
– par2 is a call-by-value formal parameter
• Changes in par2 do not change the argument variable

Slide 49
Choosing Parameter Types

• How do you decide whether a call-by-


reference or call-by-value formal parameter is
needed?
– Does the function need to change the value of the
variable used as an argument?
– Yes? Use a call-by-reference formal parameter
– No? Use a call-by-value formal parameter

Slide 50
Inadvertent Local
Variables
• If a function is to change the value of a variable
the corresponding formal parameter must be a
call-by-reference parameter with an ampersand
(&) attached
• Forgetting the ampersand (&) creates a
call-by-value parameter
– The value of the variable will not be changed
– The formal parameter is a local variable that has no
effect outside the function
– Hard error to find…it looks right!
Slide 51
4.3

Using Procedural Abstraction

• Functions should be designed so they can be


used as black boxes
• To use a function, the declaration and
comment should be sufficient
• Programmer should not need to know the
details of the function to use it

Slide 52
Functions Calling Functions
• A function body may contain a call to another
function
– The called function declaration must still appear
before it is called
• Functions cannot be defined in the body of another function
– Example: void order(int& n1, int& n2)
{
if (n1 > n2)
swap_values(n1, n2);
}
• swap_values called if n1 and n2 are not in ascending
order
• After the call to order, n1 and n2 are in ascending order
Slide 53
Pre and Postconditions
• Precondition
– States what is assumed to be true when the function
is called
• Function should not be used unless the precondition holds
• Postcondition
– Describes the effect of the function call
– Tells what will be true after the function is executed
(when the precondition holds)
– If the function returns a value, that value is described
– Changes to call-by-reference parameters are described

Slide 54
swap_values revisited
• Using preconditions and postconditions the
declaration of swap_values becomes:

void swap_values(int& n1, int& n2);


//Precondition: variable1 and variable 2
have
// been given values
// Postcondition: The values of variable1 and
// variable2 have been
// interchanged
Slide 55
Function celsius
• Preconditions and postconditions make the
declaration for celsius:

double celsius(double farenheit);


//Precondition: fahrenheit is a temperature
// expressed in degrees Fahrenheit
//Postcondition: Returns the equivalent temperature
// expressed in degrees Celsius

Slide 56
Why use preconditions
and postconditions?
• Preconditions and postconditions
– should be the first step in designing a function
– specify what a function should do
• Always specify what a function should do before
designing how the function will do it
– Minimize design errors
– Minimize time wasted writing code that doesn’t
match the task at hand

Slide 57
Case Study
Supermarket Pricing
• Problem definition
– Determine retail price of an item given suitable
input
– 5% markup if item should sell in a week
– 10% markup if item expected to take more than a
week
• 5% for up to 7 days, changes to 10% at 8 days
– Input
• The wholesale price and the estimate of days until item
sells
– Output
• The retail price of the item
Slide 58
Supermarket Pricing:
Problem Analysis
• Three main subtasks
– Input the data
– Compute the retail price of the item
– Output the results
• Each task can be implemented with a function
– Notice the use of call-by-value and
call-by-reference parameters in the following
function declarations

Slide 59
Supermarket Pricing:
Function get_input
• void get_input(double& cost, int& turnover);
//Precondition: User is ready to enter values
// correctly.
//Postcondition: The value of cost has been set to
// the wholesale cost of one item.
// The value of turnover has been
// set to the expected number of
// days until the item is sold.

Slide 60
Supermarket Pricing:
Function price
• double price(double cost, int turnover);
//Precondition: cost is the wholesale cost of
one
// item. turnover is the expected
// number of days until the item
is
// sold.
//Postcondition: returns the retail price of the
item
Slide 61
Supermarket Pricing:
Function give_output
• void give_output(double cost, int turnover, double
price);
//Precondition: cost is the wholesale cost of one
item;
// turnover is the expected time until
sale
// of the item; price is the retail price of
// the item.
//Postcondition: The values of cost, turnover, and
price
// been written to the screen.

Slide 62
Supermarket Pricing:
The main function
• With the functions declared, we can write the
main function:
int main()
{
double wholesale_cost, retail_price;
int shelf_time;
get_input(wholesale_cost, shelf_time);
retail_price = price(wholesale_cost, shelf_time);
give_output(wholesale_cost, shelf_time,
retail_price);
return 0;
}

Slide 63
Supermarket Pricing:
Algorithm Design -- price
• Implementations of get_input and
give_output
are straightforward, so we concentrate on
the price function
• pseudocode for the price function
– If turnover <= 7 days then
return (cost + 5% of cost);
else
return (cost + 10% of cost);

Slide 64
Supermarket Pricing:
Constants for The price Function
• The numeric values in the pseudocode will be
represented by constants
– Const double LOW_MARKUP = 0.05; // 5%
– Const double HIGH_MARKUP = 0.10; // 10%
– Const int THRESHOLD = 7; // At 8 days use
//HIGH_MARKUP

Slide 65
Supermarket Pricing:
Coding The price Function
• The body of the price function
–{
if (turnover <= THRESHOLD)
return ( cost + (LOW_MARKUP * cost) ) ;
else
return ( cost + ( HIGH_MARKUP * cost) ) ;
}

Slide 66
Supermarket Pricing :
Program Testing

• Testing strategies
– Use data that tests both the high and low markup cases
– Test boundary conditions, where the program is expected
to change behavior or make a choice
• In function price, 7 days is a boundary condition
• Test for exactly 7 days as well as one day more and one day less

Slide 67
Exception Handling

Slide 68
Overview

▪ Exception Handling Basics


▪ Programming Techniques for
Exception Handling

Slide 69
17.1

Exception Handling Basics

• It is often easier to write a program by first


assuming that nothing incorrect will happen
• Once it works correctly for the expected
cases, add code to handle the exceptional
cases
• Exception handling is commonly used to
handle error situations
– Once an error is handled, it is no longer an error

Slide 70
Functions and
Exception Handling
• A common use of exception handling:
– Functions with a special case that is handled in
different ways depending on how the function is
used
– If the function is used in different programs, each
program may require a different action when the
special case occurs

Slide 71
Exception Handling
Mechanism
• In C++, exception handling proceeds by:
– Some library software or your code signals that
something unusual has happened
– This is called throwing an exception
– At some other place in your program you place
the code that deals with the exceptional case
– This is called handling the exception

Slide 72
A Toy Example
• Exception handling is meant to be used
sparingly in situations that are generally not
reasonable introductory examples
• For this example:
– Suppose milk is so important that we almost never
run out
– We still would like our program to handle the
situation of running out of milk

Slide 73
The Milk Example (cont.)
• Code to handle the normal situations
involving milk, might be:
cout << "Enter number of donuts:\n";
cin >> donuts;
cout << "Enter number of glasses of milk:\n";
cin >> milk;
dpg = donuts /static_cast<double>(milk);
cout << donuts << " donuts.\n"
<< milk << " glasses of milk.\n"
<< "You have " << dpg
<< " donuts per glass of milk.\n";
Slide 74
The No Milk Problem
• If there is no milk, the code on the previous
slide results in a division by zero
– We could add a test case for this situation

Slide 75
The try Block
• The program replaces the test case in the if-
else statement with
if(milk <= 0)
throw donuts;
• This code is found in the try block
try
{
Some_Code
}
which encloses the code to handle the normal
situations
Slide 76
The Try Block Outline
• The try block encloses code that you want to
"try" but that could cause a problem
• The basic outline of a try block is:

try
{
Code_To_Try
Possibly_Throw_An_Exception
More_Code
}

Slide 77
The Exception
• To throw an exception, a throw-statement is
used to throw a value
– In the milk example:
throw donuts;
throws an integer value.
– The value thrown is sometimes called an
exception
– You can throw a value of any type

Slide 78
The catch-block
• Something that is thrown goes from one place
to another
• In C++ throw causes the flow of control to go
to another place
– When an exception is thrown, the try block stops
executing and the catch-block begins execution
– This is catching or handling the exception

Slide 79
The Milk catch-block
• The catch-block from the milk example looks
like, but is not, a function definition with a
parameter:
catch(int e)
{
cout << e << donuts, and no milk!\n"
<< "Go buy some milk.\n";
}
– If no exception is thrown, the catch-block is
ignored during program execution

Slide 80
The catch-block Parameter

• The catch-block parameter, (recall that the


catch-block is not a function) does two things:
– The type of the catch-block parameter identifies
the kind of value the catch-block can catch
– The catch-block parameter provides a name for
the value caught so you can write code using the
value that is caught

Slide 81
try-blocks and if-else
• try-blocks are very similar to if-else
statements
– If everything is normal, the entire try-block is
executed
– else, if an exception is thrown, the catch-block is
executed
• A big difference between try-blocks and if-else
statements is the try-block's ability to send a
message to one of its branches
Slide 82
try-throw-catch Review
• This is the basic mechanism for throwing and
catching exceptions
– The try-block includes a throw-statement
– If an exception is thrown, the try-block ends and
the catch-block is executed
– If no exception is thrown, then after the try-block
is completed, execution continues with the code
following the catch-block(s)

Slide 83
Defining an Exception Class
• Because a throw-statement can throw a value of
any type, it is common to define a class whose
objects can carry the kind of information you
want thrown to the catch-block
• A more important reason for a specialized
exception class is so you can have a different
type to identify each possible kind of exceptional
situation

Slide 84
The Exception Class
• An exception class is just a class that happens
to be used as an exception class

Slide 85
Throwing a Class Type
• The program uses the throw-statement
throw NoMilk(donuts);
– This invokes a constructor for the class NoMilk
– The constructor takes a single argument of type
int
– The NoMilk object is what is thrown
– The catch-block then uses the statement
e.get_donuts( )
to retrieve the number of donuts

Slide 86
Multiple Throws and
Catches
• A try-block can throw any number of
exceptions
of different types
– In any one execution, only one exception can be
thrown
– Each catch-block can catch only one exception
– Multiple catch-blocks may be used
• A parameter is not required in a catch-block

Slide 87
A Default catch-block
• When catching multiple exceptions, write the
catch-blocks for the most specific exceptions
first
– Catch-blocks are tried in order and the first one
matching the type of exception is executed
• A default (and last) catch-block to catch any
exception can be made using "…" as the
catch-block parameter
catch(…)
{ <the catch block code> }
Slide 88
Exception Class
DivideByZero
• Suppose an exception class DivideByZero
was defined as
class DivideByZero
{};
– This class has no member variables or member functions
– This is a trivial exception class
– DivideByZero is used simply to activate the appropriate
catch-block
– There is nothing to do with the catch-block parameter so
it can be omitted as shown in Display 17.4

Slide 89
Exceptions In Functions
• In some cases, an exception generated in a
function is not handled in the function
– It might be that some programs should end, while
others might do something else, so within the
function
you might not know how to handle the exception
• In this case, the program places the function
invocation in a try block and catches the
exception in a following catch-block
Slide 90
Function safe_divide
• The program of Display 17.5 includes a
function that throws, but does not catch an
exception
– In function safe_divide, the denominator is
checked
to be sure it is not zero. If it is zero, an exception
is thrown:
if (bottom == 0)
throw DivideByZero( );
– The call to function safe_divide is found in the try-block of
the program

Slide 91
Exception Specification
• If a function does not catch an exception it should
warn programmers than an exception might be
thrown by the function
– An exception specification, also called a throw list,
appears in the function declaration and definition:

double safe_divide(int n, int d) throw (DivideByZero);


– if multiple exceptions are thrown and not caught by a function:
double safe_divide(int n, int d)
throw (DivideByZero, OtherException);

Slide 92
Exceptions Not Listed
• If an exception is not listed in an exception
specification and not caught by the function:
– The program ends
• If there is no exception specification at all, it is
the same as if all possible exceptions are listed
– These exceptions will be treated "normally"
• An empty exception specification list means that
no exceptions should be thrown and not caught

Slide 93
Sample
Exception Specifications
• void some_function ( ) throw ( );
//empty exception list; so all exceptions not
// caught by the function end the program
• void some_function( ) throw(DivideByZero,
OtherException);
//Exceptions DivideByZero and OtherException
//treated normally. All others end the program
• void some_function( );
// All exceptions of all types treated normally
// If not caught by a catch-block, the program ends

Slide 94
Derived Classes and Exceptions
• Remember that an object of a derived class is
also an object of the base class
– If D is a derived class of B and B is in an exception
specification
• A thrown object of class D will be treated normally
since
it is an object of class B

Slide 95
Type Conversion
• No automatic type conversions are done with
exceptions
– if double is in the exception specification, an int
cannot be thrown unless int is also in the
exception
specification

Slide 96
Function Redefinitions in
Derived Classes
• Functions redefined or overloaded in derived
classes should have the same exception
specification as in the base class
– The exception specification can be a subset of the
exception specification in the base class
• You cannot add exceptions

Slide 97
17.2

Programming Techniques
for Exception Handling
• A guideline for exception handling is to
separate throwing an exception and catching
an exception into separate functions
– Place the throw-statement in one function and list
the exception in the exception specification
– Place the function invocation and catch-clause
in a try-block of a different function

Slide 98
try and throw…Again
• Here is a general example the approach to use
in using throw:

void functionA( ) throw (MyException)


{

throw MyException(<an argument?>);
}

Slide 99
catch…again
• Using FunctionA from the previous slide, here
is how to catch MyException:
void functionB( )
{

try
{

functionA( );

}
catch(MyException e)
{
< handle the exception>
}
}

Slide 100
When to Throw An Exception

• Throwing exceptions is generally reserved for


those cases when handling the exceptional case
depends on how and where the function was
invoked
– In these cases it is usually best to let the programmer
calling the function handle the exception
– An uncaught exception ends your program
• If you can easily write code to handle the
problem
do not throw an exception

Slide 101
Nested try-catch Blocks
• Although a try-block followed by its catch-block
can be nested inside another try-block
– It is almost always better to place the nested
try-block and its catch-block inside a function
definition, then invoke the function in the outer
try-block
• An error thrown but not caught in the inner
try-catch-blocks is thrown to the outer try-block
where it might be caught

Slide 102
Overuse of Exceptions
• Throwing an exception allows you to transfer
flow of control to almost any place in your
program
• Such un-restricted flow of control is generally
considered poor programming style as it makes
programs difficult to understand
• Exceptions should be used sparingly and only
when you cannot come up with an alternative
that
produces reasonable code
Slide 103
Exception Class Hierarchies
• It can be useful to define a hierarchy of
exception
classes.
– You might have an ArithmeticError exception class
with DivideByZeroError as a derived class
– Since a DivideByZeroError object is also an
ArithmeticError object, every catch-block for an
ArithmeticError will also catch a DivideByZeroError

Slide 104
Checking For Available
Memory
• The new operator allocates memory from the
freestore: NodePtr pointer = new Node;
– What if there is no memory available?
– bad_alloc is a predefined exception and can be used
in this way since new throws a bad_alloc exception:
try
{
NodePtr pointer = new Node;
}
catch(bad_alloc)
{
cout << "Ran out of memory!";
}

Slide 105
Rethrowing an Exception

• The code within a catch-block can throw


an exception
– This feature can be used to pass the same or a
different exception up the chain of exception
handling blocks

Slide 106
Display 17.1
Back Next

Slide 107
Display 17.2
(1/2) Back Next

Slide 108
Display 17.2
Next
(2/2) Back

Slide 109
Display 17.3
(1/2) Back Next

Slide 110
Display 17.3
(2/2) Back Next

Slide 111
Display 17.4
(1/3)Back Next

Slide 112
Display 17.4
(2/3)Back Next

Slide 113
Display 17.4
(3/3)Back Next

Slide 114
Display 17.5
(1/2)Back Next

Slide 115
Display 17.5
(2/2)Back Next

Slide 116
Defining Classes

Slide 117
Overview
▪ Introduction
▪ Structures
▪ Classes
▪ Abstract Data Types

Slide 118
What Is a Class?
• A class is a data type whose variables are
objects
• Some pre-defined classes you have used are
– int
– char
– ifstream
• You can define your own classes as well

Slide 119
Class Definitions

• A class definition includes


– A description of the kinds of values the variable
can hold
– A description of the member functions

• We will start by defining structures as a first


step toward defining classes

Slide 120
6.1
Structures
• A structure can be viewed as an object
– Contains no member functions
(The structures used here have no member functions)

– Contains multiple values of possibly different types


• The multiple values are logically related as a single item
• Example: A bank Certificate of Deposit (CD)
has the following values:
a balance
an interest rate
a term (months to maturity)

Slide 121
The CD Definition
• The Certificate of Deposit structure can be
defined as
struct CDAccount
{
double balance;
double interest_rate;
int term; //months to maturity
}; Remember this semicolon!
• Keyword struct begins a structure definition
• CDAccount is the structure tag or the structure’s
type
• Member names are identifiers declared in the braces

Slide 122
Using the Structure
• Structure definition is generally placed outside
any function definition
– This makes the structure type available to all code
that follows the structure definition
• To declare two variables of type CDAccount:

CDAccount my_account, your_account;


– My_account and your_account contain distinct
member variables balance, interest_rate, and
term
Slide 123
The Structure Value
• The Structure Value
– Consists of the values of the member variables

• The value of an object of type CDAccount


– Consists of the values of the member variables

balance
interest_rate
term

Slide 124
Specifying Member
Variables
• Member variables are specific to the
structure variable in which they are declared
– Syntax to specify a member variable:
Structure_Variable_Name . Member_Variable_Name

– Given the declaration:


CDAccount my_account, your_account;
• Use the dot operator to specify a member variable
my_account.balance
my_account.interest_rate
my_account.term

Slide 125
Using Member Variables

• Member variables can be used just as any


other variable of the same type
– my_account.balance = 1000;
your_account.balance = 2500;
• Notice that my_account.balance and
your_account.balance
are different variables!
– my_account.balance = my_account.balance + interest;

Slide 126
Duplicate Names
• Member variable names duplicated between
structure types are not a problem.
struct FertilizerStock struct CropYield
{ {
double quantity; int quantity;
double nitrogen_content; double size;
}; };

FertilizerStock super_grow; CropYield apples;


• super_grow.quantity and apples.quantity are
different variables stored in different locations

Slide 127
Structures as Arguments

• Structures can be arguments in function calls


– The formal parameter can be call-by-value
– The formal parameter can be call-by-reference
• Example:
void get_data(CDAccount& the_account);
– Uses the structure type CDAccount we saw earlier
as the type for a call-by-reference parameter

Slide 128
Structures as Return Types

• Structures can be the type of a value returned


by a function
• Example:
CDAccount shrink_wrap(double the_balance,
double the_rate,
int the_term)
{
CDAccount temp;
temp.balance = the_balance;
temp.interest_rate = the_rate;
temp.term = the_term;
return temp;
}

Slide 129
Using Function shrink_wrap
• shrink_wrap builds a complete structure value
in temp, which is returned by the function
• We can use shrink_wrap to give a variable of
type CDAccount a value in this way:

CDAccount new_account;
new_account = shrink_wrap(1000.00, 5.1,
11);

Slide 130
Assignment and Structures

• The assignment operator can be used to


assign
values to structure types
• Using the CDAccount structure again:
CDAccount my_account, your_account;
my_account.balance = 1000.00;
my_account.interest_rate = 5.1;
my_account.term = 12;
your_account = my_account;
– Assigns all member variables in your_account the
corresponding values in my_account
Slide 131
Hierarchical Structures
• Structures can contain member variables that are
also structures
struct Date struct PersonInfo
{ {
int month; double height;
int day; int weight;
int year; Date birthday;
}; };

• struct PersonInfo contains a Date structure

Slide 132
Using PersonInfo
• A variable of type PersonInfo is declared by
PersonInfo person1;
• To display the birth year of person1, first access the
birthday member of person1

cout << person1.birthday…

But we want the year, so we now specify the


year member of the birthday member

cout << person1.birthday.year;


Slide 133
Initializing Classes
• A structure can be initialized when declared
• Example:
struct Date
{
int month;
int day;
int year;
};
– Can be initialized in this way
Date due_date = {12, 31, 2004};

Slide 134
6.2
Classes
• A class is a data type whose variables are
objects
– The definition of a class includes
• Description of the kinds of values of the member
variables
• Description of the member functions
– A class description is somewhat like a
structure
definition plus the member variables

Slide 135
A Class Example
• To create a new type named DayOfYear as
a class definition
– Decide on the values to represent
– This example’s values are dates such as July 4
using an integer for the number of the month

• Member variable month is an int (Jan = 1, Feb = 2, etc.)


• Member variable day is an int
– Decide on the member functions needed
– We use just one member function named output

Slide 136
Class DayOfYear Definition
class DayOfYear
{
public:
void output( );
int month;
int day;
};
Member Function Declaration

Slide 137
Defining a Member Function

• Member functions are declared in the class


declaration
• Member function definitions identify the class
in which the function is a member
– void DayOfYear::output()
{
cout << “month = “ << month
<< “, day = “ << day
<< endl;
}

Slide 138
Member Function Definition

• Member function definition syntax:


Returned_Type Class_Name::Function_Name(Parameter_List)
{
Function Body Statements
}
– Example: void DayOfYear::output( )
{
cout << “month = “ << month
<< “, day = “ << day << endl;
}

Slide 139
The ‘::’ Operator
• ‘::’ is the scope resolution operator
– Tells the class a member function is a member of

– void DayOfYear::output( ) indicates that function


output is a member of the DayOfYear class

– The class name that precedes ‘::’ is a type


qualifier

Slide 140
‘::’ and ‘.’
• ‘::’ used with classes to identify a member
void DayOfYear::output( )
{
// function body
}

• ‘.’used with variables to identify a member


DayOfYear birthday;
birthday.output( );

Slide 141
Calling Member Functions

• Calling the DayOfYear member function


output
is done in this way:
DayOfYear today, birthday;
today.output( );
birthday.output( );
– Note that today and birthday have their own
versions of the month and day variables for use
by the output function
Slide 142
Encapsulation

• Encapsulation is
– Combining a number of items, such as variables
and functions, into a single package such as an
object of a class

Slide 143
Problems With DayOfYear

• Changing how the month is stored in the class


DayOfYear requires changes to the program
• If we decide to store the month as three
characters (JAN, FEB, etc.) instead of an int
– cin >> today.month will no longer work because
we now have three character variables to read
– if(today.month == birthday.month) will no longer
work to compare months
– The member function “output” no longer works

Slide 144
Ideal Class Definitions

• Changing the implementation of DayOfYear


requires changes to the program that uses
DayOfYear
• An ideal class definition of DayOfYear could
be changed without requiring changes to
the program that uses DayOfYear

Slide 145
Fixing DayOfYear

• To fix DayOfYear
– We need to add member functions to use when
changing or accessing the member variables
• If the program never directly references the member
variables, changing how the variables are stored will
not
require changing the program
– We need to be sure that the program does not
ever
directly reference the member variables

Slide 146
Public Or Private?

• C++ helps us restrict the program from directly


referencing member variables
– private members of a class can only be referenced
within the definitions of member functions
• If the program tries to access a private member, the
compiler gives an error message
– Private members can be variables or functions

Slide 147
Private Variables
• Private variables cannot be accessed directly
by the program
– Changing their values requires the use of public
member functions of the class
– To set the private month and day variables in a
new
DayOfYear class use a member function such as
void DayOfYear::set(int new_month, int new_day)
{
month = new_month;
day = new_day;
}

Slide 148
Public or Private Members

• The keyword private identifies the members of


a class that can be accessed only by member
functions of the class
– Members that follow the keyword private are
private members of the class
• The keyword public identifies the members of
a class that can be accessed from outside the
class
– Members that follow the keyword public are public
members of the class

Slide 149
A New DayOfYear

• The new DayOfYear class demonstrated in


Display 6.4…
– Uses all private member variables
– Uses member functions to do all manipulation of
the
private member variables
• Member variables and member function definitions can
be
changed without changes to the
program that uses DayOfYear

Slide 150
Using Private Variables

• It is normal to make all member variables


private
• Private variables require member functions to
perform all changing and retrieving of values
– Accessor functions allow you to obtain the
values of member variables
• Example: get_day in class DayOfYear
– Mutator functions allow you to change the values
of member variables
• Example: set in class DayOfYear

Slide 151
General Class Definitions
• The syntax for a class definition is
– class Class_Name
{
public:
Member_Specification_1
Member_Specification_2

Member_Specification_3
private:
Member_Specification_n+1
Member_Specification_n+2

};

Slide 152
Declaring an Object

• Once a class is defined, an object of the class


is
declared just as variables of any other type
– Example: To create two objects of type Bicycle:
class Bicycle
{
// class definition lines
};

Bicycle my_bike, your_bike;

Slide 153
The Assignment Operator

• Objects and structures can be assigned values


with the assignment operator (=)
– Example:
DayOfYear due_date, tomorrow;

tomorrow.set(11, 19);

due_date = tomorrow;

Slide 154
Program Example:
BankAccount Class
• This bank account class allows
– Withdrawal of money at any time
– All operations normally expected of a bank
account
(implemented with member functions)
– Storing an account balance
– Storing the account’s interest rate

Slide 155
Calling Public Members

• Recall that if calling a member function from


the
main function of a program, you must include
the the object name:
account1.update( );

Slide 156
Calling Private Members

• When a member function calls a private


member function, an object name is not used
– fraction (double percent);
is a private member of the BankAccount class
– fraction is called by member function update
void BankAccount::update( )
{
balance = balance + fraction(interest_rate)* balance;
}

Slide 157
Constructors
• A constructor can be used to initialize member
variables when an object is declared
– A constructor is a member function that is usually
public
– A constructor is automatically called when an object
of the class is declared
– A constructor’s name must be the name of the class
– A constructor cannot return a value
• No return type, not even void, is used in declaring or
defining a constructor

Slide 158
Constructor Declaration
• A constructor for the BankAccount class could
be declared as:
class BankAccount
{
public:
BankAccount(int dollars, int cents, double rate);
//initializes the balance to $dollars.cents
//initializes the interest rate to rate percent
…//The rest of the BankAccount definition
};

Slide 159
Constructor Definition
• The constructor for the BankAccount class
could be defined as
BankAccount::BankAccount(int dollars, int cents, double
rate)
{
if ((dollars < 0) || (cents < 0) || ( rate < 0 ))
{
cout << “Illegal values for money or rate\n”;
exit(1);
}
balance = dollars + 0.01 * cents;
interest_rate = rate;
}
– Note that the class name and function name are the same

Slide 160
Calling A Constructor

• A constructor is not called like a normal


member function:

BankAccount account1;

account1.BankAccount(10, 50, 2.0);

Slide 161
Calling A Constructor

• A constructor is called in the object


declaration

BankAccount account1(10, 50, 2.0);

– Creates a BankAccount object and calls the


constructor to initialize the member variables

Slide 162
Overloading Constructors

• Constructors can be overloaded by defining


constructors with different parameter lists
– Other possible constructors for the BankAccount
class might be

BankAccount (double balance, double


interest_rate);
BankAccount (double balance);
BankAccount (double interest_rate);
BankAccount ( );

Slide 163
The Default Constructor
• A default constructor uses no parameters
• A default constructor for the BankAccount class
could be declared in this way
class BankAccount
{
public:
BankAccount( );
// initializes balance to $0.00
// initializes rate to 0.0%
… // The rest of the class definition
};

Slide 164
Default Constructor
Definition
• The default constructor for the BankAccount
class could be defined as
BankAccount::BankAccount( )
{
balance = 0;
rate = 0.0;
}
• It is a good idea to always include a default
constructor even if you do not want to initialize
variables

Slide 165
Calling Default Constructor

• The default constructor is called during


declaration of an object
– An argument list is not used

BankAccount account1;
// uses the default BankAccount
constructor

BankAccount account1( );
// Is not legal

Slide 166
Initialization Sections

• An initialization section in a function definition


provides an alternative way to initialize
member variables
– BankAccount::BankAccount( ): balance(0),
interest_rate(0.0);

{
// No code needed in this example
}
– The values in parenthesis are the initial values for
the member variables listed

Slide 167
Parameters and Initialization
• Member functions with parameters can use
initialization sections
BankAccount::BankAccount(int dollars, int cents, double
rate)
: balance (dollars + 0.01 *
cents),
interest_rate(rate)
{
if (( dollars < 0) || (cents < 0) || (rate < 0))
{
cout << “Illegal values for money or rate\n”;
exit(1);
}
}
– Notice that the parameters can be arguments in the initialization

Slide 168
6.3
Abstract Data Types

• A data type consists of a collection of values


together with a set of basic operations
defined on the values
• A data type is an Abstract Data Type (ADT)
if programmers using the type do not have
access to the details of how the values and
operations are implemented

Slide 169
Classes To Produce ADTs

• To define a class so it is an ADT


– Separate the specification of how the type is used
by a programmer from the details of how the type
is implemented
– Make all member variables private members
– Basic operations a programmer needs should be
public member functions
– Fully specify how to use each public function
– Helper functions should be private members

Slide 170
ADT Interface
• The ADT interface tells how to use the ADT in
a program
– The interface consists of
• The public member functions
• The comments that explain how to use the functions
– The interface should be all that is needed to know
how to use the ADT in a program

Slide 171
ADT Implementation
• The ADT implementation tells how the
interface is realized in C++
– The implementation consists of
• The private members of the class
• The definitions of public and private member functions
– The implementation is needed to run a program
– The implementation is not needed to write the
main part of a program or any non-member
functions

Slide 172
ADT Benefits
• Changing an ADT implementation does
require
changing a program that uses the ADT
• ADT’s make it easier to divide work among
different programmers
– One or more can write the ADT
– One or more can write code that uses the ADT
• Writing and using ADTs breaks the larger
programming task into smaller tasks

Slide 173
Program Example
The BankAccount ADT
• In this version of the BankAccount ADT
– Data is stored as three member variables
• The dollars part of the account balance
• The cents part of the account balance
• The interest rate
– This version stores the interest rate as a fraction

Slide 174
Interface Preservation
• To preserve the interface of an ADT so that
programs using it do not need to be changed
– Public member declarations cannot be changed
– Public member definitions can be changed
– Private member functions can be added, deleted,
or changed

Slide 175
Information Hiding
• Information hiding was refered to earlier as
writing functions so they can be used like
black boxes
• ADT’s implement information hiding because
– The interface is all that is needed to use the ADT
– Implementation details of the ADT are not needed
to know how to use the ADT
– Implementation details of the data values are not
needed to know how to use the ADT

Slide 176
Display 6.1
(1/2) Back Next

Slide 177
Display 6.1
(2/2) Back Next

Slide 178
Display 6.2
Back Next

Slide 179
Display 6.3
(1/2) Back Next

Slide 180
Display 6.3
(2/2) Back Next

Slide 181
Display 6.4
(1/3) Back Next

Slide 182
Display 6.4
(2/3) Back Next

Slide 183
Display 6.4
(3/3) Back Next

Slide 184
Display 6.5
(1/4) Back Next

Slide 185
Display 6.5
(2/4) Back Next

Slide 186
Display 6.5
(3/4) Back Next

Slide 187
Display 6.5
(4/4) Back Next

Slide 188
Display 6.6
(1/3) Back Next

Slide 189
Display 6.6
(2/3) Back Next

Slide 190
Display 6.6
(3/3) Back Next

Slide 191
Display 6.7
(1/4) Back Next

Slide 192
Display 6.7
(2/4)Back Next

Slide 193
Display 6.7
(3/4) Back Next

Slide 194
Display 6.7
(4/4)Back Next

Slide 195

You might also like