Presentation is loading. Please wait.

Presentation is loading. Please wait.

chapter 11 Structured Types, Data Abstraction, and Classes

Similar presentations


Presentation on theme: "chapter 11 Structured Types, Data Abstraction, and Classes"— Presentation transcript:

1 chapter 11 Structured Types, Data Abstraction, and Classes
Goals To be able to declare a record (struct) data type To be able to access a member of a record variable To be able to define a hierarchical record structure. To be able to access values stored in a hierarchical record variable To understand the general concept of a C++ union type To understand the difference between specification and implementation of an abstract data type. To be able to declare a C++ class type. To be able to declare class objects, given the declaration of a class type. To be able to write client code that invokes class member functions. To be able to implement class member function. To be able to organize the code for a C++ class into two file: the specification (.h) file and the implementation file. To be able to write a C++ class constructor.

2 11.1 Simple Versus Structured Data Types
Structured data type : A data type in which each value is a collection of components and whose organization is characterized by the method used to access individual components. The allowable operations on a structured data type include the storage and retrieval of individual components.

3 A structured type gathers together a set of component values and usually imposes a specific arrangement on them. The method used to access the individual components of a structured type depends on how the components are arranged.

4 11.2 Records (C++ Structs ) In computer science, a record is a heterogeneous structured data type. By heterogeneous, we mean that the individual components of a record can be of different data types. Each component of a record is called a field of the record, and each field is given a name called the field name. C++ uses its own terminology with records. A record is called a structure, the fields of a record are called members of the structure, and each member has a member name.

5 Record (structure, in C++) A structured data type with a fixed number of components that are accessed by name. The components may be heterogeneous ( of different types). Field (member, in C++) A component of a record.

6 StructureDeclaration
structure TypeName { MemberList }; DataType MemberName; :

7 Let’s use a struct to describe a student in a class
Let’s use a struct to describe a student in a class. We want to store the first and last names, the overall grade point average prior to this class, the grade on programming assignments, the grade on quizzes , the final exam grade, and the final couse grade. //Type declarations enum GradType {A, B , C ,D ,F } struct StudentRec { string firstName; string lastNames; float gpa; //Grade point average int programGrade; //Assume int quizeGrade; //Assume int finalExam; //Assume GradeType courseGrade; };

8 // Variable declarations
StudentRec firstStudent; StudentRec student; int grade;

9 Accessing individual Components
Member selector : The expression used to access components of a struct variable. It is formed by using the struct variable name and the member name, separated by a dot (period) MemberSelector Structure . MemberName

10 Aggregate Operations on Structs
Aggregate operation : An operation on a data structure as a whole , as opposed to an operation on an individual component of the data structure. Aggregate Operation Allowed on Structs I/O No Assignment Yes Arithmetic Comparison Argument passage Yes, by value or by reference Return as a function’s return value yes

11 More About Struct Declarations
struct TypeName { MemberList } variableList ;

12 Hierarchical Records A component of a record can also be another record. Records whose components are themselves records are called hierarchical records. Hierarchical record : A record in which at least one of the components is itself a record.

13 struct MachineRec { int idNumber; string description; float failRate; int lastServiceMonth ; //Assume 1..12 int lastSeviceDay; //Assume 1..31 int lastSeviceYear ; // Assume int downDays; int purchaseDateMonth; //Assume 1..12; int purchaseDateDay; //Assume int purchaseDateYear; //Assume float cost; };

14 struct DateType { int month; //Assume int day; //Assume int year; //Assume }; struct StaticsType float failRate; DateType lastServiced; int downDays; struct MachineRec int idNumber; string desription; StatisticsType history; DataType purchaseDate; float cost; MachineRec machine;

15 Expression Component accessed machine.purchaseDate Datatype struct variable machine.purchaseDate.month month member of a DateType struct variable machine.purchaseDate.year year member of a DateType struct variable machine.history.lastServiced.year year member of a Datetype struct variable contained in a struct of type StatisticsType.

16 11.3 Unions In C++, a union is defined to be a struct that holds only one of its members at a time during program execution. union WeightType { long wtInOunce ; int wtInPounds; float wtInTons ; }; WeightType weight;

17 At run time , the memory space allocated to the variable weight does not include room for three distinct components. Instead , weight can contain only one of the following : either a long value or an int value or a float value .

18 It’s quite reasonable to argue that a union is not a data structure at all. It does not represent a collection of values ; it represents only a single value from among several potential values . On the other hand, unions are grouped together with the structured types because of their similarity to structs.

19 11.4 Data Abstraction Data abstraction : The separation of a data types’s logical properties from its implementation.

20 11.5 Abstract Data Types We live in a complex world. To cope with complexity, the human mind engages in abstraction-the act of separating the essential qualities of an idea or object from the details of how it works or is composed. With abstraction, we focus on the what, not the how. Control abstraction is the separation of the logical properties of an action from its implementation. Abstract data type : A data type whose properties ( domain and operations ) are specified independently of any particular implementation.

21 Data representation : The concrete form of data used to represent the abstraction values of an abstract data type.

22 11.6 C++ Classes The separation of operations and data does not correspond very well with the notion of an abstract data type. After all, an ADT consists of both data values and operations on those values.

23 OPERATIONS DATA Operation 1 ( ) Operation 2 Operation 3 Figure Data and Operations as Separate Entities

24 Operation 1 Operation 2 Operation 3 Data Figure 11-7 Data and Operations Bound into a Single Unit

25 Class : A structure type in a programming language that is used to represent an abstract data type.
Class member : A component of a class. Class members may be either data or functions.

26 Here is a C++ class declaration corresponding to the TimeType ADT that we defined in the previous section : class TimeType { public : void Set(int, int , int ); void Increment( ); void Write( ) const; bool Equal( TimeType ) const; bool LessThan( TimeType ) const ; private : int hrs; int mins; int secs; };

27 The declaration of TimeType defines a data type but does not create variable of the type. Class variable ( more often referred to as class objects or class instances ) are create by using ordinary variable declarations : TimeType startTime; TimeType endTime; Any software that declares and manipulates TimeType object is called a client of the class. Class Object (class instance) : A variable of a class type. Client : Software that declares and manipulates objects of a particular class.

28 Data and/or functions declared between the words public and private constitute the public interface ; clients can access these class members directly. Class members declared after the word private are considered private information and are inaccessible to clients. If client code attempts to access a private item, the compiler signals an error. Private class members can be accessed only by the class’s member functions. This separation of class members into private and public parts in a hallmark of ADT design. To preserve the properties of an ADT correctly, an instance of the ADT should be manipulated only through the operations that form the public interface.

29 Regarding public versus private accessibility, we can now describe more fully the difference between C++ structs and classes. C++ defines a struct to be a class whose members are all, by default, public. In contrast , members of a class are, by default, private. Furthermore, it is most common to use only data, not functions, as members of a struct. Note thaty you can delcare struct members to be private and you can include member functions in a struct, but then you might as well as a class!

30 Classes, Class Objects , and Class Members
It is important to restate that a class is a type, not a object. Like any type, a class is a pattern from which you create ( or instantiate ) many objects of that type. The declarations TimeType time1; TimeType time2; create two objects of the TimeType class : time1 and time2. Each object has its own copies of hrs,mins, and secs, the private data members of the class .

31 time1 time2 Function code Set Write Equal LessThan 5 hrs 30 mins secs
Increment Write Equal LessThan 5 hrs 30 mins secs Function code Set Increment Write Equal LessThan 17 hrs 58 mins 2 secs

32 In truth , the C++ compiler does not waste memory by placing duplicate copies of a member function-say, Increment-into both time1 and time2. The compiler generates just one physical copy of Increment, and any class object executes this one copy of the function.

33 Built-in Operations on Class Objects
Two built-in operations that are valid for struct and class objects are member selection ( . ) and assignment (= ). You select an individual member of a class by using dot notation. That is , you write the name of the class object, then a dot, then the member name. time1.Increment( );

34 Earlier we remarked that the Equal and LessThan function have only one parameter each, even though they are comparing two TimeType objects. In the If statement of the previous code segment, we are comparing time1 and time2. Because LessThan is a class member, we invoke it by giving the name of a class object (time1), then a dot, then the function name (LessThan ). Only one item remains unspecified : the class object with which time1 should be compared (time2). Therefore , the LessThan fucntion requires only one parameter, not two .

35 Class Scope Class scope applies to the member names within structs, unions, and classes. To say that a member name has class scope means that the name is bound to that class (or struct or union) . If the same identifier happens to be declared outside the class, the two identifiers are unrelated.

36 Information Hiding Conceptually, a class object has an invisible wall around it. This wall , called the abstraction barrier, protects private data and functions from being accessed by client code. The barrier also prohibits the class object from directly accessing data and functions outside the object. This barrier is a critical characteristic of class and abstract data types. For a class object to share information with the outside world (that is ,with clients), there must be a gap in the abstraction barrier. This gap is the public interface –the class members declared to be public. The only way that a client can manipulate the internals of the class object is indirectly-through the operations in the public interface.

37 Abstraction barrier : The invisible wall around a class object that encapsulates implementation details. The wall can be breached only through the public interface. Black box : An electrical or mechanical device whose inner working are hidden from view. Information hiding : The encapsulation and hiding of implementation details to keep the user of an abstraction from depending on or incorrectly manipulating these detail.

38 11.7 Specification and Implementation Files
The specification describes the behavior of the data type without reference to its implementation. The implementation creates an abstraction barrier by hiding the concrete data representation as well as the code for the operations. In C++, it is customary (though not required ) to package the class declaration and the class implementation into separate files.

39 Compiling and Linking a Multifile Program
Separate compilation of source code files. a multifile program : a program divided up into several files containing source code. In C++ , it is possible to compile each of these files separately and at different times. The compiler translates each source code file into an object code file. The system’s linker program brings the object code together to form an executable program file.

40 An important benefit of separate compilation is that modifying the code in just one file requires recompiling only that file. The new .obj file is then relinked with the other existing .obj files. Of course, if a modification to one file affects the code in another file-for example, changing a function’s interface by altering the number or data types of the function parameters-then the affected files also need to be modified and recompiled.

41 The mechanics of compiling ,linking, and executing vary form one computer system to another. Many C++ systems provide an integrated environment-a program that bundles the editor, the compiler, and the linker into one package. Whichever environment you use-the command-line environment or an integrated environment-the overall process is the same: You compile the individual source code files into object code, link the object files into an executable program. Then execute the program.

42 11.8 Guaranteed Initialization with Class Constructs
C++ provides a mechanism, called a class constructor, to guarantee the initialization of a class object. A constructor is a member function that is implicitly invoked whenever a class object is created. A constructor function has an unusual name : the name of the class itself. Examp e:\ecpp\chap11_TimeType.h e:\ecpp\char11_TimeType.cpp

43 Invoking a Constructor
Although a constructor is a member of a class , it is never invoked using dot notation. A constructor is automatically invoked whenever a class objects is created.

44 Guidelines for using class constructors
A constructor cannot return a function value , so the function is declared without a return value type. A class may provide several constructors. When a class object is declared , the compiler choose the appropriate constructor according to the number and data types of the arguments to the constructor. Arguments to a constructor are passed by placing the argument list immediately after the name of the class object being declared: If a class object is declared without an argument list ,as in the statement SomeClass anObject; then the effect depends upon what constructors( if any ) the class provide. If the class has no constructors at all, memory is allocated for anObject but its private data members are in an uninitialized state. If the class does have constructors, then the default (parameterless) constructor is invoked if there is one. If the class has constructors but no default constructor, a syntax error occurs.

45 Another special member function supported by C++ : the class destructor.
Just as a constructor is implicitly invoked when a class object is created, a destructor is implicitly invoked when a class object is destroyed-for example, when control leaves the block in which a local object is declared . A class destructor is named the same as a constructor except that the first character is a tilde(~): class SomeClass { public : : SomeClass( ); // Constructor ~SomeClass( ); // Destructor private : }


Download ppt "chapter 11 Structured Types, Data Abstraction, and Classes"

Similar presentations


Ads by Google