Chapter 11 Structured Types Data Abstraction and Classes

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

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

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

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 4

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. . . 5

this. Animal 5000. id 2037581 . name “giant panda” . genus “Ailuropoda” . species “melanoluka” . country “China” . age 18 . weight 234. 6 . health Good 6

another. Animal 6000. id 5281003 . name “llama” . genus “Lama” . species “peruana” . country “Peru” . age 7 . weight 278. 5 . health Excellent 7

struct Animal. Type enum Health. Type { Poor, Fair, Good, Excellent } ; struct Animal. Type { long id ; string name ; string genus ; string species ; string country ; int age ; float weight ; Health. Type health ; }; Animal. Type // declares a struct data type // does not allocate memory struct members this. Animal ; // declare variables of Animal. Type another. Animal ; 8 8

struct type Declaration SYNTAX struct Type. Name { Member. List }; Member. List // does not allocate memory SYNTAX Data. Type Member. Name ; . . . 9

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. 10

More about struct type declarations If the struct type declaration precedes all functions it will be visible throughout the rest of the file. If it is placed within a function, only that function can use it. It is common to place struct type declarations with Type. Names in a (. h) header file and #include that file. It is possible for members of different struct types to have the same identifiers. Also a non-struct variable may have the same identifier as a structure member. 11

Accessing struct Members Dot ( period ) is the member selection operator. After the struct type declaration, the various members can be used in your program only when they are preceded by a struct variable name and a dot. EXAMPLES this. Animal. weight another. Animal. country 12

Valid operations on a struct member depend only on its type this. Animal. age = 18; this. Animal. id = 2037581; cin >> this. Animal. weight; getline ( cin, this. Animal. species ); this. Animal. name = “giant panda”; this. Animal. genus[ 0 ] = toupper (this. Animal. genus[ 0 ] ) ; this. Animal. age++; 13

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 14

Aggregate struct Operations l I/O, arithmetic, and comparisons of entire struct variables are NOT ALLOWED! l operations valid on an entire struct type variable: assignment to another struct variable of same type, pass to a function as argument (by value or by reference), return as value of a function 15

Examples of aggregate struct operations another. Animal = this. Animal ; // assignment Write. Out(this. Animal); // value parameter Change. Weight. And. Age(this. Animal); // reference parameter this. Animal = Get. Animal. Data( ); // return value of function NOW WE’LL WRITE THE 3 FUNCTIONS USED HERE. . . 16

void Write. Out( /* in */ Animal. Type this. Animal) // Prints out values of all members of this. Animal // Precondition: // Postcondition: all members of this. Animal are assigned all members have been written out { cout << “ID # “ << this. Animal. id << this. Animal. name << endl ; cout << this. Animal. genus << this. Animal. species << endl ; cout << this. Animal. country << endl ; cout << this. Animal. age << “ years “ << endl ; cout << this. Animal. weight << “ lbs. “ << endl ; cout << “General health : “ ; Write. Word ( this. Animal. health ) ; } 17 17

Passing a struct Type by Reference void Change. Age ( /* inout */ Animal. Type& this. Animal ) // Adds 1 to age // Precondition: // Postcondition: this. Animal. age is assigned this. Animal. age == this. Animal. age@entry + 1 { this. Animal. age++ ; } 18

Animal. Type Get. Animal. Data ( void ) // Obtains all information about an animal from keyboard // Postcondition: // Function value == Animal. Type members entered at kbd { Animal. Type this. Animal ; char response ; do { // have user enter all members until they are correct. . . } while (response != ‘Y’ ) ; return this. Animal ; } 19 19

Hierarchical Structures The type of a struct member can be another struct type. This is called nested or hierarchical structures. Hierarchical structures are very useful when there is much detailed information in each record. FOR EXAMPLE. . . 20

struct Machine. Rec Information about each machine in a shop contains: an id. Number, a written description, the purchase date, the cost, and a history (including failure rate, number of days down, and date of last service). 21

struct Date. Type { int month ; int day ; int year ; }; // Assume 1. . 12 // Assume 1. . 31 // Assume 1900. . 2050 struct Statistics. Type { float fail. Rate ; Date. Type last. Serviced ; int down. Days ; }; // Date. Type is a struct type struct Machine. Rec { int id. Number ; string description ; Statistics. Type history ; Date. Type purchase. Date ; float cost ; }; // Statistics. Type is a struct type Machine. Rec machine ; 22 22

struct type variable machine 7000 5719 “DRILLING…” . 02 1 25 1999 4 3 21 1995 8000. 0 . month. day. year. failrate . last. Serviced . id. Number. description. history . downdays. month. day. year . purchase. Date . cost machine. history. last. Serviced. year has value 1999 23

Unions in C++ DEFINITION A union is a struct that holds only one of its members at a time during program execution. EXAMPLE union Weight. Type { long wt. In. Ounces ; int wt. In. Pounds; float wt. In. Tons; } ; only one at a time 24

Using Unions union Weight. Type { long wt. In. Ounces ; int wt. In. Pounds; float wt. In. Tons; } ; // declares a union type Weight. Type weight; // declares a union variable weight. wt. In. Tons = 4. 83 ; // Weight in tons is no longer needed. Reuse the memory space. weight. wt. In. Pounds = 35; 25 25

Abstraction l is the separation of the essential qualities of an object from the details of how it works or is composed l focuses on what, not how l is necessary for managing large, complex software projects 26

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

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

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

Abstract Data Type (ADT) l a data type whose properties (domain and operations) are specified (what) independently of any particular implementation (how) FOR EXAMPLE. . . 30

ADT Specification Example TYPE Time. Type DOMAIN Each Time. Type 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 31

Another ADT Specification TYPE Complex. Number. Type 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 32

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

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

Some Possible Representations of Complex. Number. Type struct with 2 float members -16. 2. real 5. 8. imag 2 -element float array -16. 2 5. 8 35

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

class Time. Type Specification // SPECIFICATION FILE ( timetype. h ) class Time. Type { // declares a class data type // does not allocate memory public : // 5 public function members void bool Set ( int hours , int mins , int secs ) ; Increment ( ) ; Write ( ) const ; Equal ( Time. Type other. Time ) const ; Less. Than ( Time. Type other. Time ) const ; private : int int }; // 3 private data members hrs ; mins ; secs ; 37 37

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 38

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

class type Declaration The class declaration 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. 40

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. 41

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 42

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

Implementation File for Time. Type // IMPLEMENTATION FILE ( timetype. cpp ) // Implements the Time. Type member functions. #include “ timetype. h” #include <iostream> // also must appear in client code . . . bool Time. Type : : Equal ( /* in */ Time. Type other. Time ) const // Postcondition: // Function value == true, if this time equals other. Time // == false , otherwise { return ( (hrs == other. Time. hrs) && (mins == other. Time. mins) && (secs == other. Time. secs) ) ; } . . . 44

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 (some. Char) ; cin. ignore (100, ‘n’) ; l these statements declare my. Infile as an instance of class ifstream and invoke function member open ifstream my. Infile ; my. Infile. open ( “A: \mydata. dat” ) ; 45

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 specification abs trac bar tion rier implementation 46

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 current. Time. Write( ) ; number. Z. Write( ) ; l // class Time. Type // class Complex. Number. Type in the implementation file, the scope resolution operator is used in the heading before the function member’s name to specify its class void Time. Type : : Write ( ) const { . . . 47

Time. Type Class Instance Diagrams current. Time Set Increment Write Less. Than Equal end. Time Private data: hrs 17 mins 58 secs 2 Increment Write Less. Than Private data: hrs 18 mins 30 secs 0 Equal 48

Use of const with Member Functions l when a member function does not modify the private data members, use const in both the function prototype (in specification file) and the heading of the function definition (in implementation file) 49

Example Using const with a Member Function void Time. Type : : 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 ; 50 50

Separate Compilation and Linking of Files specification file main program timetype. h client. cpp implementation file timetype. cpp #include “timetype. h” Compiler client. obj timetype. obj Linker client. exe 51

Avoiding Multiple Inclusion of Header Files 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 52

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

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 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 54

Specification of Time. Type Class Constructors class Time. Type // timetype. h { public : // 7 function members void Set ( int hours , int minutes , int seconds ) ; void Increment ( ) ; void Write ( ) const ; bool Equal ( Time. Type other. Time ) const ; bool Less. Than ( Time. Type other. Time ) const ; Time. Type ( int init. Hrs , int init. Mins , int init. Secs ) ; // constructor Time. Type ( ) ; private : int int }; // default constructor // 3 data members hrs ; mins ; secs ; 55 55

Implementation of Time. Type Default Constructor Time. Type : : Time. Type ( ) // Default Constructor // Postcondition: // hrs == 0 && mins == 0 && secs == 0 { hrs = 0 ; mins = 0 ; secs = 0 ; } 56 56

Implementation of Another Time. Type Class Constructor Time. Type : : Time. Type ( /* in */ int init. Hrs, /* in */ int init. Mins, /* in */ int init. Secs ) // Constructor // Precondition: 0 <= init. Hrs <= 23 && 0 <= init. Mins <= 59 // 0 <= init. Secs <= 59 // Postcondition: // hrs == init. Hrs && mins == init. Mins && secs == init. Secs { hrs = init. Hrs ; mins = init. Mins ; secs = init. Secs ; } 57 57

Automatic invocation of constructors occurs Time. Type departure. Time ; Time. Type movie. Time (19, 30, 0 ) ; // default constructor invoked // parameterized constructor departure. Time Set Increment Write Less. Than Equal movie. Time Set Private data: hrs 0 mins 0 secs 0 Increment Write Less. Than Equal Private data: hrs 19 mins 30 secs 0 58
- Slides: 58