39
2003 Prentice Hall, Inc. All rights reserved. 1 Pointers in C++; Section 3.5; Chapter 5 Concept of pointers absent in Java Pointer holds a memory address. & -- address of varible –* -- dereference (what is being pointed to?) -> -- dereferencing (member elements of object being pointed to)

2003 Prentice Hall, Inc. All rights reserved. 1 Pointers in C++; Section 3.5; Chapter 5 Concept of pointers absent in Java Pointer holds a memory address

  • View
    212

  • Download
    0

Embed Size (px)

Citation preview

2003 Prentice Hall, Inc. All rights reserved.

1

Pointers in C++; Section 3.5; Chapter 5

• Concept of pointers absent in Java• Pointer holds a memory address.

– & -- address of varible– * -- dereference (what is being pointed to?)– -> -- dereferencing (member elements of object being

pointed to)

2003 Prentice Hall, Inc. All rights reserved.

2

Pointer Example

# include <iostream.h>int main(){ int x = 10; int* y; //declare as pointer to an integer y = &x; //have y point to x, by setting it to address of x; x += 3;

cout<<"The value of x is: "<<x<<endl; cout<<"The value of y is: "<<(unsigned int) y<<endl; cout<<"The content of y is: "<< *y <<endl; cout<<"The address of y is: "<<(unsigned int) &y<<endl;}

2003 Prentice Hall, Inc. All rights reserved.

3

Pointer Example contd

//modify contents of the pointer *y = 50;

cout<<"The value of x is: "<<x<<endl; cout<<"The value of y is: "<<(unsigned int)

y<<endl; cout<<"The content of y is: "<< *y <<endl; cout<<"The address of y is: "<<

(unsigned int)&y<<endl;

2003 Prentice Hall, Inc. All rights reserved.

4

Pointer Example ctd //dynamic memory allocation y = new int(30); cout<<"The value of x is: "<<x<<endl;cout<<"The value of y is: "<<

(unsigned int) y<<endl;cout<<"The content of y is: "<< *y <<endl;cout<<"The address of y is: "<<

(unsigned int) &y<<endl; //free up memorydelete y;

2003 Prentice Hall, Inc. All rights reserved.

5

Memory Allocation

• Each variable requires some amount of memory• Setting aside that memory for the variable is

allocation• Declaring a non-pointer variable allocates the

memory automatically.• Declaring a pointer does not allocate memory for

the object pointed to!

2003 Prentice Hall, Inc. All rights reserved.

6

Memory Allocation

• Example:

int a; // memory allocatedchar c; // memory allocatedchar c[10]; // memory allocatedchar *f; // memory NOT allocatedstudent *s; // memory NOT allocated

2003 Prentice Hall, Inc. All rights reserved.

7

Dynamic Memory Allocation

• Static: always the same during runtime– basic variables, arrays of known size

• Dynamic: changes during runtime– amount of memory allocated for an array whose size

depends on user input

– only allocating memory in certain situations (within a conditional statement)

– allocating a number of objects that isn’t known in advance (queue, linked list, etc)

2003 Prentice Hall, Inc. All rights reserved.

8

Dynamic Memory Allocation in C++

• uses new and delete– much more intuitive:

variable = new type;– new returns a pointer to the new object (variable must be a

pointer)

– When you wish to deallocate memory:delete variable;

2003 Prentice Hall, Inc. All rights reserved.

9

Dynamic Memory Allocation in C++

queue *q;

q = new queue;q->addItem(5);q->addItem(8);int i = q->getItem();

delete q;

course *c;

c = new course;c->setID(322);

delete c;

2003 Prentice Hall, Inc. All rights reserved.

Allocating memory using new

Point *p = new Point(5, 5);

• new can be thought of a function with slightly strange syntax

• new allocates space to hold the object.• new calls the object’s constructor.• new returns a pointer to that object.

2003 Prentice Hall, Inc. All rights reserved.

11

WHY POINTERS?

• Pointers are one of the most powerful features of the C++ language.

• Pointers are used to...– manage arrays

– safely pass variable addresses to functions

– provide functions access to strings and arrays

– dynamically allocate memory

– manipulate large collections of data elements

2003 Prentice Hall, Inc. All rights reserved.

What is a pointer?

int x = 10;int *p;

p = &x;

p gets the address of x in memory.

p

x10

2003 Prentice Hall, Inc. All rights reserved.

What is a pointer?

int x = 10;int *p;

p = &x;

*p = 20;

*p is the value at the address p.

p

x20

2003 Prentice Hall, Inc. All rights reserved.

What is a pointer?

int x = 10;int *p;

p = &x;

*p = 20;

Declares a pointer to an integer

& is address operator gets address of x

* dereference operator gets value at p

2003 Prentice Hall, Inc. All rights reserved.

15

Bubble Sort Using Pass-by-Reference(Pointer)

• Implement bubbleSort using pointers– Want function swap to access array elements

• Individual array elements: scalars

– Passed by value by default

• Pass by reference using address operator &

2003 Prentice Hall, Inc.All rights reserved.

Outline16

fig05_15.cpp(1 of 3)

1 // Fig. 5.15: fig05_15.cpp2 // This program puts values into an array, sorts the values into3 // ascending order, and prints the resulting array.4 #include <iostream>5 6 using std::cout;7 using std::endl;8 9 #include <iomanip>10 11 using std::setw;12 13 void bubbleSort( int *, const int ); // prototype14 void swap( int * const, int * const ); // prototype15 16 int main()17 {18 const int arraySize = 10;19 int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };20 21 cout << "Data items in original order\n";22 23 for ( int i = 0; i < arraySize; i++ )24 cout << setw( 4 ) << a[ i ];25

2003 Prentice Hall, Inc.All rights reserved.

Outline17

fig05_15.cpp(2 of 3)

26 bubbleSort( a, arraySize ); // sort the array27 28 cout << "\nData items in ascending order\n";29 30 for ( int j = 0; j < arraySize; j++ )31 cout << setw( 4 ) << a[ j ];32 33 cout << endl;34 35 return 0; // indicates successful termination36 37 } // end main38 39 // sort an array of integers using bubble sort algorithm40 void bubbleSort( int *array, const int size )41 {42 // loop to control passes43 for ( int pass = 0; pass < size - 1; pass++ )44 45 // loop to control comparisons during each pass46 for ( int k = 0; k < size - 1; k++ )47 48 // swap adjacent elements if they are out of order49 if ( array[ k ] > array[ k + 1 ] )50 swap( &array[ k ], &array[ k + 1 ] );

Declare as int *array (rather than int array[]) to indicate function bubbleSort receives single-subscripted array.

Receives size of array as argument; declared const to ensure size not modified.

2003 Prentice Hall, Inc.All rights reserved.

Outline18

fig05_15.cpp(3 of 3)

fig05_15.cppoutput (1 of 1)

51 52 } // end function bubbleSort53 54 // swap values at memory locations to which 55 // element1Ptr and element2Ptr point 56 void swap( int * const element1Ptr, int * const element2Ptr )57 { 58 int hold = *element1Ptr; 59 *element1Ptr = *element2Ptr; 60 *element2Ptr = hold; 61 62 } // end function swap

Data items in original order

2 6 4 8 10 12 89 68 45 37

Data items in ascending order

2 4 6 8 10 12 37 45 68 89

Pass arguments by reference, allowing function to swap values at memory locations.

2003 Prentice Hall, Inc. All rights reserved.

19

Encapsulation Encapsulation Section 4.1

• Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse•Typically, the public parts of an object are used to provide a controlled interface to the private parts of the object

2003 Prentice Hall, Inc. All rights reserved.

20

PolymorphismPolymorphism Section 4.2; Chapter 10

• Polymorphism is the quality that allows one name to be used for two or more related but technically different purposes

• C++ supports polymorphism through function overloading (same function name, different parameters)

         

2003 Prentice Hall, Inc. All rights reserved.

21

 Inheritance Inheritance Section 4.3; Chapter 9

• Inheritance is the process by which one object can acquire the properties of another

• Inheritance allows a hierarchy of classes to be built, moving from the general to the most specific

2003 Prentice Hall, Inc. All rights reserved.

22

Encapsulation Section 4.1

• Data abstraction allow programmers to hide data representation details behind a (comparatively) simple set of operations (an interface)

• What the benefits of data abstraction?– Reduces conceptual load

• Programmers need to knows less about the rest of the program

– Provides fault containment• Bugs are located in independent components

– Provides a significant degree of independence of program components

• Separate the roles of different programmer

Software Software EngineeringEngineering

GoalsGoals

2003 Prentice Hall, Inc. All rights reserved.

23

EncapsulationClasses, Objects and Methods

• The unit of encapsulation in an O-O PL is a class– An abstract data type

• The set of values is the set of objects (or instances)

• Objects can have a– Set of instance attributes (has-a relationship)

– Set of instance methods

• Classes can have a– Set of class attributes

– Set of class methods

Method calls are Method calls are known as known as messagesmessages

• The entire set of methods of an object is known as the message protocol or the message interface of the object

2003 Prentice Hall, Inc. All rights reserved.

24

Polymorphism Section 4.2; Chapter 10

• Polymorphism– “Program in the general”

– Treat objects in same class hierarchy as if all base class

– Virtual functions and dynamic binding• Will explain how polymorphism works

– Makes programs extensible• New classes added easily, can still be processed

• In our examples– Use abstract base class Shape

• Defines common interface (functionality)• Point, Circle and Cylinder inherit from Shape

– Class Employee for a natural example

2003 Prentice Hall, Inc. All rights reserved.

25

Relationships Among Objects in an Inheritance Hierarchy

– Derived-class object can be treated as base-class object• “is-a” relationship

• Base class is not a derived class object

2003 Prentice Hall, Inc. All rights reserved.

26

Invoking Base-Class Functions from Derived-Class Objects

• Aim pointers (base, derived) at objects (base, derived)– Base pointer aimed at base object

– Derived pointer aimed at derived object• Both straightforward

– Base pointer aimed at derived object• “is a” relationship

– Circle “is a” Point• Will invoke base class functions

– Function call depends on the class of the pointer/handle• Does not depend on object to which it points

• With virtual functions, this can be changed (more later)

2003 Prentice Hall, Inc. All rights reserved.

27

Inheritance Section 4.3; Chapter 9

• Inheritance– Software reusability

– Create new class from existing class• Absorb existing class’s data and behaviors

• Enhance with new capabilities

– Derived class inherits from base class• Derived class

– More specialized group of objects

– Behaviors inherited from base class

• Can customize

– Additional behaviors

2003 Prentice Hall, Inc. All rights reserved.

28

Inheritance

• Class hierarchy– Direct base class

• Inherited explicitly (one level up hierarchy)

– Indirect base class• Inherited two or more levels up hierarchy

– Single inheritance• Inherits from one base class

– Multiple inheritance• Inherits from multiple base classes

– Base classes possibly unrelated

• Chapter 22

2003 Prentice Hall, Inc. All rights reserved.

29

Inheritance

• Three types of inheritance– public

• Every object of derived class also object of base class– Base-class objects not objects of derived classes– Example: All cars vehicles, but not all vehicles cars

• Can access non-private members of base class– Derived class can effect change to private base-class

members• Through inherited non-private member functions

– private• Alternative to composition• Chapter 17

– protected • Rarely used

2003 Prentice Hall, Inc. All rights reserved.

30

Inheritance

• Abstraction– Focus on commonalities among objects in system

• “is-a” vs. “has-a”– “is-a”

• Inheritance

• Derived class object treated as base class object

• Example: Car is a vehicle

– Vehicle properties/behaviors also car properties/behaviors

– “has-a”• Composition

• Object contains one or more objects of other classes as members

• Example: Car has a steering wheel

2003 Prentice Hall, Inc. All rights reserved.

31

Introduction File I/O Section 4.4; Chapter 12

• Overview common I/O features• C++ I/O

– Object oriented• References, function overloading, operator overloading

– Type safe• I/O sensitive to data type

• Error if types do not match

– User-defined and standard types• Makes C++ extensible

2003 Prentice Hall, Inc. All rights reserved.

32

Streams

• Stream: sequence of bytes– Input: from device (keyboard, disk drive) to memory

– Output: from memory to device (monitor, printer, etc.)

• I/O operations often bottleneck– Wait for disk drive/keyboard input

– Low-level I/O• Unformatted (not convenient for people)

• Byte-by-byte transfer

• High-speed, high-volume transfers

– High-level I/O• Formatted

• Bytes grouped (into integers, characters, strings, etc.)

• Good for most I/O needs

2003 Prentice Hall, Inc. All rights reserved.

33

Classic Streams vs. Standard Streams

• Classic streams– Input/output chars (one byte)

– Limited number of characters (ASCII)

• Standard stream libraries– Some languages need special alphabets

– Unicode character set supports this• wchar_t character type

– Can do I/O with Unicode characters

2003 Prentice Hall, Inc. All rights reserved.

34

iostream Library Header Files

• iostream library– Has header files with hundreds of I/O capabilities– <iostream.h>

• Standard input (cin)

• Standard output (cout)

• Unbuffered error (cerr)

• Buffered error (clog)

– <iomanip.h>• Formatted I/O with parameterized stream manipulators

– <fstream.h>• File processing operations

2003 Prentice Hall, Inc. All rights reserved.

35

Stream Output

• Output– Use ostream– Formatted and unformatted

– Standard data types (<<)

– Characters (put function)

– Integers (decimal, octal, hexadecimal)

– Floating point numbers• Various precision, forced decimal points, scientific notation

– Justified, padded data

– Uppercase/lowercase control

2003 Prentice Hall, Inc. All rights reserved.

36

Output of char * Variables

• C++ determines data type automatically– Generally an improvement (over C)

– Try to print value of a char *• Memory address of first character

• Problem– << overloaded to print null-terminated string

– Solution: cast to void *• Use whenever printing value of a pointer

• Prints as a hex (base 16) number

2003 Prentice Hall, Inc. All rights reserved.

37

Character Output using Member Function put

• put function– Outputs characters

• cout.put( 'A' );

– May be cascaded• cout.put( 'A' ).put( '\n' );• Dot operator (.) evaluates left-to-right

– Can use numerical (ASCII) value• cout.put( 65 );

• Prints 'A'

2003 Prentice Hall, Inc. All rights reserved.

38

Stream Input

• Formatted and unformatted input– istream

• >> operator– Normally skips whitespace (blanks, tabs, newlines)

• Can change this

– Returns 0 when EOF encountered• Otherwise, returns reference to object• cin >> grade

– State bits set if errors occur• Discussed in 12.7 and 12.8

2003 Prentice Hall, Inc. All rights reserved.

39

get and getline Member Functions

• get function– cin.get()– Returns one character from stream (even whitespace)

• Returns EOF if end-of-file encountered

• End-of-file– Indicates end of input

• ctrl-z on IBM-PCs

• ctrl-d on UNIX and Macs

– cin.eof()• Returns 1 (true) if EOF has occurred