Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Object-Oriented Programming Using C++ CLASS 4 Honors.

Similar presentations


Presentation on theme: "1 Object-Oriented Programming Using C++ CLASS 4 Honors."— Presentation transcript:

1 1 Object-Oriented Programming Using C++ CLASS 4 Honors

2 2 14.8 Object Composition Object composition occurs when a class contains an instance of another class. Creates a “has a” relationship between classes.

3 3 A class can contain an object of another class class Dateclass Employee {public:{public: // methods//methodsprivate:// data }; char lastName[25]; char firstName[25]; Date birthdate; Date hiredate; }; Composition (example not in textbook)

4 4 Date class

5 5 // DATE1.H #ifndefDATE1_H #defineDATE1_H class Date{ public: Date(int = 1, int = 1, int = 1900); // default constructor void print ( ) const; ~Date( ); private: int month;// 1-12 int day;// 1-31 based on month int year;// any year int checkDay(int); }; #endif

6 6 Date::Date(int mn, int dy, int yr) { if (mn > 0 && mn <= 12) month = mn; else{ month = 1; cout << “Month 1” << mn << “ invalid.Set to month 1.” << endl; } year = yr;// could also check day = checkDay(dy);// validate the day cout << “Date object constructor for date ”; print( ); cout << endl; }

7 7 int Date::checkDay(int testDay) { static int daysPerMonth[13] = {0, 31, 28, 31, 30 31, 30, 31, 31, 30, 31, 30, 31}; if (testDay > 0 && testDay <= daysPerMonth[month]) return testDay; if (month == 2 && testDay == 29 && (year % 400 == 0 || (year % 4 == 0 && year % 100 !=0))) return testDay; cout<<“Day”<< testDay << “ invalid. Set to day 1.”<<endl; return 1; }

8 8 //Print Date object in form month/day/year void Date::print( ) const { cout << month << ‘/’ << day << ‘/’ << year; } Date::~Date( ) { cout << “Date object destructor for date ”; print( ); cout << endl; }

9 9 Employee class

10 10 // emply1.h #ifndef EMPLY1_H #define EMPLY1_H #include "date1.h“ class Employee { public: Employee( char *, char *, int, int, int, int, int, int ); void print() const; ~Employee(); private: char firstName[ 25 ]; char lastName[ 25 ]; const Date birthDate; const Date hireDate; }; #endif

11 11 // Member function definitions for Employee class. #include using namespace std; #include #include "emply1.h" #include "date1.h"

12 12 Employee::Employee( char *fname, char *lname, int bmonth, int bday, int byear, int hmonth, int hday, int hyear ) : birthDate( bmonth, bday, byear ), hireDate( hmonth, hday, hyear ) { // body of constructor

13 13 Employee::Employee( char *fname, char *lname, int bmonth, int bday, int byear, int hmonth, int hday, int hyear ) : birthDate( bmonth, bday, byear ), hireDate( hmonth, hday, hyear ) // constructor of date class called twice: // once for the birthDate object // once for the hireDate object { // body of constructor

14 14 int length = strlen( fname ); length = ( length < 25 ? length : 24 ); strncpy( firstName, fname, length ); firstName[ length ] = '\0'; length = strlen( lname ); length = ( length < 25 ? length : 24 ); strncpy( lastName, lname, length ); lastName[ length ] = '\0'; cout << "Employee object constructor: “ << firstName << ' ' << lastName << endl; }

15 15 void Employee::print() const { cout << lastName << ", " << firstName << "\nHired: "; hireDate.print(); cout << " Birth date: "; birthDate.print(); cout << endl; } Employee::~Employee() { cout << "Employee object destructor: " << lastName << ", " << firstName << endl; } P. 466

16 16 #include using namespace std; #include "emply1.h“ int main() {Employee e( "Bob", "Jones", 7, 24, 1949, 3, 12, 1988 ); e.print(); Date d( 14, 35, 1994 ); cout << endl; return 0; } For the Birthdate object For the Hiredate object Parameters to the Employee constructor

17 17 Specifying ADTs: The ADT List Except for the first and last items in a list, each item has a unique predecessor and a unique successor Head (or front) does not have a predecessor Tail (or end) does not have a successor

18 18 The ADT List Items are referenced by their position within the list Specifications of the ADT operations –Define an operation contract for the ADT list –Do not specify how to store the list or how to perform the operations ADT operations can be used in an application without the knowledge of how the operations will be implemented

19 19 The ADT List ADT List Operations –Create an empty list –Destroy a list –Determine whether a list is empty –Determine the number of items in a list –Insert an item at a given position in the list –Delete the item at a given position in the list –Look at (retrieve ) the item at a given position in the list

20 20 The ADT List Operation Contract for the ADT List createList() destroyList() isEmpty():boolean {query} getLength():integer {query} insert(in index:integer, in newItem:ListItemType, out success:boolean) remove(in index:integer, out success:boolean) retrieve(in index:integer, out dataItem:ListItemType, out success:boolean) {query}

21 21 The ADT List Pseudocode to create the list milk, eggs, butter aList.createList() aList.insert(1, milk, success) aList.insert(2, eggs, success) aList.insert(3, butter, success)

22 22 The ADT List milk, eggs, butter Insert bread after milk aList.insert(2, bread, success) milk, bread, eggs, butter Insert juice at end of list aList.insert(5, juice, success) milk, bread, eggs, butter, juice

23 23 The ADT List milk, bread, eggs, butter, juice Remove eggs aList.remove(3, success) milk, bread, butter, juice Insert apples at beginning of list aList.insert(1, apples, success) apples, milk, bread, butter, juice

24 24 The ADT List apples, milk, bread, butter, juice Pseudocode function that displays a list displayList(in aList:List) for (position = 1 to aList.getLength()) { aList.retrieve(position, dataItem, success) Display dataItem } // end for

25 25 The ADT List Figure 3-7 The wall between displayList and the implementation of the ADT list

26 26 The ADT Sorted List The ADT sorted list –Maintains items in sorted order –Inserts and deletes items by their values, not their positions

27 27 The ADT Sorted List Operation Contract for the ADT Sorted List sortedIsEmpty():boolean{query} sortedGetLength():integer{query} sortedInsert(in newItem:ListItemType, out success:boolean) sortedRemove(in index:integer, out success :boolean) sortedRetrieve(in index:integer, out dataItem:ListItemType, out success :boolean){query} locatePosition(in anItem:ListItemType, out isPresent:boolean):integer{query}

28 28 Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT –What data does a problem require? –What operations does a problem require?

29 29 Implementing ADTs Choosing the data structure to represent the ADT’s data is a part of implementation –Choice of a data structure depends on Details of the ADT’s operations Context in which the operations will be used

30 30 Implementing ADTs Implementation details should be hidden behind a wall of ADT operations –A program (client) should only be able to access the data structure by using the ADT operations

31 31 Implementing ADTs Figure 3-8 ADT operations provide access to a data structure

32 32 Implementing ADTs Figure 3-9 Violating the wall of ADT operations

33 33 An Array-Based ADT List Both an array and a list identify their items by number –Using an array to represent a list is a natural choice –Store a list’s items in an array items Distinguish between the list’s length and the array’s size –Keep track of the list’s length

34 34 An Array-Based ADT List Header file /** @file ListA.h */ const int MAX_LIST = maximum-size-of-list ; typedef desired-type-of-list-item ListItemType; class List { public:... private: ListItemType items[MAX_LIST]; int size; }; // end List

35 35 An Array-Based ADT List A list’s k th item is stored in items[k-1] Figure 3-11 An array-based implementation of the ADT list

36 36 An Array-Based ADT List To insert an item, make room in the array Figure 3-12 Shifting items for insertion at position 3

37 37 An Array-Based ADT List To delete an item, remove gap in array Figure 3-13 (a) Deletion causes a gap; (b) fill gap by shifting

38 38 Array of Objects Objects can be the elements of an array: Square lottaSquares[10]; Default constructor for object is used when array is defined Must use initializer list to invoke constructor that takes arguments: for example in class Square Square (int); in main driver: Square triSqu[3] = {5,7,11}; More complex initialization if constructor takes > 1 argument

39 39 Array of InventoryItem objects Assume InventoryItem class has 3 constructors: InventoryItem(); InventoryItem(string); InventoryItem(string,int); InventoryItem inventory[3] = {“Hammer”, “Wrench”, “Pliers”};

40 40 Array of InventoryItem objects // instantiation of objects with constructors containing // more than one argument requires different syntax InventoryItem inventory[3] = { “Hammer”, // first object InventoryItem(“Wrench”,17), // second object // default constructor for third object }

41 41 Using the array of objects InventoryItem inventory[3] = { InventoryItem(“Hammer”,12), InventoryItem(“wrench”, 17), InventoryItem(“pliers”,10) }; for (int I =0; I < 3; I++) { cout << inventory[I].getDescription(); cout << inventory[I].getUnits(); }

42 42 C++ Exceptions Throwing exceptions –A throw statement throws an exception throw ExceptionClass ( stringArgument ); –Methods that throw an exception have a throw clause void myMethod(int x) throw(MyException) { if (...) throw MyException(“MyException: …”);... } // end myMethod You can use an exception class in the C++ Standard Library or define your own

43 43 An ADT List Implementation Using Exceptions We define two exception classes #include using namespace std; class ListIndexOutOfRangeException : public out_of_range { public: ListIndexOutOfRangeException(const string & message = “”) : out_of_range(message.c_str()) {} }; // end ListException

44 44 An ADT List Implementation Using Exceptions #include using namespace std; class ListException : public logic_error { public: ListException(const string & message = “”) : logic_error(message.c_str()) {} }; // end ListException

45 45 An ADT List Implementation Using Exceptions /** @file ListAexcept.h */ #include “ListException.h” #include “ ListIndexOutOfRangeException.h”... class List { public:... void insert(int index, const ListItemType& newItem) throw(ListIndexOutOfRangeException, ListException);... } // end List

46 46 An ADT List Implementation Using Exceptions /** @file ListAexcept.cpp */ void List::insert(int index, const ListItemType& newItem) throw(ListIndexOutOfRangeException, ListException); { if (size > MAX_LIST) throw ListException(“ListException: ” + “List full on insert”);... } // end insert


Download ppt "1 Object-Oriented Programming Using C++ CLASS 4 Honors."

Similar presentations


Ads by Google