Day2.1 ProgrammingConcepts
Day2.1 ProgrammingConcepts
Day2.1 ProgrammingConcepts
(Using C++)
Slide 1
Reference:
Slide 2
Object Oriented
Programming
• Abbreviated OOP
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
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
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
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;
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
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>
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
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
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:
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);
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
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;
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
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)
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
age 1001 34
initial 1002 A
hours 1003 23.5
1004
• 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
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
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:
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
Slide 69
17.1
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
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:
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:
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
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
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
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)
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:
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
Slide 125
Using Member Variables
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;
}; };
Slide 127
Structures as Arguments
Slide 128
Structures as Return Types
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
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
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
Slide 136
Class DayOfYear Definition
class DayOfYear
{
public:
void output( );
int month;
int day;
};
Member Function Declaration
Slide 137
Defining a Member Function
Slide 138
Member Function Definition
Slide 139
The ‘::’ Operator
• ‘::’ is the scope resolution operator
– Tells the class a member function is a member of
Slide 140
‘::’ and ‘.’
• ‘::’ used with classes to identify a member
void DayOfYear::output( )
{
// function body
}
Slide 141
Calling Member Functions
• 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
Slide 144
Ideal Class Definitions
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?
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
Slide 149
A New DayOfYear
Slide 150
Using Private Variables
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
Slide 153
The Assignment Operator
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
Slide 156
Calling Private Members
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
BankAccount account1;
Slide 161
Calling A Constructor
Slide 162
Overloading Constructors
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
BankAccount account1;
// uses the default BankAccount
constructor
BankAccount account1( );
// Is not legal
Slide 166
Initialization Sections
{
// 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
Slide 169
Classes To Produce ADTs
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