1 / 26

CSS342: Objects and Classes

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

eavan
Download Presentation

CSS342: Objects and Classes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSS342: Objects and Classes Professor: Munehiro Fukuda 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 CSS342: Objects and Classes

  3. Class Implementation of method S 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. Program that uses method S Function call with arguments Return a value CSS342: Objects and Classes

  4. Class add remove query 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 CSS342: Objects and Classes

  5. Class Arnold Berger M 0201 Sorting depends on an implementation. Display a student entry Frank Cioch M 0202 Bill Erdly M 0203 Munehiro Fukuda M 0204 Add a new student entry Chuck Jackels M 0205 Baili Liu F 0206 Delete a student entry Janet McDaniel F 0207 Dina Meske F 0208 Clark Olson M 0209 Check # students Darian Smolar F 0210 List Class Specification CSS342: Objects and Classes

  6. Class 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. CSS342: Objects and Classes

  7. Class Arnold Berger M 0201 Frank Cioch M 0202 Bill Erdly M 0203 Munehiro Fukuda M 0204 Chuck Jackels M 0205 Baili Liu F 0206 Janet McDaniel F 0207 Dina Meske F 0208 Clark Olson M 0209 Darian Smolar F 0210 C++ Class public member functions/methods data members Sorting depends on an implementation. create( )/constructor destroy( )/destructor insert( ) remove( ) retrieve( ) getLength( ) isEmpty( ) Utility_func1( ) Utility_func2( ) private CSS342: Objects and Classes

  8. Class 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 CSS342: Objects and Classes

  9. Example: List 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 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. Example: List Array indexes 12 3 19 100 0 1 3 k–1 MAX_LIST – 1 2 k …. 5 10 18 ? ? …. ? size 1 3 4 k MAX_LIST 2 items Positions in our list spec. An Array Implementation of List Classlist.cpp CSS342: Objects and Classes

  11. 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 items.resize( MAX_LIST ); } 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. Example: List 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; } CSS342: Objects and Classes

  13. Example: List 12 3 19 100 Insert insert( 3, newItem ) 44 Shift 3 Shift 2 Shift 1 Array indexes 0 1 3 k–1 MAX_LIST – 1 2 k …. 5 10 18 ? ? …. ? size 1 3 4 k MAX_LIST 2 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. Example: List Remove remove( 3 ) Shift 1 Shift 2 Shift 3 Array indexes 0 1 3 k–1 MAX_LIST – 1 2 k 12 3 44 19 …. 5 10 18 ? ? …. ? size 1 3 4 k MAX_LIST 2 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. Example: List Main program • 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. Example: Rational 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 / denominator private: int numerator; int denominator; void reduce( ); // A utility function }; #endif CSS342: Objects and Classes

  17. 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) Rational t; t.numerator = numerator * s.denominator – denominator * s.numerator; t.denominator = denominator * s.denominator; t.reduce( ); return t; } Class Rational Implementation File: rat.cpp CSS342: Objects and Classes

  18. 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) 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; } CSS342: Objects and Classes

  19. Example: Rational 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; } } CSS342: Objects and Classes

  20. Example: Rational Class Rational Main Program: ratDriver.cpp • 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. 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 Operator Overloading: rat2.cpp CSS342: Objects and Classes

  22. Example: Rational + 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; } CSS342: Objects and Classes

  23. Example: Rational >, ==, and >= Implementation //----------------------------------------------- > -------------------------------------------- // 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. Example: Rational += Implementation //----------------------------------------------- += -------------------------------------------- // 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. Example: Rational << 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; } CSS342: Objects and Classes

  26. Example: Rational 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. } CSS342: Objects and Classes

More Related