chapter 11 Structured Types, Data Abstraction, and Classes

Slides:



Advertisements
Similar presentations
1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
Advertisements

Road Map Introduction to object oriented programming. Classes
Chapter 3 Data Abstraction: The Walls. © 2005 Pearson Addison-Wesley. All rights reserved3-2 Abstract Data Types Modularity –Keeps the complexity of a.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Lecture 29 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 11: Classes and Data Abstraction
Abstract Data Types and Encapsulation Concepts
1 Abstract Data Type (ADT) a data type whose properties (domain and operations) are specified (what) independently of any particular implementation (how)
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Chapter 11: Classes and Data Abstraction. C++ Programming: Program Design Including Data Structures, Fourth Edition2 Objectives In this chapter, you will:
Cosc237/structures1 Structures aggregate data types record - single variable name for the whole collection composed of several variables - fields,BUT,
Defining New Types Lecture 21 Hartmut Kaiser
CHAPTER 13 CLASSES AND DATA ABSTRACTION. In this chapter, you will:  Learn about classes  Learn about private, protected, and public members of a class.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
1 Chapter Structured Types, Data Abstraction and Classes Dale/Weems.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
Copyright © 2002 W. A. Tucker1 Chapter 10 Lecture Notes Bill Tucker Austin Community College COSC 1315.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
1 CS Programming Languages Class 22 November 14, 2000.
1 Copyright © 1998 by Addison Wesley Longman, Inc. Chapter 10 Abstraction - The concept of abstraction is fundamental in programming - Nearly all programming.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 12: Classes and Data Abstraction.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 11: Classes and Data Abstraction.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 05: Classes and Data Abstraction.
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
72 4/11/98 CSE 143 Abstract Data Types [Sections , ]
1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
Chapter 11: Abstract Data Types Lecture # 17. Chapter 11 Topics The Concept of Abstraction Advantages of Abstract Data Types Design Issues for Abstract.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
1 Chapter 12 Classes and Abstraction. 2 Chapter 12 Topics Meaning of an Abstract Data Type Declaring and Using a class Data Type Using Separate Specification.
1 Structured Types, Data Abstraction and Classes.
Chapter 12 Classes and Abstraction
EGR 2261 Unit 13 Classes Read Malik, Chapter 10.
Programming Logic and Design Seventh Edition
Abstract Data Types and Encapsulation Concepts
Object-Oriented Programming: Classes and Objects
Dale/Weems/Headington
Java Programming: Guided Learning with Early Objects
Review: Two Programming Paradigms
Chapter 3: Using Methods, Classes, and Objects
11.1 The Concept of Abstraction
About the Presentations
Chapter Structured Types, Data Abstraction and Classes
Object-Oriented Programming: Classes and Objects
Lecture 9 Concepts of Programming Languages
Abstract Data Types and Encapsulation Concepts
Introduction to Structured Data Types and Classes
CS212: Object Oriented Analysis and Design
CS148 Introduction to Programming II
Classes and Data Abstraction
Abstract Data Types and Encapsulation Concepts
Lecture 22 Inheritance Richard Gesick.
Defining New Types Lecture 22 Hartmut Kaiser
Classes and Objects.
Defining Classes and Methods
Defining Classes and Methods
Defining Classes and Methods
Chapter 9 Introduction To Classes
CS148 Introduction to Programming II
11.1 The Concept of Abstraction
Lecture 9 Concepts of Programming Languages
Chapter 11 Abstraction - The concept of abstraction is fundamental in
Introduction to Classes and Objects
Presentation transcript:

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.

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.

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.

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.

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.

StructureDeclaration structure TypeName { MemberList }; DataType MemberName; :

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 0..400 int quizeGrade; //Assume 0..300 int finalExam; //Assume 0..300 GradeType courseGrade; };

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

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

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

More About Struct Declarations struct TypeName { MemberList } variableList ;

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.

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

struct DateType { int month; //Assume 1 . .12 int day; //Assume 1 . .31 int year; //Assume 1900 . .2050 }; struct StaticsType float failRate; DateType lastServiced; int downDays; struct MachineRec int idNumber; string desription; StatisticsType history; DataType purchaseDate; float cost; MachineRec machine;

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.

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;

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 .

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.

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

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.

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

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.

OPERATIONS DATA Operation 1 ( ) Operation 2 Operation 3 Figure 11-6 Data and Operations as Separate Entities

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

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.

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; };

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.

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.

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!

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 .

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

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.

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( );

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 .

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.

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.

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.

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.

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.

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.

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.

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

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.

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.

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 : }