Title: Professor: Munehiro Fukuda
1CSS342 Objects and Classes
- Professor Munehiro Fukuda
2Todays Topics
- Class
- Encapsulation and information hiding
- From a abstract data specification to a class
design - Examples
- List a list of students
- Interface and implementation
- Constructors and destructors
- Rational rational numbers
- Operator overloading
3Encapsulation and Information Hiding
Class
- Wall Not only encapsulate the entire
implementation but also make it
invisible/inaccessible. - Slit Interface of the implementation such as
arguments and a return value.
Program that uses method S
Function call with arguments
Return a value
4Class
Class
- Classes a new data type formed of a collection
of data and a set of operations on the data - Data Structures a construct within a programming
language that stores a collection of data
Behave as a new data type
- Examples
- student lists
- rational numbers
- complex numbers
- currency (cents/dollars)
- length measurement (inches/feet)
- weight measurement (oz/lbs)
Program that uses a class
5List Class Specification
Class
6List Operations Spec.
Class
- create( )
- creates an empty list.
- destroy( )
- destroys a list.
- insert( int index, Student item)
- insert an item in front of the position index.
Return true in success. - remove( int index )
- remove the item at the position index. Return
true in success. - retrieve( int index, Student item )
- retrieve the item at the position index, store it
in item, and return true in success. - getLength( )
- return the number of items in a list.
- isEmpty( )
- return true if the number of items is 0.
7C Class
Class
public
data members
member functions/methods
Sorting depends on an implementation.
create( )/constructor
destroy( )/destructor
insert( )
remove( )
retrieve( )
getLength( )
isEmpty( )
Utility_func1( )
Utility_func2( )
private
8C Header and Implementation File
Class
- Header File (.h)
- Write a class specification
- Summary of the class usage and behavior
- Public member function prototypes
- Private data members
- Private member function prototypes
- Implementation File (.cpp)
- Code an implementation of each member function
- ClassNamefunctionName
- Function spec (pre/postconditions) in comments
- The body of function with appropriate comments
9List Header list.h
Example List
ifndef _List_H_ // do not process below if this
header has been already read by a
compiler define _List_H_ // define _List_H_ so
that this header file will be never read again by
a compiler // Summary of the class usage and
behavior const int MAX_LIST 100 typedef
Student ListItemType // typedef int
ListItemType in the following slides class
List Public List( ) // a
constructor // destructor is supplied by
compiler bool isEmpty( ) const // returns
true when a list has no items. int getLength( )
const // comments on each method bool insert(
int index, ListItemtype newItem ) bool remove(
int index ) bool retrieve( int index,
ListItemTpe dataItem ) const priate
vectorltListItemtypegt items // array
implementation int size // of items int
translate( int index ) const // tranlate the
index into the corresponding position endif
10An Array Implementation of List Classlist.cpp
Example List
11Constructor
Example List
- A method that describes how an instance of the
class is created
Example 1 List( ) items.resize( MAX_LIST
) List( int initSize ) if (initSize gt
0 ) items.resize( initSize ) else
items.resize( MAX_LIST ) Example
2 MyClass( int initialValue 0 ) myData(
initialValue)
List list
List list(10)
MyClass m
MyClass m(10)
Initializer List
12Why Initializer Lists?
Example List
- Are the following constructors correct?
Class List public List( string profName )
p.name profName private
Professor p Class Professor public
Professor( string n ) name n
private string name
Class List public List( int courseNumber )
course courseNumber private
const int course
Class List public List( List
anotherSection ) another
anotherSection private List another
13Insert
Example List
insert( 3, newItem )
44
Shift 1
Shift 2
Shift 3
Array indexes
MAX_LIST 1
k1
1
3
0
2
?
?
18
10
5
?
.
.
k
size
MAX_LIST
k
1
3
4
2
Positions in our list spec.
bool Listinsert( int index, ListItemType
newItem ) if ( (index gt 1) (index lt size
1) (size lt MAX_LIST) ) for ( int pos
size pos gt index pos ) // shift from k to
index to the right. itemstranslate(pos1)
itemstranslate(pos) itemstranslate(index
) newItem // insert the item
size // increment items else
return false
14Remove
Example List
remove( 3 )
Shift 1
Shift 2
Shift 3
Array indexes
MAX_LIST 1
k1
1
3
0
2
12
3
44
19
?
?
18
10
5
?
.
.
k
size
MAX_LIST
k
1
3
4
2
Positions in our list spec.
bool Listremove( int index ) if ( (index gt
1) (index lt size) ) for ( int pos
index 1 pos lt size pos ) // shift from
index1 to k to the left.
itemstranslate(pos1) itemstranslate(pos)
size // decrement items return
true else return false
15Main program
Example List
- The main program to test your class is called a
driver program. - The driver program should test all your class
methods. - Compilation g list.cpp listDriver.cpp
include List.h int main( ) List aList
ListItemType dataItem bool success
success aList.insert(1, 20)
aList.retrieve(1, dataItem)
16Class Rational Header File rat.hfrom Deitel
Deitel
Example Rational
ifndef RAT_H // To prevent multiple definitions
of the same header define RAT_H // If not fed
into a compiler, mark this header as
defined. include ltiostreamgt // For outdate
compilers, use include ltiostream.hgt using
namespace std class Rational // A class name
should start from a capital letter. public
Rational ( int 0, int 1 ) // Default
constructor. Rational add( const Rational a
) // Add a to this and return the result.
Rational subtract( const Rational s ) //
Subtract s from this and return the result.
Rational multiply( const Rational m ) //
Multiply this by m and return the result.
Rational divide( const Rational d ) // Divide
this by d and return the result. void
printRational( ) const // Print numerator /
denominator private int numerator int
denominator void reduce( ) // A utility
function endif
17Class Rational Implementation File rat.cpp
Example Rational
include rat.h // You should insert blank
lines for better readability. RationalRational(
int n, int d ) numerator d lt 0 ? n
n // sign/- is added to the numerator
denominator d lt 0 ? d d reduce( ) //
3/6 ? 1/2, 6/8 ? 3/4 Rational Rationaladd(
const Rational a ) // n/d N/D (n D d
N) / (d D) Rational t t.numerator
numerator a.denominator denominator
a.numerator t.denominator denominator
a.denominator t.reduce( ) return
t Rational Rationalsubtract( const Rational
s ) // n/d N/D (n D d N) / ( d D)
Rational t t.numerator numerator
s.denominator denominator s.numerator
t.denominator denominator s.denominator
t.reduce( ) return t
18Class Rational Implementation File Cont'd
Example Rational
Rational Rationalmultiply( const Rational m )
// n/d N/D (n N) / (d D) Rational t
t.numerator numerator m.numerator
t.denominator denominator m.denominator
t.reduce( ) return t Rational
Rationaldivide( const Rational v ) // n/d /
N/D n/d D/N (n D) / (d N) Rational
t t.numerator numerator v.denominator
t.denominator denominator v.numerator
t.reduce( ) return t void
RationalprintRational( ) const if (
denominator 0) cout ltlt DIVIDE BY ZERO
ERROR!!! ltlt endl else if (numerator
0) // dont print out 0 / 5 cout ltlt 0
else cout ltlt numerator ltlt / ltlt
denominator
19Rational Class Implementation File Contd
Example Rational
void Rationalreduce( ) int n numerator lt
0 ? numerator numerator // get a positive
numerator. int d denominator //
denominator is already positive. int largest
n gt d ? n d // max(n, d) int gcd
0 // great common divisor for ( int loop
largest loop gt2 loop-- ) // check if
numerator and denominator if ( numerator
loop 0 denominator loop 0 ) // are
divisible with loop max(n,d)2 gcd
loop // if so, that loop is gcd! break
if (gcd ! 0) // If gcd has been
found, divide them numerator / gcd // by
gcd. denominator / gcd
20Class Rational Main Program ratDriver.cpp
Example Rational
- Compilation g rat.cpp ratDriver.cpp
include ltiostream.hgt include rat.h void
main( ) Rational x(-2, 6), y(-14, -16), z
x.printRational( ) cout ltlt
y.printRational( ) z x.add(y) cout ltlt
ltlt z.printRational( ) ltlt endl // Repeat the
same test for all methods.
Question Why cant we code like that? z x y
21Operator Overloading rat2.cpp
Example Rational
ifndef RAT2_H define RAT2_H include
ltiostreamgt // for outdated compilers, include
ltiostream.hgt using namespace std class Rational
// class spec including assumptions should be
provided here friend ostream operatorltlt
(ostream output, constRational r) // those
two functions are stand-friend istream
operatorgtgt ( istream input, Rational r ) //
along functions. public Rational( int 0, int
1 ) // constructor Rational operator(const
Rational ) const // arithmetic operatorsthis
object parameter Rational operator(const
Rational ) const // this object parameter
Rational operator(const Rational ) const //
this object parameter Rational
operator/(const Rational ) const // this
object / parameter bool operatorgt(const
Rational ) const // boolean comparison
operators this object gt parameter ? bool
operatorlt(const Rational ) const // this
object lt parameter ? bool operatorgt(const
Rational ) const // this object gt parameter
? bool operator(const Rational )
const // this object parameter ? bool
operator!(const Rational ) const // this
object ! parameter ? Rational
operator(const Rational ) // assignment
operators this object parameter // You
should also define operator, operator, and
operator / private // the same as
rat.h endif
22 Implementation
Example Rational
//-----------------------------------------------
-------------------------------------------- //
overloaded this object parameter Rational
Rationaloperator( const Rational a ) const
// operations are the same as Rationaladd(
const Rational a ) Rational sum
sum.numerator numerator a.denominator
denominator a.numerator sum.denominator
denominator a.denominator sum.reduce( )
return sum
23 gt, , and gt Implementation
Example Rational
//-----------------------------------------------
gt -------------------------------------------- //
overloaded gt true if this object gt parameter,
otherwise false bool Rationaloperatorgt( const
Rational r ) const return float(numerator/den
ominator) gt float(r.numerator/r.denominator)
// use float, otherwise fractions are truncated.
//-----------------------------------------------
-------------------------------------------- //
overloaded true if this object parameter,
otherwise false bool Rationaloperator( const
Rational r ) const return numerator
r.numerator denominator r.denominator
//-----------------------------------------------
gt -------------------------------------------- //
overloaded gt true if this object gt parameter,
otherwise false bool Rationaloperatorgt( const
Rational r ) const // once you have defined
operatorsgt and , you can use them. return
this r this gt r // this is a pointer to
this object, and thus this is this object
itself.
24 Implementation
Example Rational
//-----------------------------------------------
-------------------------------------------- //
overloaded this object parameter Rational
Rationaloperator( const Rational r ) //
should not instantiate a new object. Wed rather
add parameter to this object itself. numerator
numerator r.denominator denominator
r.numerator denominator denominator
r.denominator reduce( ) return this //
why must we return the reference rather than the
value?
Example (ab)c - if a value is
returned 1. ab computed 2. A copy of a
generated 3. (this copy)c computed - if the
reference is returned 1. ab computed 2. The
reference returned 3. ac computed
25ltlt Implementation
Example Rational
//-----------------------------------------------
ltlt -------------------------------------------- //
prints DIVIDE BY ZERO ERROR!!! if denominator
is zero, // prints whole numbers without
denominator (as ints), otherwise uses
/ ostream operatorltlt( ostream output, const
Rational r ) // we are operating on an ostream
object, output rather than our Rational. //
ostream itself has an operatorltlt like
operatorltlt(cont int), operatorltlt(const
float). // It is unfeasible to define
ostreamoperatorltlt(const Rational) // Thus,
this operatorltlt must be defined as a stand-alone
function if (r.denominator 0) output
ltlt DIVIDE BY ZERO ERROR!!! ltlt endl // zero
division else if (r.numerator 0) output
ltlt 0 // zero rational else if
(r.denominatr 1) output ltlt
r.numerator // whole number else output
ltlt r.numerator ltlt / ltlt r.denominator return
output
26Class Rational Main Program ratDriver.cpp
Example Rational
include ltiostream.hgt include rat2.h void
main( ) Rational x(-2, 6), y(-14, -16), z
x.printRational( ) cout ltlt
y.printRational( ) z x y cout ltlt
ltlt z.printRational( ) ltlt endl // Repeat the
same test for all methods.