C++ Data Types and Data Abstractions

109
1 C++ C++ Data Types and Data Abstractions Data Types and Data Abstractions

description

C++ Data Types and Data Abstractions. C++ Data Types. Namespaces Built-in data types Literal constants Variables Pointers References The C++ string Type The const Qualifier. What is “using namespace std;”. #include using namespace std; void main ( ) { int start = 5; - PowerPoint PPT Presentation

Transcript of C++ Data Types and Data Abstractions

Page 1: C++ Data Types and Data Abstractions

1

C++C++

Data Types and Data AbstractionsData Types and Data Abstractions

Page 2: C++ Data Types and Data Abstractions

2

C++ Data TypesC++ Data Types

• Namespaces• Built-in data types• Literal constants• Variables• Pointers• References• The C++ string Type• The const Qualifier

Page 3: C++ Data Types and Data Abstractions

3

What is “using namespace std;”What is “using namespace std;”

#include <iostream>

using namespace std;

void main ( ) {int start = 5;

int end = 19;

if (start < end ) {

cout << “A”;

} // end if

cout << “B”;

} // end main

Page 4: C++ Data Types and Data Abstractions

4

NamespacesNamespaces

The problem: When two variables (or functions) in global scope have the same identifier (name), we get a compile-time error.

To avoid such name collisions, programmers need to use unique identifiers in their own code.In C, if you use multiple third-party libraries and there is a name collision, you have three choices:

• Get the source code to the libraries and modify and recompile it,• ask one of the library publishers to rename their identifiers, or• decide not to use one of the libraries.

Often, none of these options are available.

Page 5: C++ Data Types and Data Abstractions

5

NamespacesNamespaces

To tackle this problem, C++ introduced namespaces.

All identifiers declared within a defined block are associated with the block’s namespace identifier.

All references to these identifiers from outside the block must indicate the namespace identifier.

One example is the namespace std, in which Standard C++ defines its library’s identifiers, such as the cout stream object.

Page 6: C++ Data Types and Data Abstractions

6

NamespacesNamespaces

You can access objects in the namespace std in the following way using the scope resolution operator “::”

#include <iostream>

int main()

{

std::cout << “Hello World!”;

return 0;

}

Page 7: C++ Data Types and Data Abstractions

7

NamespacesNamespaces

Or, you can use the using namespace statement to omit the corresponding namespace references:

#include <iostream>

using namespace std;

int main()

{

cout << “Hello World!”;

return 0;

}

Page 8: C++ Data Types and Data Abstractions

8

NamespacesNamespaces

This is how you define your own namespaces:

#include <iostream>namespace MyNames{

int value1 = 10;int value2 = 20;int ComputeSum(){ return (value1 + value2);}

}

int main(){

std::cout << MyNames::ComputeSum() << std::endl;}

Page 9: C++ Data Types and Data Abstractions

9

NamespacesNamespaces

If you use multiple using namespace statements, you may get a compile-time error due to ambiguity:

#include <iostream>

namespace MyNames

{

int value1 = 10;

int value2 = 20;

}

namespace MyOtherNames

{

int value1 = 30;

int value2 = 40;

}

using namespace std;using namespace MyNames;using namespace MyOtherNames;

int main(){

value1 = 50;}

Page 10: C++ Data Types and Data Abstractions

10

NamespacesNamespacesYou can also define nested namespaces:

#include <iostream>namespace MyNames{

int value1 = 10;int value2 = 20;namespace MyInnerNames{

int value3 = 30;}

}

int main(){

std::cout << MyNames::value1 << std::endl;std::cout << MyNames::MyInnerNames::value3 << std::endl;

}

Page 11: C++ Data Types and Data Abstractions

11

Numeric Data TypesNumeric Data Types

• Type char represents individual characters and small integers (1 byte).

• Types short, int, and long represent integer values (half a machine word, 1 machine word, 1 or more machine words)

• Types float, double, and long double represent floating point values (1 machine word, 2 machine words, 3 or 4 machine words)

Page 12: C++ Data Types and Data Abstractions

12

Numeric Data TypesNumeric Data Types

• Type char, short, int, and long are also called integral types.

• Integral types can be signed or unsigned.

• Example: The value of an 8-bit unsigned char ranges from 0 to 255, while the range for an 8-bit signed char is from –128 to 127.

Page 13: C++ Data Types and Data Abstractions

13

Literal ConstantsLiteral Constants

Literal constants are values that occur in a program.Example:

int main(){ int students = 21; double pi = 3.1416;}

Here, 21 is a literal constant of type int, and 3.1416 is a literal constant of type double.

Page 14: C++ Data Types and Data Abstractions

14

Literal ConstantsLiteral Constants

We can use prefixes to write literal integer constants in decimal, octal, or hexadecimal notation.

Examples: Decimal (no prefix): 15

Octal (prefix 0 [zero]): 015 = 13 (decimal)

Hexadecimal (prefix 0x [zero-x]): 0x15 = 21 (decimal)

Page 15: C++ Data Types and Data Abstractions

15

Literal ConstantsLiteral ConstantsBy default, the C++ compiler assumes that all literal integer constants are of type int and all literal floating point constants are of type double.

You can specify different types by appending a letter to the literal integer constant.

Examples:

2344U (unsigned)

1555L (long)

166UL (unsigned long)

3.1416F (float)

6.2831L (long double)

Page 16: C++ Data Types and Data Abstractions

16

Literal ConstantsLiteral Constants

Another built-in (or primitive) C++ data type is the type bool.

Its only literals are true and false.

Note that the type bool does not exist in C.

In C, we represent the Boolean values true and false by the integers 1 and 0.

Page 17: C++ Data Types and Data Abstractions

17

Literal ConstantsLiteral Constants

We use single quotation marks to write literal character constants.

Examples: ‘x’, ‘4’, ‘:’, ‘ ‘ (space)

Nonprintable characters and some special characters can be represented by escape sequences.

Examples:

‘\n’ (newline), ‘\a’ (bell), ‘\t’ (tab)

‘\\’ (backslash), ‘\’’ (single quote), ‘\”’ (double quote)

Page 18: C++ Data Types and Data Abstractions

18

Literal ConstantsLiteral Constants

Generalized escape sequences are indicated by a backslash followed by up to three digits.

The value of the digits in the sequence is interpreted as the corresponding literal constant in the ASCII character set.

Examples:

\7 (bell)

\14 (newline)

\65 (‘5’)

Page 19: C++ Data Types and Data Abstractions

19

Literal ConstantsLiteral Constants

A character literal can be preceded by an L, for example: L’a’

This is called a wide-character literal and has type wchar_t.

Such wide-character literals support language character sets like Chinese and Japanese, which cannot be represented within the 256 character ASCII set.

Page 20: C++ Data Types and Data Abstractions

20

Literal ConstantsLiteral Constants

A literal string constant is composed of zero or more characters enclosed in double quotation marks.

Examples:

“” (null string)

“x”

“hello”

“Hi,\nHow are you?\n”

Page 21: C++ Data Types and Data Abstractions

21

Literal ConstantsLiteral Constants

A string literal can be written across multiple lines. You can use a backslash as the last character on a line to indicate that the string continues on the next line.

Example:

“This is an \

excellent \

multi-line string literal.”

Page 22: C++ Data Types and Data Abstractions

22

VariablesVariablesVariables provide us with named memory storage that we can

• write to,• read from, and• manipulatethroughout the course of our program.

Each variable has a specific type, which determines• the size and layout of its associated memory,• the range of values that can be stored, and• the set of operations that can be applied to it.

Variables are also referred to as objects.

Page 23: C++ Data Types and Data Abstractions

23

VariablesVariables

There are two values associated with a variable:

1. Its data value, which is stored at some memory address. It is also called the rvalue (read value) of the variable.

2. Its address value, indicating the location in memory

where its data value is stored. This value is also referred to as the variable’s lvalue (location value).

Page 24: C++ Data Types and Data Abstractions

24

PointersPointers

• A pointer holds the memory address of another object.• Through the pointer we can indirectly manipulate the

referenced object.

Pointers are useful for

• Creating linked data structures such as trees and lists,• management of dynamically allocated objects, and• as a function parameter type for passing large objects

such as arrays.

Page 25: C++ Data Types and Data Abstractions

25

PointersPointers

• Every pointer has an associated type.• The type of a pointer tells the compiler how to

interpret the memory content at the referenced location and how many bytes this interpretation includes.

Examples of pointer definitions:

int *pointer;

int *pointer1, *pointer2;

string *myString;

Page 26: C++ Data Types and Data Abstractions

26

PointersPointers

The dereference operator (*) dereferences a pointer variable so that we can manipulate the memory content at the location specified by the pointer.

The address-of operator (&) provides the memory address (a pointer) of a given object.

Page 27: C++ Data Types and Data Abstractions

27

PointersPointers

Example: Correct or incorrect?

int var1=333, var2=444, *pvar1, *pvar2;

pvar1 = var1; incorrect. *int int

pvar2 = &var2; correct. *int = *int

*pvar1 = var2; correct. int = int

*pvar2 = *pvar1 + 100; correct. int = int

Page 28: C++ Data Types and Data Abstractions

28

PointersPointersNotice that in pointer definitions the ‘*’ symbol indicates the pointer type and is not the dereference operator.

Example:int var;int *pvar1 = var;

Incorrect! During initialization a pointer can only be assigned an address:int var;int *pvar1 = &var;Correct!

Page 29: C++ Data Types and Data Abstractions

29

ReferencesReferences

• References (aliases) can be used as alternative names for objects.

• In most cases they are used as formal parameters to a function.

• A reference type is defined by following the type specifier with the address-of operator.

Example:

int val1 = 333;

int &refVal1 = val1;

Page 30: C++ Data Types and Data Abstractions

30

ReferencesReferences• A reference must be initialized.• Once defined, a reference cannot be made to refer to

another object.• All operations on the reference are actually applied to the

object to which the reference refers.

Example:

int val1 = 333;int &refVal1 = val1;val1++;refVal1 += 100;cout << “Result: ” << refVal1;

Result: 434

Page 31: C++ Data Types and Data Abstractions

Pass-by-valuePass-by-value

CALLINGBLOCK

FUNCTION CALLED

sends a copy of the contents of the actual parameter

SO, the actual parameter cannot be changed by the function.

31

Page 32: C++ Data Types and Data Abstractions

Pass-by-referencePass-by-reference

sends the location (memory address)of the actual parameter

can change value ofactual parameter

CALLINGBLOCK FUNCTION

CALLED

32

Page 33: C++ Data Types and Data Abstractions

33

The C++ string TypeThe C++ string TypeTo use the C++ string type, you must include its associated header file:#include <string>

Different ways to initialize strings:string myString(“Hello folks!”);string myOtherString(myString);string myFinalString; // empty string

The length of a string is returned by its size() operation (without the terminating null character): cout << myString.size();

= 12

Page 34: C++ Data Types and Data Abstractions

34

The C++ string TypeThe C++ string Type

We can use the empty() operation to find out whether a string is empty:

bool isStringEmpty = myString.empty();

Use the equality operator to check whether two strings are equal:

if (myString == myOtherString)

cout << “Wow, the strings are equal.”;

Copy one string to another with the assignment operator: myFinalString = myOtherString;

Page 35: C++ Data Types and Data Abstractions

35

The C++ string TypeThe C++ string Type

Use the plus operator to concatenate strings:

string s1 = “Wow! ”, s2 = “Ouch! ”;

const char *s3 = “Yuck! ”

s2 += s1 + s3 + s2;

cout << s2;

= Ouch! Wow! Yuck! Ouch!

Page 36: C++ Data Types and Data Abstractions

36

The const QualifierThe const Qualifier

The const type qualifier transforms an object into a constant. Example: const double pi = 3.1416;

• Constants allow you to store parameters in well- defined places in your code• Constants have an associated type. • Constants must be initialized.• Constants cannot be modified after their definition.• Constants replace the #define “technique” in C.

Page 37: C++ Data Types and Data Abstractions

37

The const QualifierThe const Qualifier

Sometimes you may want to define for your object a set of states or actions.

For example, you could define the following states for the Student Counselor:

• observeStudent• shoutAtStudent• followStudent• rechargeBattery

Page 38: C++ Data Types and Data Abstractions

38

The const QualifierThe const Qualifier

Using the const qualifier, you could define the following constants:

const int observeStudent = 1;

const int shoutAtStudent = 2;

const int followStudent = 3;

const int rechargeBattery = 4;

A function SetRobotState could then be defined as follows:

bool SetRobotState(int newState)

{

int currentState = newState;

return executionSuccessful;

}

Page 39: C++ Data Types and Data Abstractions

39

Enumeration TypesEnumeration Types

However, mapping states onto integers has certain disadvantages:

• You cannot restrain the range of values that are passed to SetRobotState.• There is no useful typing – if you define individual sets of states for multiple objects, each object could formally be set to any of these states, not only its individual ones.

This problem can be solved with enumeration types.

Page 40: C++ Data Types and Data Abstractions

40

Enumeration TypesEnumeration TypesEnumeration types can be defined as follows:

enum robotState { observeStudent = 1, shoutAtStudent, followStudent, rechargeBattery };

This way we defined a new type robotState that can only assume four different values.

These values still correspond to integers. For example,

cout << followStudent;gives you the output ‘3’.

Page 41: C++ Data Types and Data Abstractions

41

Enumeration TypesEnumeration TypesWe are now able to restrain the values that are passed to SetRobotState to the four legal ones:

bool SetRobotState(robotState newState){ … robotState currentState = newState; return executionSuccessful;}

Any attempt to call SetRobotState with an integer value or a value of a different enumeration type will cause an error at compile time.

Page 42: C++ Data Types and Data Abstractions

42

C++ Data TypesC++ Data Types

structured

array struct union class

address

pointer reference

simple

integral enum

char short int long bool

floating

float double long double

Page 43: C++ Data Types and Data Abstractions

43

Structured Data TypesStructured Data Types

Chapter 11

Page 44: C++ Data Types and Data Abstractions

44

C++ Data TypesC++ Data Types

structured

array struct union class

address

pointer reference

simple

integral enum

char short int long bool

floating

float double long double

Skipping for now…

Page 45: C++ Data Types and Data Abstractions

45

Structured Data Type 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

Page 46: C++ Data Types and Data Abstractions

46

C++ Structured Type 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 . . .

Page 47: C++ Data Types and Data Abstractions

47

thisAnimalthisAnimal

.id 2037581

.name “giant panda”

.genus “Ailuropoda”

.species “melanoluka”

.country “China”

.age 18

.weight 234.6

.health Good

Page 48: C++ Data Types and Data Abstractions

48

anotherAnimalanotherAnimal

.id 5281003

.name “llama”

.genus “Lama”

.species “peruana”

.country “Peru”

.age 7

.weight 278.5

.health Excellent

Page 49: C++ Data Types and Data Abstractions

49

struct AnimalTypestruct AnimalType

enum HealthType { Poor, Fair, Good, Excellent } ;

struct AnimalType // declares a struct data type{ // does not allocate memory

long id ;string name ;string genus ;string species ; struct members string country ; int age ; float weight ; HealthType health ;

} ;

AnimalType thisAnimal ; // declare variables of AnimalType

AnimalType anotherAnimal ; 49

Page 50: C++ Data Types and Data Abstractions

50

structstruct type Declaration type Declaration

SYNTAX struct TypeName {

MemberList } ;

MemberList SYNTAX

DataType MemberName ;

DataType MemberName ; . . .

Page 51: C++ Data Types and Data Abstractions

51

structstruct type Declaration 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.

Page 52: C++ Data Types and Data Abstractions

52

structstruct type declarations 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.

Page 53: C++ Data Types and Data Abstractions

53

AccessingAccessing structstruct Members 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.

EXAMPLESthisAnimal.weightanotherAnimal.country

Page 54: C++ Data Types and Data Abstractions

54

Valid operations on a struct member Valid operations on a struct member depend only on its typedepend 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++;

Page 55: C++ Data Types and Data Abstractions

55

Aggregate Operation Aggregate Operation

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

Page 56: C++ Data Types and Data Abstractions

56

AggregateAggregate struct struct Operations Operations

I/O, arithmetic, and comparisons of entire struct variables are NOT ALLOWED!

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

Page 57: C++ Data Types and Data Abstractions

57

Examples of Examples of aggregate aggregate structstruct operations operations

anotherAnimal = thisAnimal ; // assignment

WriteOut(thisAnimal); // value parameter

ChangeWeightAndAge(thisAnimal); // reference parameter

thisAnimal = GetAnimalData( ); // return value of function

Page 58: C++ Data Types and Data Abstractions

58

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

58

Page 59: C++ Data Types and Data Abstractions

59

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 Passing a structstruct Type by Reference Type by Reference

Page 60: C++ Data Types and Data Abstractions

60

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 ;

}60

Page 61: C++ Data Types and Data Abstractions

61

Hierarchical Structures 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 . . .

Page 62: C++ Data Types and Data Abstractions

62

struct MachineRecstruct MachineRec

Information about each machine in a shop contains:

an idNumber,

a written description,

the purchase date,

the cost,

and a history (including failure rate, number of days down, and date of last service).

Page 63: C++ Data Types and Data Abstractions

63

struct DateType

{ int month ; // Assume 1 . . 12

int day ; // Assume 1 . . 31

int year ; // Assume 1900 . . 2050

};

struct StatisticsType

{ float failRate ;

DateType lastServiced ; // DateType is a struct type

int downDays ;

} ;

struct MachineRec

{ int idNumber ;

string description ;

StatisticsType history ; // StatisticsType is a struct type

DateType purchaseDate ;

float cost ;

} ;

MachineRec machine ; 63

Page 64: C++ Data Types and Data Abstractions

64

struct type variable struct type variable machinemachine

.idNumber .description . history .purchaseDate .cost

.month .day .year

5719 “DRILLING…” 3 21 1995 8000.0

.failrate .lastServiced .downdays

.02 1 25 1999 4.month .day .year

machine.history.lastServiced.year has value 1999

Page 65: C++ Data Types and Data Abstractions

65

C++ Data TypesC++ Data Types

structured

array struct union class

address

pointer reference

simple

integral enum

char short int long bool

floating

float double long double

Page 66: C++ Data Types and Data Abstractions

66

Unions in C++Unions in C++

Definition

A union is a struct that holds only one of its members at a time during program execution.

For Example

union WeightType

{

long wtInOunces ; int wtInPounds; only one at a time

float wtInTons;

} ;

Page 67: C++ Data Types and Data Abstractions

67

Using UnionsUsing 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;

Page 68: C++ Data Types and Data Abstractions

68

Abstraction Abstraction

Abstraction is the separation of the essential qualities of an object from the details of how it works or is composed

It focuses on what, not how

It is necessary for managing large, complex software projects

Page 69: C++ Data Types and Data Abstractions

69

Control Abstraction 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)

Page 70: C++ Data Types and Data Abstractions

70

Data Abstraction Data Abstraction

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?

Page 71: C++ Data Types and Data Abstractions

71

Data Type Data Type

set of values(domain)

allowable operationson those values

For example, data type int has

domain

-32768 . . . 32767

operations

+, -, *, /, %, >>, <<

Page 72: C++ Data Types and Data Abstractions

72

Abstract Data Type (ADT)Abstract Data Type (ADT)

Is a programmer-defined type with a set of

values and allowable operations for the type.

Some ways to define a new C++ type are:

using typedef

using struct

using class

Page 73: C++ Data Types and Data Abstractions

73

Using Using typedeftypedef

typedef int Boolean;

typedef char String20 [21] ;

String20 message; // variable declarations

Boolean seniorCitizen;

Page 74: C++ Data Types and Data Abstractions

74

Using Using structstruct

typedef char String20 [ 21 ] ;

struct EmployeeType { // declares a struct data type

long idNumber ;

String20 name ; data members

int hoursWorked ;

int numDependents ;

float hourlyWage ;

} ;

EmployeeType mySelf; // declares variable

Page 75: C++ Data Types and Data Abstractions

75

mySelf mySelf

.idNumber 213456789

.name ‘B’ ‘a’ ‘r’ ‘b’ ‘a’ ‘r‘ ‘a’ ‘ ’ ‘ ’ ‘ ’ ‘ ’ ‘\0’ . . .

.hoursWorked 38

.dependents 4

.hourlyWage 24.50

Page 76: C++ Data Types and Data Abstractions

76

Abstract Data Type (ADT) Abstract Data Type (ADT)

An ADT is a data type whose properties (domain and operations) are specified (what) independently of any particular implementation (how)

For example . . .

Page 77: C++ Data Types and Data Abstractions

77

ADT Specification ExampleADT Specification Example

TYPETimeType

DOMAINEach TimeType value is a time in hours, minutes, and seconds.

OPERATIONSSet the timePrint the timeIncrement by one secondCompare 2 times for equalityDetermine if one time is “less than” another

Page 78: C++ Data Types and Data Abstractions

78

Another ADT SpecificationAnother ADT Specification

TYPEComplexNumberType

DOMAIN

Each value is an ordered pair of real numbers (a, b) representing a + bi.

OPERATIONSInitialize the complex numberWrite the complex numberAdd SubtractMultiplyDivideDetermine the absolute value of a complex number

Page 79: C++ Data Types and Data Abstractions

79

ADT Implementation means 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

Page 80: C++ Data Types and Data Abstractions

80

Information HidingInformation 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.

clientcode

specification implementation

abstraction barrier

Page 81: C++ Data Types and Data Abstractions

81

Benefits of information hidingBenefits of information hiding

Data and details can be concealed from the client of the abstraction.

Code can be changed without affecting the client because the specification and interface are unchanged.

Page 82: C++ Data Types and Data Abstractions

82

10 45 27

Several Possible Representations of Several Possible Representations of TimeTypeTimeType

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

“10” “45” “27”

Page 83: C++ Data Types and Data Abstractions

83

Some Possible RepresentationsSome Possible Representationsof of ComplexNumberTypeComplexNumberType

struct with 2 float members

2-element float array

-16.2 5.8

-16.2 5.8

.real .imag

Page 84: C++ Data Types and Data Abstractions

84

C++ Data TypesC++ Data Types

structured

array struct union class

address

pointer reference

simple

integral enum

char short int long bool

floating

float double long double

Page 85: C++ Data Types and Data Abstractions

85

class TimeTypeclass TimeType Specification 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 ;

} ;

Page 86: C++ Data Types and Data Abstractions

86

Use of C++ data TypeUse of C++ data Type class class

Facilitates re-use of C++ code for an ADT

Software that uses the class is called a client

Variables of the class type are called class objects or class instances

Client code uses public member functions to handle its class objects

Page 87: C++ Data Types and Data Abstractions

87

Using Using classclass

A class is a programmer-defined type whose components (called class members) can be variables or functions.

Class members are private by default. Compiler does not permit client code to access private class members.

Class members declared public form the interface between the client and the class.

In most classes, the private members contain data, and the public members are functions to manipulate that data.

Page 88: C++ Data Types and Data Abstractions

88

Member functions categorized by taskMember functions categorized by task

CONSTRUCTOR -- a member function that actually creates a new instance and initialized some or all of its data members

ACCESS FUNCTION or OBSERVER -- a member function that can inspect (use but not modify) the data members of a class without changing their values. Such a function is declared with const following the parameter list in both the specification and the implementation files.

Page 89: C++ Data Types and Data Abstractions

89

Client Code UsingClient Code Using TimeTypeTimeType

#include “timetype.h” // includes specification of the classusing 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 ; } ;}

89

Page 90: C++ Data Types and Data Abstractions

90

classclass type Declaration 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.

Page 91: C++ Data Types and Data Abstractions

91

C++ Data Type C++ Data Type classclass represents an ADT represents an ADT

2 kinds of class members: data members and function members

Class members are private by default

Data members are generally private

Function members are generally declared public

Private class members can be accessed only by the class member functions (and friend functions), not by client code.

Page 92: C++ Data Types and Data Abstractions

92

AggregateAggregate class class Operations Operations

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

Other operations can be defined as class member functions

Page 93: C++ Data Types and Data Abstractions

93

2 separate files Generally Used for2 separate files Generally Used for classclass Type Type

// Specification File ( timetype .h ) // Specifies the data and function members. class TimeType { public: . . .

private: . . . } ;

// Implementation File ( timetype.cpp ) // Implements the TimeType member functions. . . .

Page 94: C++ Data Types and Data Abstractions

94

Implementation File for Implementation File for TimeTypeTimeType

// 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)

) ; }

. . .

Page 95: C++ Data Types and Data Abstractions

95

Member selection operator .Member selection operator .

When a client uses a public member function, the function call requires a dot preceded by the name of the object. You can think of the function call as being sent to this object.

ofstream outFile ;

outFile.open (“a:\\my.out”) ;...

outFile.close( ) ;

classtype

variable,object,instance

Page 96: C++ Data Types and Data Abstractions

96

Familiar Class Instances and Familiar Class Instances and Function Members Function Members

The member selection operator ( . ) selects either data members or function members

Header files iostream and fstream declare the istream, ostream,and ifstream, ofstream I/O classes

Both cin and cout are class objects and get and ignore are function members

cin.get (someChar) ;cin.ignore (100, ‘\n’) ;

The statements below, declare myInfile as an instance of class ifstream and invoke function member open

ifstream myInfile ;

myInfile.open ( “A:\\mydata.dat” ) ;

Page 97: C++ Data Types and Data Abstractions

97

Scope Resolution Operator ( :: ) Scope Resolution Operator ( :: )

C++ programs typically use several class types

Different classes can have member functions with the same identifier, like Write( )

Member selection operator is used to determine the class whose member function Write( ) is invoked

currentTime .Write( ) ; // class TimeTypenumberZ .Write( ) ; // class ComplexNumberType

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

}

Page 98: C++ Data Types and Data Abstractions

98

TimeType TimeType Class Instance DiagramsClass 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

Page 99: C++ Data Types and Data Abstractions

99

Use of Use of constconst with Member Functions with Member Functions

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)

Page 100: C++ Data Types and Data Abstractions

100

Example Using Example Using constconst with with a Member Function 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 ;

} 100

Page 101: C++ Data Types and Data Abstractions

101

Class Constructors Class Constructors

A class constructor is a member function whose purpose is to initialize the private data members of a class object

The name of a constructor is always the name of the class, and there is no return type for the constructor

A class may have several constructors with different parameter lists. A constructor with no parameters is the default constructor

A constructor is implicitly invoked when a class object is declared--if there are parameters, their values are listed in parentheses in the declaration

Page 102: C++ Data Types and Data Abstractions

102

Specification of Specification of TimeType TimeType Class Class Constructors 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 membersint hrs ; int mins ; int secs ;

} ; 102

Page 103: C++ Data Types and Data Abstractions

103

Implementation of Implementation of TimeTypeTimeType Default Default Constructor Constructor

TimeType :: TimeType ( )

// Default Constructor

// Postcondition:

// hrs == 0 && mins == 0 && secs == 0

{

hrs = 0 ;

mins = 0 ;

secs = 0 ;

}

Page 104: C++ Data Types and Data Abstractions

104

Implementation of Another Implementation of Another TimeTypeTimeType Class Constructor 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 ;

}104

Page 105: C++ Data Types and Data Abstractions

105

Automatic invocation of constructors occurs 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

0

0

0

Private data:

hrs

mins

secs

Set

Increment

Write

LessThan

Equal

19

30

0

Page 106: C++ Data Types and Data Abstractions

106

Separate Compilation and Linking of FilesSeparate Compilation and Linking of Files

timetype.h

client.cpp timetype.cpp

client.obj

client.exe

timetype.obj

Compiler Compiler

Linker

#include “timetype.h”

implementation file

specification file

main program

Page 107: C++ Data Types and Data Abstractions

107

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 uses of #include for the same header file

#ifndef Preprocessor_Identifier

#define Preprocessor_Identifier . . .

#endif

Avoiding Multiple Inclusion of Header FilesAvoiding Multiple Inclusion of Header Files

Page 108: C++ Data Types and Data Abstractions

108

Example Using Preprocessor Example Using Preprocessor Directive Directive #ifndef#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 programclass TimeType{ #include “timetype.h” #include “timetype.h”

public: . . . . . . int main ( void )

{

private: . . .

. . . }} ; #endif

Page 109: C++ Data Types and Data Abstractions

109

The EndThe End

Next Lecture

More about classes.

How to create and use them.