Download presentation
Presentation is loading. Please wait.
1
CSS342: Objects and Classes
Professor: Munehiro Fukuda CSS342: Objects and Classes
2
CSS342: Objects and Classes
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 CSS342: Objects and Classes
3
Encapsulation 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. Implementation of method S Program that uses method S Function call with arguments Return a value CSS342: Objects and Classes
4
Class 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 add remove query Examples: student lists rational numbers complex numbers currency (cents/dollars) length measurement (inches/feet) weight measurement (oz/lbs) Program that uses a class CSS342: Objects and Classes
5
List Class Specification
Add a new student entry Delete a student entry Display a student entry Check # students Berger Cioch Olson Erdly Meske Liu McDaniel Fukuda Jackels Smolar Arnold Frank Clark Bill Dina Baili Janet Munehiro Chuck Darian M F 0201 0202 0209 0203 0208 0206 0207 0204 0205 0210 Sorting depends on an implementation. CSS342: Objects and Classes
6
CSS342: Objects and Classes
List 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. CSS342: Objects and Classes
7
create( )/constructor destroy( )/destructor
C++ Class Class public member functions/methods data members Sorting depends on an implementation. create( )/constructor Berger Cioch Olson Erdly Meske Liu McDaniel Fukuda Jackels Smolar Arnold Frank Clark Bill Dina Baili Janet Munehiro Chuck Darian M F 0201 0202 0209 0203 0208 0206 0207 0204 0205 0210 destroy( )/destructor insert( ) remove( ) retrieve( ) getLength( ) isEmpty( ) Utility_func1( ) Utility_func2( ) private CSS342: Objects and Classes
8
C++ 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 ClassName::functionName Function spec (pre/postconditions) in comments The body of function with appropriate comments CSS342: Objects and Classes
9
CSS342: Objects and Classes
List 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: vector<ListItemtype> items; // array implementation int size; // # of items int translate( int index ) const; // tranlate the index into the corresponding position } #endif CSS342: Objects and Classes
10
An Array Implementation of List Class list.cpp
Example: List An Array Implementation of List Class list.cpp 12 3 19 100 ? 18 10 5 …. k size Positions in our list spec. items Array indexes MAX_LIST – 1 MAX_LIST k–1 1 2 4 CSS342: Objects and Classes
11
CSS342: Objects and Classes
Example: List 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 Example 2: MyClass( int initialValue = 0 ) : myData( initialValue) { } List list; List list(10); MyClass m; MyClass m(10); Initializer List CSS342: Objects and Classes
12
CSS342: Objects and Classes
Why Initializer Lists? Example: List Are the following constructors correct? Class List { public: List( string profName ) { p.name = profName; } private: Professor p; Class Professor { Professor( string n ) { name = n; 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; CSS342: Objects and Classes
13
Insert insert( 3, newItem ) 44 Array indexes 1 2 3 k–1 k 12 3 19 100
Example: List insert( 3, newItem ) 44 Shift 3 Shift 2 Shift 1 Array indexes 1 2 3 k–1 MAX_LIST – 1 k 12 3 19 100 …. 5 10 18 ? ? …. ? size 1 2 3 4 k MAX_LIST Positions in our list spec. 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; } CSS342: Objects and Classes
14
Remove remove( 3 ) Array indexes 1 2 3 k–1 k 12 3 44 19 …. 5 10 18 ? ?
Example: List remove( 3 ) Shift 1 Shift 2 Shift 3 Array indexes 1 2 3 k–1 MAX_LIST – 1 k 12 3 44 19 …. 5 10 18 ? ? …. ? size 1 2 3 4 k MAX_LIST Positions in our list spec. 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; } CSS342: Objects and Classes
15
CSS342: Objects and Classes
Main 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); … } CSS342: Objects and Classes
16
Class Rational Header File: rat.h from Deitel & Deitel
Example: Rational Class Rational Header File: rat.h from 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 / denominator private: int numerator; int denominator; void reduce( ); // A utility function }; #endif CSS342: Objects and Classes
17
Class Rational Implementation File: rat.cpp
Example: Rational #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) t.numerator = numerator * s.denominator – denominator * s.numerator; t.denominator = denominator * s.denominator; CSS342: Objects and Classes
18
Class Rational Implementation File Cont'd
Example: Rational Class Rational Implementation File Cont'd Rational 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) t.numerator = numerator * v.denominator; t.denominator = denominator * v.numerator; 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; CSS342: Objects and Classes
19
Rational Class Implementation File Cont’d
Example: Rational 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; CSS342: Objects and Classes
20
Class Rational Main Program: ratDriver.cpp
Example: Rational Compilation: g++ rat.cpp 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. } Question: Why can’t we code like that? z = x + y; CSS342: Objects and Classes
21
Operator Overloading: rat2.cpp
Example: Rational #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 here friend 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 CSS342: Objects and Classes
22
CSS342: Objects and Classes
+ Implementation Example: Rational // // 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; } CSS342: Objects and Classes
23
>, ==, and >= Implementation
Example: Rational // > // overloaded >; true if this object > parameter, otherwise false bool 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 false bool Rational::operator==( const Rational& r ) const { return numerator == r.numerator && denominator == r.denominator; } // >= // overloaded >=; true if this object >= parameter, otherwise false bool 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. } CSS342: Objects and Classes
24
CSS342: Objects and Classes
+= Implementation Example: Rational // = // overloaded +=; this object += parameter Rational& 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 CSS342: Objects and Classes
25
<< Implementation
Example: Rational // << // 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; } CSS342: Objects and Classes
26
Class Rational Main Program: ratDriver.cpp
Example: Rational #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. } CSS342: Objects and Classes
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.