Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 C++ Plus Data Structures Nell Dale Chapter 2 Data Design and Implementation Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.

Similar presentations


Presentation on theme: "1 C++ Plus Data Structures Nell Dale Chapter 2 Data Design and Implementation Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus."— Presentation transcript:

1 1 C++ Plus Data Structures Nell Dale Chapter 2 Data Design and Implementation Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus

2 2 Data Abstraction l Separation of a data type’s logical properties from its implementation. LOGICAL PROPERTIESIMPLEMENTATION What are the possible values? How can this be done in C++? What operations will be needed? How can data types be used?

3 3 APPLICATION 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 REPRESENTATION Data Encapsulation l is the separation of the representation of data from the applications that use the data at a logical level; a programming language feature that enforces information hiding. int y; y = 25;

4 4 Encapsulated C++ Data Type int Value range: INT_MIN.. INT_MAX Operations: + prefix - prefix + infix - infix * infix / infix % infix Relational Operators infix TYPE int (inside) Representation of int as 16 bits two’s complement + Implementation of Operations

5 5 Abstract Data Type (ADT) l A data type whose properties (domain and operations) are specified independently of any particular implementation.

6 6 l Application (or user) level: modeling real-life data in a specific context. l Logical (or ADT) level: abstract view of the domain and operations. WHAT l Implementation level: specific representation of the structure to hold the data items, and the coding for operations. HOW Data from 3 different levels

7 7 Viewing a library from 3 different levels l Application (or user) level: Library of Congress, or Baltimore County Public Library. l Logical (or ADT) level: domain is a collection of books; operations include: check book out, check book in, pay fine, reserve a book. l Implementation level: representation of the structure to hold the “books”, and the coding for operations.

8 8 Composite Data Type A composite data type is a type which l stores a collection of individual data components under one variable name, l and allows the individual data components to be accessed.

9 4 Basic Kinds of ADT Operations l Constructor -- creates a new instance (object) of an ADT. l Transformer -- changes the state of one or more of the data values of an instance. l Observer -- allows us to observe the state of one or more of the data values without changing them. l Iterator -- allows us to process all the components in a data structure sequentially. 9

10 Two Forms of Composite Data Types Components are not organized with respect to one another. The organization determines method used to access individual data components. UNSTRUCTURED STRUCTURED EXAMPLES: EXAMPLES: arrays classes and structs 10

11 11 C++ Built-In Data Types Composite array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double

12 12 Records A record is a composite data type made up of a finite collection of not necessarily homogeneous elements called members or fields. For example....year 1999.maker ‘h’ ‘o’ ‘n’ ‘d’ ‘a’ ‘\0’....price 18678.92 thisCar at Base Address 6000

13 13 struct CarType { int year ; char maker[10]; float price ; } ; CarType thisCar; //CarType variables CarType myCar;

14 14 Accessing struct members The member selection operator (period. ) is used between the variable name and the member identifier to access individual members of a record (struct or class) type variable. EXAMPLES myCar.year thisCar.maker[4]

15 15 Valid struct operations l Operations valid on an entire struct type variable: assignment to another struct variable of same type, pass as a parameter to a function (either by value or by reference), return as the value of a function.

16 Pass-by-value CALLING BLOCK FUNCTION CALLED sends a copy of the contents of the actual parameter SO, the actual parameter cannot be changed by the function. 16

17 Pass-by-reference sends the location (memory address) of the actual parameter can change value of actual parameter CALLING BLOCK FUNCTION CALLED 17

18 18 Using struct type Reference Parameter to change a member void AdjustForInflation(CarType& car, float perCent) // Increases price by the amount specified in perCent { car.price = car.price * perCent + car.price; } ; SAMPLE CALL AdjustForInflation(myCar, 0.03);

19 19 Using struct type Value Parameter to examine a member bool LateModel(CarType car, int date) // Returns true if the car’s model year is later than or // equal to date; returns false otherwise. { return ( car.year >= date ) ; } ; SAMPLE CALL if ( LateModel(myCar, 1995) ) cout << myCar.price << endl ;

20 20 C++ class data type l A class is an unstructured type that encapsulates a fixed number of data components (data members) with the functions (called member functions) that manipulate them. l The predefined operations on an instance of a class are whole assignment and component access.

21 21 class DateType Specification // SPECIFICATION FILE( datetype.h ) class DateType// declares a class data type { public : // 4 public member functions void Initialize ( int newMonth, int newDay, int newYear ) ; int YearIs( ) const ; // returns year int MonthIs( ) const ; // returns month int DayIs( ) const ; // returns day private :// 3 private data members int year ; int month ; int day ; } ; 21

22 22 Use of C++ data type class l Variables of a class type are called objects (or instances) of that particular class. l Software that declares and uses objects of the class is called a client. l Client code uses public member functions (called methods in OOP) to handle its class objects. l Sending a message means calling a public member function.

23 23 Client Code Using DateType #include “datetype.h” // includes specification of the class #include “bool.h” int main ( void ) { DateType startDate ; // declares 2 objects of DateType DateType endDate ; bool retired = false ; startDate.Initialize ( 6, 30, 1998 ) ; endDate.Initialize ( 10, 31, 2002 ) ; cout << startDate.MonthIs( ) << “/” << startDate.DayIs( ) << “/” << startDate.YearIs( ) << endl; while ( ! retired ) { finishSomeTask( ) ;... } 23

24 24 2 separate files generally used for class type // SPECIFICATION FILE ( datetype.h ) // Specifies the data and function members. class DateType { public:... private:... } ; // IMPLEMENTATION FILE ( datetype.cpp ) // Implements the DateType member functions....

25 25 DateType Class Instance Diagrams Initialize YearIs MonthIs DayIs startDate endDate Private data: year month day 2002 10 31 Initialize YearIs MonthIs DayIs 1998 6 30 Private data: year month day

26 26 Implementation of DateType member functions // IMPLEMENTATION FILE (datetype.cpp) #include “datetype.h” // also must appear in client code void DateType :: Initialize ( int newMonth, int newDay, int newYear ) // Post: year is set to newYear. // month is set to newMonth. // day is set to newDay. { year = newYear ; month = newMonth ; day = newDay ; } 26

27 int DateType :: MonthIs ( ) const // Accessor function for data member month { return month ; } int DateType :: YearIs ( ) const // Accessor function for data member year { return year ; } int DateType :: DayIs ( ) const // Accessor function for data member day { return day ; } 27

28 28 Familiar Class Instances and Member Functions l The member selection operator (. ) selects either data members or member functions. l Header files iostream and fstream declare the istream, ostream,and ifstream, ofstream I/O classes. l Both cin and cout are class objects and get and ignore are member functions. cin.get (someChar) ; cin.ignore (100, ‘\n’) ; l These statements declare myInfile as an instance of class ifstream and invoke member function open. ifstream myInfile ; myInfile.open ( “A:\\mydata.dat” ) ;

29 29 Scope Resolution Operator ( :: ) l C++ programs typically use several class types. l Different classes can have member functions with the same identifer, like Write( ). l Member selection operator is used to determine the class whose member function Write( ) is invoked. currentDate.Write( ) ;// class DateType numberZ.Write( ) ;// class ComplexNumberType l In the implementation file, the scope resolution operator is used in the heading before the member function’s name to specify its class. void DateType :: Write ( ) const {... }

30 30 Information Hiding Class implementation details are hidden from the client’s view. This is called information hiding. Public functions of a class provide the interface between the client code and the class objects. client code specificationimplementation abstraction barrier

31 // SPECIFICATION FILE( strtype.h ) #include const int MAX_CHARS = 200 ; enum RelationType { LESS, EQUAL, GREATER } ; enum InType { ALPHA_NUM, ALPHA, NON_WHITE, NOT_NEW } ; class StrType// declares class data type { public : // 7 public member functions void MakeEmpty ( ) ; void GetString ( bool skip, InType charsAllowed ) ; void GetStringFile ( bool skip, InType charsAllowed, ifstream& inFile ) ; void PrintToScreen ( bool newLine ) const ; void PrintToFile ( bool newLine, ofstream& outFile) const ; int LengthIs( ) const ; void CopyString( StrType& newString ) const ; private :// 1 private data member char letters [MAX_CHARS + 1 ] ; } ; 31

32 32 StrType Class Interface Diagram StrType class Private data: letters GetString GetStringFile CopyString LengthIs PrintToFile MakeEmpty PrintToScreen ‘c’ ’a’ ’t’ ’ \0 ’...

33 // IMPLEMENTATION FILE (strtype.cpp) #include “strtype.h” // also appears in client code #include “string.h” void StrType :: MakeEmpty ( ) // Post: letters is empty string. { letters[0] = ‘\0’ ; }... int StrType :: LengthIs ( ) const // Returns length of letters string. { return strlen ( letters ) ; } 33

34 34 Handling Exceptions l In a program, we may encounter a run time error l If we abort the program, all the work done so far may be lost l The program should somehow save the work, warn the user and exit gracefully

35 35 Writing Exception Handling Code l Let us use try~catch and throw statements l If an exception occurs, we alert the system with “throw” statement l Then the program enters the exception handling code within the catch clause

36 36 An Example l #include l using namespace std; l void main() l { l double price,sum; l sum = 0.0; l try l { do { n cout<<"Enter a price (ctrl-D and ENTER to stop)"; n cin>>price; n if (price < 0) throw string("bad number "); n If (cin) sum = sum + price; n } while (cin); n }

37 37 Sample Code l catch (string message) l { l cout<< message << "found in the input" <<endl; l exit(0); l } l cout<<"the sum of prices entered is"<<sum<<endl; l }


Download ppt "1 C++ Plus Data Structures Nell Dale Chapter 2 Data Design and Implementation Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus."

Similar presentations


Ads by Google