css342: objects and classes

26
CSS342: Objects and Classes 1 CSS342: Objects and Classes Professor: Munehiro Fukuda

Upload: eavan

Post on 04-Jan-2016

44 views

Category:

Documents


2 download

DESCRIPTION

CSS342: Objects and Classes. Professor: Munehiro Fukuda. Today’s 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 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CSS342: Objects and Classes

CSS342: Objects and Classes 1

CSS342: Objects and Classes

Professor: Munehiro Fukuda

Page 2: CSS342: Objects and Classes

CSS342: Objects and Classes 2

Today’s 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

Page 3: CSS342: Objects and Classes

CSS342: Objects and Classes 3

Encapsulation and Information Hiding

• 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.

Implementationof method S

Programthat uses method S

Function call with arguments

Return a value

Class

Page 4: CSS342: Objects and Classes

CSS342: Objects and Classes 4

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

add

remove

query

Behave as a new data type

Programthat uses

a class

Examples:- student lists- rational numbers- complex numbers- currency (cents/dollars)- length measurement (inches/feet)- weight measurement (oz/lbs)

Class

Page 5: CSS342: Objects and Classes

CSS342: Objects and Classes 5

List Class Specification

Add a new student entry

Delete a student entry

Display a student entry

Check # students

BergerCioch

Olson

Erdly

Meske

LiuMcDaniel

FukudaJackels

Smolar

ArnoldFrank

Clark

Bill

Dina

BailiJanet

MunehiroChuck

Darian

MM

M

M

F

FF

MM

F

02010202

0209

0203

0208

02060207

02040205

0210

Sorting depends on an implementation.

Class

Page 6: CSS342: Objects and Classes

CSS342: Objects and Classes 6

List Operations Spec.• 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.

Class

Page 7: CSS342: Objects and Classes

CSS342: Objects and Classes 7

C++ Class

destroy( )/destructor

insert( )

create( )/constructor

retrieve( )

BergerCioch

Olson

Erdly

Meske

LiuMcDaniel

FukudaJackels

Smolar

ArnoldFrank

Clark

Bill

Dina

BailiJanet

MunehiroChuck

Darian

MM

M

M

F

FF

MM

F

02010202

0209

0203

0208

02060207

02040205

0210

Sorting depends on an implementation.

data membersmember functions/methodspublic

private

remove( )

getLength( )

isEmpty( )

Utility_func1( )

Utility_func2( )

Class

Page 8: CSS342: Objects and Classes

CSS342: Objects and Classes 8

C++ Header and Implementation File

• 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

• ClassName::functionName• Function spec (pre/postconditions) in comments• The body of function with appropriate comments

Class

Page 9: CSS342: Objects and Classes

CSS342: Objects and Classes 9

List Header: list.h#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 behaviorconst 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:

vector<ListItemtype> items; // array implementation int size; // # of items int translate( int index ) const; // tranlate the index into the corresponding position}#endif

Example: List

Page 10: CSS342: Objects and Classes

CSS342: Objects and Classes 10

An Array Implementation of List Classlist.cpp

12 3 19 100 ??18105 ?…. ….ksize

Positions in our list spec.

items

Array indexes

MAX_LIST – 1

MAX_LIST

k–1

k1 2 3 4

1 2 30

Example: List

Page 11: CSS342: Objects and Classes

CSS342: Objects and Classes 11

Constructor

• A method that describes how an instance of the class is created:

Example 1:List( ) { items.resize( MAX_LIST );}List( int initSize ) { if (initSize > 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

Example: List

Page 12: CSS342: Objects and Classes

CSS342: Objects and Classes 12

Why Initializer Lists?

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; }

Example: List

Page 13: CSS342: Objects and Classes

CSS342: Objects and Classes 13

Insert

12 3 19 100 ??18105 ?…. ….ksize

Positions in our list spec.

Array indexes

MAX_LIST – 1

MAX_LIST

k–1

k1 2 3 4

1 2 30

44

insert( 3, newItem )

Shift1

bool List::insert( int index, ListItemType newItem ) { if ( (index >= 1) && (index <= size + 1) && (size < MAX_LIST) ) {

for ( int pos = size; pos >= index; ––pos ) // shift from k to index to the right. items[translate(pos+1)] = items[translate(pos)];

items[translate(index)] = newItem; // insert the item ++size; // increment # items } else return false;}

Shift2

Shift3

Example: List

Page 14: CSS342: Objects and Classes

CSS342: Objects and Classes 14

Remove

12 3 44 19 ??18105 ?…. ….ksize

Array indexes

MAX_LIST – 1

MAX_LIST

k–1

k1 2 3 4

1 2 30

remove( 3 )

Shift1

bool List::remove( int index ) { if ( (index >= 1) && (index <= size) ) {

for ( int pos = index + 1; pos <= size; ++pos ) // shift from index+1 to k to the left. items[translate(pos–1)] = items[translate(pos)];

––size; // decrement # items return true; } else return false;}

Shift2

Shift3

Positions in our list spec.

Example: List

Page 15: CSS342: Objects and Classes

CSS342: Objects and Classes 15

Main program

#include “List.h”int main( ){ List aList; ListItemType dataItem; bool success;

success = aList.insert(1, 20); aList.retrieve(1, dataItem); …}

• 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

Example: List

Page 16: CSS342: Objects and Classes

CSS342: Objects and Classes 16

Class Rational Header File: rat.hfrom Deitel & Deitel

#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 <iostream> // For outdate compilers, use #include <iostream.h>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 / denominatorprivate: int numerator; int denominator; void reduce( ); // A utility function};#endif

Example: Rational

Page 17: CSS342: Objects and Classes

CSS342: Objects and Classes 17

Class Rational Implementation File: rat.cpp#include “rat.h” // You should insert blank lines for better readability.

Rational::Rational( int n, int d ) { numerator = d < 0 ? –n : n; // sign+/- is added to the numerator denominator = d < 0 ? –d; d; reduce( ); // 3/6 → 1/2, 6/8 → 3/4}Rational Rational::add( 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 Rational::subtract( 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;}

Example: Rational

Page 18: CSS342: Objects and Classes

CSS342: Objects and Classes 18

Class Rational Implementation File Cont'dRational Rational::multiply( 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 Rational::divide( 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 Rational::printRational( ) const { if ( denominator == 0) cout << “DIVIDE BY ZERO ERROR!!!” << endl; else if (numerator == 0) // don’t print out … 0 / 5 cout << 0; else cout << numerator << “ / ” << denominator;}

Example: Rational

Page 19: CSS342: Objects and Classes

CSS342: Objects and Classes 19

Rational Class Implementation File Cont’d

void Rational::reduce( ) { int n = numerator < 0 ? –numerator : numerator; // get a positive numerator. int d = denominator; // denominator is already positive. int largest = n > d ? n : d; // max(n, d) int gcd = 0; // great common divisor

for ( int loop = largest; loop >=2; 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; }}

Example: Rational

Page 20: CSS342: Objects and Classes

CSS342: Objects and Classes 20

Class Rational Main Program: ratDriver.cpp

#include <iostream.h>#include “rat.h”

void main( ) { Rational x(-2, 6), y(-14, -16), z;

x.printRational( ); cout << “ + ”; y.printRational( ); z = x.add(y); cout << “ = ” << z.printRational( ) << endl;

// Repeat the same test for all methods.}

• Compilation: g++ rat.cpp ratDriver.cpp

Question:Why can’t we code like that?z = x + y;

Example: Rational

Page 21: CSS342: Objects and Classes

CSS342: Objects and Classes 21

Operator Overloading: rat2.cpp#ifndef RAT2_H#define RAT2_H#include <iostream> // for outdated compilers, #include <iostream.h>using namespace std;class Rational { // class spec including assumptions should be provided herefriend ostream& operator<< (ostream& output, constRational & r); // those two functions are stand-friend istream& operator>> ( istream& input, Rational & r ); // along functions.public: Rational( int = 0, int = 1 ); // constructor Rational operator+(const Rational &) const; // arithmetic operators:this 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 operator>(const Rational &) const; // boolean comparison operators: this object > parameter ? bool operator<(const Rational &) const; // this object < parameter ? bool operator>=(const Rational &) const; // this object >= 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

Example: Rational

Page 22: CSS342: Objects and Classes

CSS342: Objects and Classes 22

+ Implementation

//----------------------------------------------- + --------------------------------------------// overloaded +; this object + parameter

Rational Rational::operator+( const Rational& a ) const { // operations are the same as Rational::add( const Rational& a ) Rational sum;

sum.numerator = numerator * a.denominator + denominator * a.numerator; sum.denominator = denominator * a.denominator; sum.reduce( );

return sum;}

Example: Rational

Page 23: CSS342: Objects and Classes

CSS342: Objects and Classes 23

>, ==, and >= Implementation//----------------------------------------------- > --------------------------------------------// overloaded >; true if this object > parameter, otherwise falsebool Rational::operator>( const Rational& r ) const { return float(numerator/denominator) > float(r.numerator/r.denominator); // use float, otherwise fractions are truncated.}

//----------------------------------------------- == --------------------------------------------// overloaded ==; true if this object == parameter, otherwise falsebool Rational::operator==( const Rational& r ) const { return numerator == r.numerator && denominator == r.denominator;}

//----------------------------------------------- >= --------------------------------------------// overloaded >=; true if this object >= parameter, otherwise falsebool Rational::operator>=( const Rational& r ) const {// once you have defined operators> and ==, you can use them. return *this == r || *this > r; // this is a pointer to this object, and thus *this is this object itself. }

Example: Rational

Page 24: CSS342: Objects and Classes

CSS342: Objects and Classes 24

+= Implementation

//----------------------------------------------- += --------------------------------------------// overloaded +=; this object += parameterRational& Rational::operator+=( const Rational& r ) { // should not instantiate a new object. We’d 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:(a+=b)+=c

- if a value is returned:1. a+=b computed; 2. A copy of a generated; 3. (this copy)+=c computed

- if the reference is returned:1. a+=b computed; 2. The reference returned; 3. a+=c computed

Example: Rational

Page 25: CSS342: Objects and Classes

CSS342: Objects and Classes 25

<< Implementation//----------------------------------------------- << --------------------------------------------// prints “DIVIDE BY ZERO ERROR!!!” if denominator is zero,// prints whole numbers without denominator (as ints), otherwise uses ‘/’

ostream& operator<<( ostream& output, const Rational& r ) {// we are operating on an ostream object, “output” rather than our Rational.// ostream itself has an operator<< like operator<<(cont int&), operator<<(const float&).// It is unfeasible to define ostream::operator<<(const Rational&)// Thus, this operator<< must be defined as a stand-alone function

if (r.denominator == 0) output << “DIVIDE BY ZERO ERROR!!!” << endl; // zero division else if (r.numerator == 0) output << 0; // zero rational else if (r.denominatr == 1) output << r.numerator; // whole number else output << r.numerator << “/” << r.denominator; return output;}

Example: Rational

Page 26: CSS342: Objects and Classes

CSS342: Objects and Classes 26

Class Rational Main Program: ratDriver.cpp

#include <iostream.h>#include “rat2.h”

void main( ) { Rational x(-2, 6), y(-14, -16), z;

x.printRational( ); cout << “ + ”; y.printRational( ); z = x + y; cout << “ = ” << z.printRational( ) << endl;

// Repeat the same test for all methods.}

Example: Rational