Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Structured Data Types and Classes

Similar presentations


Presentation on theme: "Introduction to Structured Data Types and Classes"— Presentation transcript:

1 Introduction to Structured Data Types and Classes
A Intro to structs & classes

2 Objectives In this chapter you will learn:
About structured data types and C++ structs About object-oriented programming and classes About information hiding How to use access specifiers About interface and implementation files How to prevent multiple inclusion How to work with member functions A Intro to structs & classes

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

4 Structured Data Type A structured data type is a type in which each value is a collection of component items. the entire collection has a single name each component can be accessed individually A Intro to structs & classes

5 C++ Structured Type often we have related information of various types that we’d like to store together for convenient access under the same identifier, for example . . . Define a data types to represent time Hours, mins, & seconds A Intro to structs & classes

6 Several Possible Representations of TimeType
3 int variables 3 strings 3-element int array actual choice of representation depends on time, space, and algorithms needed to implement operations “10” “45” “27” A Intro to structs & classes

7 Some Possible Representations of ComplexNumberType
struct with 2 float members 2-element float array .real imag A Intro to structs & classes

8 struct TimeType struct TimeType // declares a struct data type does not // allocate memory { int hrs ; // struct members int mins ; int secs ; } ; TimeType StartTime ; // declare variables of TimeType TimeType EndTime = {12, 0, 0}; // initializer list 8 A Intro to structs & classes

9 struct type Declaration
SYNTAX struct TypeName // does not allocate memory { MemberList } ; MemberList SYNTAX DataType MemberName ; . A Intro to structs & classes

10 struct type Declaration
The struct declaration creates a new data type and names the members of the struct. A struct declaration creates a new data type  a user-defined data type. It does not allocate memory for any variables of that type! You still need to declare your struct variables. A Intro to structs & classes

11 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 TypeNames 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. A Intro to structs & classes

12 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. Note: initial member values are unknown EXAMPLES StartTime.hrs = 5; EndTime.mins = 29; cin >> EndTime.hrs; A Intro to structs & classes

13 Aggregate Operation is an operation on a data structure as a whole, as opposed to an operation on an individual component of the data structure Allow use of a struct variable as a single unit A Intro to structs & classes

14 Aggregate struct Operations
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 I/O, arithmetic, and comparisons of entire struct variables are NOT ALLOWED! Can be defined using functions A Intro to structs & classes

15 Defining Aggregate struct Operations
void WriteOut( /* in */ TimeType thisTime) // outputs values of all members of thisTime in the format hrs:mins:secs // Precondition: all members of thisTime are assigned // Postcondition: all members have been written out { cout <<thisTime.hrs <<“:” << thisTime.mins ; cout << “:”<< thisTime.secs << endl; } A Intro to structs & classes

16 Structs: good or bad? + Allow representation of complex data that consists of several related fields that are of different types Initialization (or lack of it) can cause problems Only 3 aggregate ops are predefined, any other op must be defined as a separate function Functions that operate on struct are not textually related to the type definition Not access protection to data members A Intro to structs & classes

17 Abstraction is the separation of the essential qualities of an object from the details of how it works or is composed focuses on what, not how is necessary for managing large, complex software projects A Intro to structs & classes

18 Control Abstraction separates the logical properties of an action from its implementation . Search (list, item, length, where, found); the function call depends on the function’s specification (description), not its implementation (algorithm) A Intro to structs & classes

19 Data Abstraction LOGICAL PROPERTIES IMPLEMENTATION
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? A Intro to structs & classes

20 Data Type set of values allowable operations (domain) on those values
FOR EXAMPLE, data type int has domain operations +, -, *, /, %, >>, << A Intro to structs & classes

21 Abstract Data Type (ADT)
a data type whose properties are specified (what) independently of any particular implementation (how) Data type properties include both a domain and a set of allowable operations FOR EXAMPLE . . . A Intro to structs & classes

22 ADT Specification Example
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 A Intro to structs & classes

23 ADT Implementation means
choosing a specific data representation for the abstract data using data types that already exist (built-in or programmer-defined) writing functions for each allowable operation A Intro to structs & classes

24 Object-Oriented Programming and Classes
C++ allows the programmer to create Abstract Data Types using classes. In general, classes form the basis of object- oriented programming Example: lets create a new ADT for TimeType using a C++ class A Intro to structs & classes

25 class TimeType Specification
// SPECIFICATION FILE ( timetype.h ) class TimeType // declares a class data type { // does not allocate memory public : // 7 public function members int GetHrs() const; int GetMins() const; int GetSecs() const; void Set ( int hours , int mins , int secs ) ; void Increment ( ) ; void Write ( ) const ; bool LessThan ( TimeType otherTime ) const ; private : // 3 private data members int hrs ; int mins ; int secs ; } ; A Intro to structs & classes

26 Classes In C++ programming, classes are data structures that contain data members along with function members (also called member functions or methods) The data members define the domain i.e. set of values that objects of that type can take. The member functions define the allowable operations that can be used to manipulate objects of that type. A class encapsulates all the elements of an ADT in a single units. Note: Functions that are not part of a class are referred to as global functions A Intro to structs & classes

27 Classes Class definition = class specification + class implementation
declaration as in slide 25 Class implementation: defines each member function that is declared in the class specification Client programs: Programs that declare and use objects of the defined class Client programs must include, using an #include directive, the specification file of the class TimeType T; A Intro to structs & classes

28 Implementation of TimeType Member Functions
#include “ timetype.h” // Specification file #include <iostream> void TimeType :: Set ( int H, int M, int S) // Postcondition: data members are assigned new values as follows: // hrs = H, mins= M, and secs= S { hrs = H; mins = M; secs = S; } A Intro to structs & classes

29 Member Selection Operator
Member selection operator is used to access class members: T.hrs = 20; T.Write(); Classes allow the programmer to define different types of accessibility to the members of the class. A Intro to structs & classes

30 Information Hiding The principle of information hiding states that any class members that other programmers, sometimes called clients, do not need to access or know about should be hidden Information hiding helps minimize the amount of information that needs to pass in and out of an object, which helps increase program speed and efficiency Information hiding reduces the complexity of the code that clients see, allowing them to concentrate on the task of integrating an object into their programs A Intro to structs & classes

31 Access Specifiers The first step in hiding class information is to set access specifiers for class members Access specifiers control a client’s access to individual data members and member functions There are four levels of access specifiers: public, private, protected, and friend The public access specifier allows anyone to call a class’s member function or to modify a data member A Intro to structs & classes

32 Access Specifiers The private access specifier prevents clients from calling member functions or accessing data members and is one of the key elements in information hiding Example: assume in a client program we have TimeType T; T.hrs = 8; error because hrs is declared to be private T.set(8, 30, 48);  OK because member function set() is declared public. A Intro to structs & classes

33 Access Specifiers An access specifier that is placed on a line by itself followed by a colon is called an access label Access to classes is private by default Access to structs is public by default Accessor functions are public member functions that a client can call to retrieve or modify the value of a data member Because accessor functions often begin with the words get or set, they are also referred to as get or set functions A Intro to structs & classes

34 TimeType Class Instance Diagrams
currentTime endTime Private data: hrs mins secs Set Increment Write LessThan GetHrs 17 58 2 GetMins GetSecs Private data: hrs mins secs Set Increment Write LessThan GetHrs 19 30 GetMins GetSecs A Intro to structs & classes

35 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 abstraction barrier specification implementation A Intro to structs & classes

36 Interface and Implementation Files
Interface code refers to the data member and member function declarations inside a class definition’s braces Interface code does not usually contain definitions for member functions, nor does it usually assign values to the data members. Interface code is generally placed in a header file with a .h extension Implementation code refers to a class’s function definitions and any code that assigns values to a class’s data members Implementation code is placed in .cpp files Implementation code must have access to the class specification by using a #include directive C++ source files are distributed in compiled format, whereas header files are distributed as plain text files Interface code is the only code that can be seen by a user of the class A Intro to structs & classes

37 2 Separate Files Generally Used to Define a class
// SPECIFICATION FILE ( timetype .h ) // Specifies the data and function members. class TimeType { public: private: } ; // IMPLEMENTATION FILE ( timetype.cpp ) // Implements the TimeType member functions. A Intro to structs & classes

38 Implementation File for TimeType
// IMPLEMENTATION FILE ( timetype.cpp ) // Implements the TimeType member functions. #include “ timetype.h” // also must appear in client code #include <iostream> 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) ) ; } …………. A Intro to structs & classes

39 Example 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 ; } ; } A Intro to structs & classes 39

40 Separate Compilation and Linking of Files
specification file main program timetype.h implementation file client.cpp timetype.cpp #include “timetype.h” Compiler Compiler client.obj timetype.obj Linker client.exe A Intro to structs & classes

41 Modifying a Class When you modify a class, interface code, such as class member declarations, should change the least The implementation code normally changes the most when you modify a class This rule of thumb is not carved in stone because you may find it necessary to drastically modify your class’s interface A Intro to structs & classes

42 Modifying a Class But for the most part, the implementation is what will change No matter what changes you make to your implementation code, the changes will be invisible to clients if their only entry point into your code is the interface—provided that the interface stays the same A Intro to structs & classes

43 Avoiding Multiple Inclusion of Header Files
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 this preprocessor directive syntax is used to avoid the compilation error that would otherwise occur from multiple declarations of the same class #ifndef Preprocessor_Identifier #define Preprocessor_Identifier . . // class declaration #endif A Intro to structs & classes

44 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 A Intro to structs & classes

45 Visual C++ pragma once Directive
The pragma once directive instructs the compiler to include a header file only once, no matter how many times it encounters an #include statements for that header in other C++ files in the project Supported in Visual C++ only. A Intro to structs & classes

46 Visual C++ pragma once Directive
// timetype .h // SPECIFICATION FILE #pragma once // timetype .cpp // client.cpp // IMPLEMENTATION FILE // Appointment program class TimeType { #include “timetype.h” #include “timetype.h” public: int main ( void ) { private: } ; A Intro to structs & classes

47 Scope Resolution Operator ( :: )
C++ programs typically use several class types different classes can have member functions with the same name, like Write( ) Functions from several classes can be in the same file. Some functions may also be global functions 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 { } A Intro to structs & classes

48 Use of const with Member Functions
when a member function does not modify the private data members of the class, use const in both the function prototype (in specification file) and the heading of the function definition (in implementation file) void TimeType :: Write ( ) const { } A Intro to structs & classes

49 Example Using const with a Member Function
void TimeType :: Write ( ) const // Precondition: data members have been assigned values // Postcondition: Time has been output in form HH:MM:SS { if ( hrs < 10 ) cout << ‘0’ ; cout << hrs << ‘:’ ; if ( mins < 10 ) cout << mins << ‘:’ ; if ( secs < 10 ) cout << secs ; } A Intro to structs & classes 49

50 Inline Functions Functions defined inside the class body in an interface file are called inline functions To conform to information-hiding techniques, only the shortest function definitions, such as accessor functions, should be added to the interface file A Intro to structs & classes

51 Inline Functions A. Berrached@UHD Intro to structs & classes
// SPECIFICATION FILE ( timetype.h ) class TimeType // declares a class data type { // does not allocate memory public : // 7 public function members int GetHrs() const { return hrs; } ; int GetMins() const {return mins;} ; int GetSecs() const ; void Set ( int h , int m , int s ) ; void Increment ( ) ; void Write ( ) const { cout <<hrs<<“:”<<mins<<“:”<<secs<<endl; } ; bool LessThan ( TimeType otherTime ) const ; private : // 3 private data members int hrs ; int mins ; int secs ; A Intro to structs & classes

52 Inline Functions A. Berrached@UHD Intro to structs & classes
// SPECIFICATION FILE ( timetype.h ) class TimeType // declares a class data type { // does not allocate memory public : // 7 public function members int GetHrs() const { return hrs; } ; int GetMins() const {return mins;} ; int GetSecs() const ; void Set ( int h , int m , int s ) ; void Increment ( ) ; void Write ( ) const; bool LessThan ( TimeType otherTime ) const ; private : // 3 private data members int hrs ; int mins ; int secs ; } ; inline void TimeType::Write ( ) const { cout <<hrs<<“:”<<mins<<“:”<<secs<<endl; A Intro to structs & classes

53 Implementation--Increment
void TimeType::Increment ( ) { // Precondition: data members have been assigned values // Postcondition: time is advanced by 1 second with 23:59:59 wrapping // around to 0:0:0 secs = (secs+1)%60; if ( secs == 0) mins = (mins + 1) %60; if (mins == 0) hrs = (hrs + 1) % 24; }; // all class members are accessed without selection operator Notes: All class members, including private members, are accessible from the class implementation All members are accessed without the selection operator A Intro to structs & classes

54 Implementation--LessThan
bool TimeType::LessThan (TimeType otherTime ) cont { // Precondition: data members have been assigned values for both // this time and otherTime // Postcondition: return True if this time is earlier than otherTime; False //otherwise }; A Intro to structs & classes

55 Class Constructors a class constructor is a member function whose purpose is to initialize the private data members of a class object a class constructor is automatically invoked when a class object is instantiated (i.e. declared). You define a class constructor the same way you define any other member function, except: the name of a constructor is always the name of its class there is no return type for a constructor. a class may have several constructors with different parameter lists. A constructor with no parameters is the default constructor. Constructors are never called explicitly. They are implicitly invoked. A Intro to structs & classes

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

57 Implementation of TimeType Default Constructor
TimeType :: TimeType ( ) // Default Constructor // Postcondition: // hrs == 0 && mins == 0 && secs == 0 { hrs = 0 ; mins = 0 ; secs = 0 ; } A Intro to structs & classes

58 Implementation of Another TimeType Class Constructor
TimeType :: TimeType ( /* in */ int initHrs, /* in */ int initMins, /* in */ int initSecs ) // Constructor // Precondition: 0 <= initHrs <= && 0 <= initMins <= 59 // <= initSecs <= 59 // Postcondition: // hrs == initHrs && mins == initMins && secs == initSecs { hrs = initHrs ; mins = initMins ; secs = initSecs ; } A Intro to structs & classes

59 Automatic invocation of constructors occurs
TimeType departureTime ; // default constructor invoked TimeType movieTime (19, 30, 0 ) ; // parameterized constructor departureTime movieTime Set Set Private data: hrs mins secs Increment Private data: hrs mins secs Increment 19 30 Write Write LessThan LessThan Equal Equal A Intro to structs & classes

60 What if no default constructor is defined ?
TimeType departureTime ; // no default constructor defined TimeType movieTime (19, 30, 0 ) ; // error if no parameterized constructor Private data: hrs mins secs Set Increment Write LessThan Equal ? departureTime A Intro to structs & classes

61 Class Destructor--Preview
Invoked automatically when a class object is destroyed, example When control leave the block in which a local object is declared Named the same as the its class name, except that it is prefixed with a tilde character ~SomeClass() Only one destructor per class Generally used to de-allocate space allocated when class object was instantiated. A Intro to structs & classes

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


Download ppt "Introduction to Structured Data Types and Classes"

Similar presentations


Ads by Google