Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.

Similar presentations


Presentation on theme: "1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington."— Presentation transcript:

1

2 1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington

3 2 Chapter 11 Topics l Meaning of a Structured Data Type Declaring and Using a struct Data Type C++ union Data Type l Meaning of an Abstract Data Type Declaring and Using a class Data Type l Using Separate Specification and Implementation Files Invoking class Member Functions in Client Code C++ class Constructors

4 3 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long double

5 4 Structs

6 5 Structured Data Type A structured data type is a type in which each value is a collection of component items. l the entire collection has a single name l each component can be accessed individually

7 6 C++ Structured Type l often we have related information of various types that we’d like to store together for convenient access under the same identifier, for example...

8 7 thisAnimal 5000.id 2037581.name “giant panda”.genus “Ailuropoda”.species “melanoluka”.country “China”.age 18.weight 234.6.health Good

9 8 anotherAnimal 6000.id 5281003.name “llama”.genus “Lama”.species “peruana”.country “Peru”.age 7.weight 278.5.health Excellent

10 9 struct AnimalType enum HealthType { Poor, Fair, Good, Excellent } ; struct AnimalType// declares a struct data type {// does not allocate memory intid ; string name ; string genus ; string species ; struct members string country ; int age ; float weight ; } ; AnimalType thisAnimal ; // declare variables of AnimalType AnimalType anotherAnimal ;

11 10 struct type Declaration SYNTAX struct TypeName // does not allocate memory { MemberList } ; MemberList SYNTAX DataType MemberName ;.

12 11 struct type Declaration The struct declaration names a type and names the members of the struct. It does not allocate memory for any variables of that type! You still need to declare your struct variables.

13 12 More about struct type declarations If struct type declaration precedes all functions visible throughout the rest of the file (global scope). If it is placed within a function, only that function can use it (local scope). Common to place struct type decl. in (.h) header file #include that file.

14 13 More about struct type declarations Members of different struct types MAY have the same identifiers (names). struct Student struct Instructor {{ int id;int id; float gpa;float salary;} Non-struct variable MAY have the same identifier as a structure member. Student s; float gpa;

15 14 Accessing struct Members Dot ( period ) is the member selection operator. After struct type declaration: struct members can be used in your program only when they are preceded by –dot –a struct variable name EXAMPLES AnimalType thisAnimal, anotherAnimal; thisAnimal.weight anotherAnimal.country

16 15 Valid operations on a struct member depend only on its type thisAnimal.age = 18; thisAnimal.id = 2037581; cin >> thisAnimal.weight; getline ( cin, thisAnimal.species ); thisAnimal.name = “giant panda”; thisAnimal.genus[ 0 ] = toupper (thisAnimal.genus[ 0 ] ) ; thisAnimal.age++; struct AnimalType {long id ; string name ; string genus ; string species; string country int age ; float weight ; HealthType health ; } ; AnimalType thisAnimal;

17 16 Aggregate Operations

18 17 Aggregate Operation l is an operation on a data structure as a whole as opposed to an operation on an individual component of the data structure

19 18 Aggregate struct Operations l NOT ALLOWED n I/O n arithmetic n comparisons of entire struct variables l Operations ALLOWED on entire struct variable: n assignment to another struct variable of same type n pass to a function as argument (by value or by reference) n return as value of a function see time1.cpp time2.cpp

20 19 Examples of aggregate struct operations anotherAnimal = thisAnimal ; // assignment WriteOut(thisAnimal); // value parameter ChangeWeightAndAge(thisAnimal); // reference parameter thisAnimal = GetAnimalData( ); // return value of function NOW WE’LL WRITE THE 3 FUNCTIONS USED HERE...

21 20 void WriteOut( /* in */ AnimalType thisAnimal) // Prints out values of all members of thisAnimal // Precondition: all members of thisAnimal are assigned // Postcondition: all members have been written out { cout << “ID # “ << thisAnimal.id << thisAnimal.name << endl ; cout << thisAnimal.genus << thisAnimal.species << endl ; cout << thisAnimal.country << endl ; cout << thisAnimal.age << “ years “ << endl ; cout << thisAnimal.weight << “ lbs. “ << endl ; cout << “General health : “ ; WriteWord ( thisAnimal.health ) ; }

22 21 void ChangeAge ( /* inout */ AnimalType& thisAnimal ) // Adds 1 to age // Precondition: thisAnimal.age is assigned // Postcondition: thisAnimal.age == thisAnimal.age@entry + 1 { thisAnimal.age++ ; } Passing a struct Type by Reference

23 22 AnimalType GetAnimalData ( void ) // Obtains all information about an animal from keyboard // Postcondition: // Function value == AnimalType members entered at kbd { AnimalType thisAnimal ; char response ; do {// have user enter all members until they are correct. } while (response != ‘Y’ ) ; return thisAnimal ; }

24 23 Hierarchical Structures

25 24 Hierarchical Structures A struct member can be of another struct type. This is called nested or hierarchical structures. Hierarchical structures are useful when there is detailed info in each record. FOR EXAMPLE...

26 25 struct MachineRec Information about each machine in a shop contains: an idNumber, a written description, the purchase date, the cost, and a historical statistics (including failure rate, number of days down, and date of last service).

27 26 struct DateType {int month ; // Assume 1.. 12 int day ;// Assume 1.. 31 int year ; // Assume 1900.. 2050 }; struct StatisticsType {floatfailRate ; DateTypelastServiced ; // DateType is a struct type intdownDays ; } ; struct MachineRec {int idNumber ; string description ; StatisticsType history ; // StatisticsType is a struct type DateType purchaseDate ; float cost ; } ; MachineRec machine ;

28 27 struct type variable machine 7000.idNumber.description. history.purchaseDate.cost.month.day.year 5719 “BULLDOZ…” 3 21 1995 78000..failrate.lastServiced.downdays.02 6 25 1999 4.month.day.year machine.history.lastServiced.year has value 1999

29 28 Unions

30 29 Unions in C++ DEFINITION A union is a struct that holds only one of its members at a time during program execution. EXAMPLE union WeightType { long wtInOunces ; int wtInPounds; only one at a time float wtInTons; } ;

31 30 Using Unions union WeightType// declares a union type { long wtInOunces ; int wtInPounds; float wtInTons; } ; WeightType weight;// declares a union variable weight.wtInTons = 4.83 ; // Weight in tons is no longer needed. Reuse the memory space. weight.wtInPounds = 35;// see Unionex.cpp

32 31 Abstraction

33 32 Abstraction l Is the separation of the essential qualities of an object from the details of how it works or is composed Essential qualities >>> details l Focuses on what, not how l Like a table of contents l Is necessary for managing large, complex software projects

34 33 Control Abstraction l separates the logical properties of an action from its implementation logical properties >> implementation. Search (list, item, length, where, found);. l the function call depends on the function’s specification (description), not its implementation (algorithm)

35 34 Data Abstraction l separates the logical properties of a data type from its implementation LOGICAL PROPERTIESIMPLEMENTATION What are the possible values?How can this be done in C++? What operations will be needed?How can existing data types be used?

36 35 Data Type set of values (domain) allowable operations on those values FOR EXAMPLE, data type short has domain -32768... 32767 operations +, -, *, /, %, >>, <<

37 36 Abstract Data Type

38 37 Abstract Data Type (ADT) l a data type whose n properties (domain and operations) WHAT l are specified independently of any n particular implementation HOW FOR EXAMPLE...

39 38 ADT Specification Example (Properties) TYPE TimeType DOMAIN Each TimeType value is a time in hours, minutes, and seconds. OPERATIONS Set the time Print the time Increment by one second Compare 2 times for equality Determine if one time is “less than” another Notice NO Implementation given!!

40 39 Another ADT Specification TYPE ComplexNumberType DOMAIN Each value is an ordered pair of real numbers (a, b) representing a + bi. OPERATIONS Initialize the complex number Write the complex number Add Subtract Multiply Divide Determine the absolute value of a complex number Notice NO Implementation given!!

41 40 ADT Implementation means l choosing a specific data representation for the abstract data using data types that already exist (built-in or programmer-defined) l writing functions for each allowable operation

42 41 10 45 27 Several Possible Representations of TimeType 3 int variables 3 strings 3-element int array l actual choice of representation depends on time, space, and algorithms needed to implement operations 10 45 27 “10” “45” “27”

43 42 Some Possible Representations of ComplexNumberType struct with 2 float members 2-element float array -16.2 5.8.real.imag

44 43 Classes

45 44 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long double

46 Class l A structured type n (many components, access to each) n in a programming language n used to represent an ADT l Not a passive data structure n (only being acted upon) l An active data structure n containing data & operations n in a single unit

47 46 class TimeType Specification // SPECIFICATION FILE( timetype.h ) class TimeType// declares a class data type {// does not allocate memory public : // 5 public function members void Set ( int hours, int mins, int secs ) ; void Increment ( ) ; void Write ( ) const ; bool Equal ( TimeType otherTime ) const ; bool LessThan ( TimeType otherTime ) const ; private :// 3 private data members int hrs ; int mins ; int secs ; } ;

48 47 Use of C++ data Type class l facilitates re-use of C++ code for an ADT l software that uses the class is called a client l variables of the class type are called class objects or class instances l client code uses public member functions to handle its class objects

49 48 Client Code Using TimeType #include “timetype.h” // includes specification of the class using namespace std ; int main ( ) { TimeType currentTime ; // declares 2 objects of TimeType TimeType endTime ; bool done = false ; currentTime.Set ( 5, 30, 0 ) ; endTime.Set ( 18, 30, 0 ) ; while ( ! done ) {... currentTime.Increment ( ) ; if ( currentTime.Equal ( endTime ) ) done = true ; } ; }

50 49 class type Definition The class definition creates a data type and names the members of the class. It does not allocate memory for any variables of that type! Client code still needs to declare class variables.

51 50 C++ Data Type class represents an ADT l 2 kinds of class members: data members and function members l class members are private by default l data members are generally private l function members are generally declared public l private class members can be accessed only by the class member functions (and friend functions), not by client code.

52 51 class TimeType Specification // SPECIFICATION FILE( timetype.h ) class TimeType// declares a class data type {// does not allocate memory public : // 5 public function members void Set ( int hours, int mins, int secs ) ; void Increment ( ) ; void Write ( ) const ; bool Equal ( TimeType otherTime ) const ; bool LessThan ( TimeType otherTime ) const ; private :// 3 private data members int hrs ; int mins ; int secs ; } ;

53 52 Aggregate class Operations l built-in operations valid on class objects are: member selection using dot (. ) operator, assignment to another class variable using ( = ), pass to a function as argument (by value or by reference), return as value of a function l other operations can be defined as class member functions

54 53 2 separate files Generally Used for class Type // SPECIFICATION FILE ( timetype.h ) // Specifies the data and function members. class TimeType { public:... private:... } ; // IMPLEMENTATION FILE ( timetype.cpp ) // Implements the TimeType member functions....

55 54 Implementation File for TimeType // IMPLEMENTATION FILE ( timetype.cpp ) // Implements the TimeType member functions. #include “ timetype.h”// also must appear in client code #include... bool TimeType :: Equal ( /* in */ TimeType otherTime ) const // Postcondition: // Function value == true, if this time equals otherTime // == false, otherwise { return ( (hrs == otherTime.hrs) && (mins == otherTime.mins) && (secs == otherTime.secs) ) ; }... // see s:\cp2\cpp\time\TestTime

56 55 Familiar Class Instances and Function Members l the member selection operator (. ) selects either data members or function members 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 function members cin.get (someChar) ; cin.ignore (100, ‘\n’) ; l these statements declare myInfile as an instance of class ifstream and invoke function member open ifstream myInfile ; myInfile.open ( “A:\\mydata.dat” ) ;

57 56 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

58 57 Information Hiding ""... the purpose of hiding is to make inaccessible certain details that should not affect other parts of a system." -- [Ross et al, 1975] "... [I]nformation hiding: a module is characterized by the information it hides from other modules, which are called its clients. The hidden information remains a secret to the client modules." -- [Ghezzi et al, 1991] "[Information hiding is] the principle that users of a software component (such as a class) need to know only the essential details of how to initialize and access the component, and do not need to know the details of the implementation." -- [Budd, 1991] "The technique of encapsulating software design decisions in modules in such a way that the module's interfaces reveal little as possible about the module's inner workings; thus each module is a 'black box' to the other modules in -- [IEEE, 1983] "The process of hiding all the details of an object that do not contribute to its essential characteristics; typically, the structure of an object is hidden, as well as the implementation of its methods. The terms information hiding and encapsulation are usually interchangeable." -- [Booch, 1991]

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

60 59 TimeType Class Instance Diagrams Private data: hrs mins secs Set Increment Write LessThan Equal Private data: hrs mins secs Set Increment Write LessThan Equal 17 58 2 18 30 0 currentTime endTime

61 60 Use of const with Member Functions l when a member function does not modify private data members use const in both n function prototype (specification file) n heading of function implementation (implementation file)

62 61 class TimeType Specification // SPECIFICATION FILE( timetype.h ) class TimeType// declares a class data type {// does not allocate memory public : // 5 public function members void Set ( int hours, int mins, int secs ) ; void Increment ( ) ; void Write ( ) const ; bool Equal ( TimeType otherTime ) const ; bool LessThan ( TimeType otherTime ) const ; private :// 3 private data members int hrs ; int mins ; int secs ; } ;

63 62 Example Using const with a Member Function void TimeType :: Write ( ) const // Postcondition: Time has been output in form HH:MM:SS { if ( hrs < 10 ) cout << ‘0’ ; cout << hrs << ‘:’ ; if ( mins < 10 ) cout << ‘0’ ; cout << mins << ‘:’ ; if ( secs < 10 ) cout << ‘0’ ; cout << secs ; }

64 63 Separate Compilation and Linking of Files timetype.h client.cpptimetype.cpp client.obj client.exetimetype.obj Compiler Linker #include “timetype.h” implementation file specification file main program

65 Projects l Many program files (nodes) n compiled n linked l as one executable (.exe) l Project files have.dsw extensions l The project name will be the executable name

66 Creating a MS VC++ Project l File -> New l Click on Projects Tab l Select Target Type: Win 32 Console Application l Enter Project Name (becomes name of workspace folder) l Modify the workspace folder’s path to r:\.. l Select empty project l Click OK (new folder will be created on r:) l Debug Subfolder created for.obj and.exe

67 Adding Source Code to a MSVC++ Project To add new source code file to currently active project: l Select File -> New l Click on Files tab l Select C++ Source File as the file type l Enter File name l Modify, if necessary, the file’s folder path l Click OK

68 Adding Existing Files to a MSVC++ Project To add new source code file(s) to currently active project: l Select File View in Workspace Pane (LHS) l Right Click Source Files Folder l Select “Add files to Folder” l Browse and select files l Click OK

69 68 #define Directive

70 69 l often several program files use the same header file containing typedef statements, constants, or class type declarations--but, it is a compile-time error to define the same identifier twice l this preprocessor directive syntax is used to avoid the compilation error that would otherwise occur from multiple uses of #include for the same header file #ifndef Preprocessor_Identifier #define Preprocessor_Identifier. #endif Avoiding Multiple Inclusion of Header Files

71 70 Example Using Preprocessor Directive #ifndef // timetype.h FOR COMPILATION THE CLASS DECLARATION IN // SPECIFICATION FILE FILE timetype.h WILL BE INCLUDED ONLY ONCE #ifndef TIME_H #define TIME_H // timetype.cpp // client.cpp // IMPLEMENTATION FILE // Appointment program class TimeType { #include “timetype.h” #include “timetype.h” public:...... int main ( void ) { private:...... } } ; #endif

72 71 Constructors

73 72 Class Constructors l a class constructor is a member function whose purpose is to INITIALIZE the private data members of a class object l the name of a constructor is always the name of the class, and there is no return type for the constructor

74 73 Class Constructors l a class may have several constructors with different parameter lists. A constructor with no parameters is the default constructor l a constructor is implicitly invoked when a class object is declared--if there are parameters, their values are listed in parentheses in the declaration

75 74 Specification of TimeType Class Constructors class TimeType// timetype.h { public : // 7 function members TimeType ( int initHrs, int initMins, int initSecs ) ; // constructor TimeType ( ) ; // default constructor void Set ( int hours, int minutes, int seconds ) ; void Increment ( ) ; void Write ( ) const ; bool Equal ( TimeType otherTime ) const ; bool LessThan ( TimeType otherTime ) const ; private :// 3 data members int hrs ; int mins ; int secs ; } ;

76 75 Implementation of TimeType Default Constructor TimeType :: TimeType ( ) // Default Constructor // Postcondition: // hrs == 0 && mins == 0 && secs == 0 { hrs = 0 ; mins = 0 ; secs = 0 ; }

77 76 Implementation of Another TimeType Class Constructor TimeType :: TimeType ( /* in */ int initHrs, /* in */ int initMins, /* in */ int initSecs ) // Constructor // Precondition: 0 <= initHrs <= 23 && 0 <= initMins <= 59 // 0 <= initSecs <= 59 // Postcondition: //hrs == initHrs && mins == initMins && secs == initSecs { hrs = initHrs ; mins = initMins ; secs = initSecs ; }

78 77 Automatic invocation of constructors occurs TimeType departureTime ; // default constructor invoked TimeType movieTime (19, 30, 0 ) ; // parameterized constructor departureTime movieTime Private data: hrs mins secs Set Increment Write LessThan Equal 000000 Private data: hrs mins secs Set Increment Write LessThan Equal 19 30 0

79 78 Why Objects? Why Objects Anyway? l Object-oriented programming doesn't fundamentally add much (it doesn't lead to much shorter programs) l But, it is a style more appropriate to human psychology. l Thesis: Humans as part of their basic function are highly adept at recognizing and interacting with everyday objects. Everyday objects: Things we encounter everyday Properties: l active: not fully controlled by us, with internal evolving state. l communicative: we can "send messages". l encapsulated: some of the properties are not visible (though we can learn some of it by sending messages) l nested: complex objects have many object components (which in turn have object components etc) l uniquely named (more or less) l Objects in OOP (Object-Oriented Programming) also have all of these features. Conclusion: It is thus good to have programs create entities like these objects we are familiar with.

80 79 l See TimeTestwConstructor.dsw

81 80 Microsoft Visual C++ Project Files (Keepers).dsp Project file.dsw Workspace file.exe Executable program

82 81 Microsoft Visual C++ Temporary Files l Many are large and can be removed!.ilk Incremental link file.pch Precompiled header.pdb Precompiled debugging info.idb Incremental debug info.ncb Supports viewing classes.opt Workspace configuration.plg Build log file.obj Machine code translations

83 82


Download ppt "1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington."

Similar presentations


Ads by Google