390 likes | 485 Views
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). Pointer Example. # include <iostream.h>
E N D
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)
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; }
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;
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 memory delete y;
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!
Memory Allocation • Example:int a; // memory allocatedchar c; // memory allocatedchar c[10]; // memory allocatedchar *f; // memory NOT allocatedstudent *s; // memory NOT allocated
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)
Dynamic Memory Allocation in C++ • uses new and delete • much more intuitive:variable= newtype; • new returns a pointer to the new object (variable must be a pointer) • When you wish to deallocate memory:deletevariable;
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;
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.
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
What is a pointer? int x = 10; int *p; p = &x; p gets the address of x in memory. p 10 x
What is a pointer? int x = 10; int *p; p = &x; *p = 20; *p is the value at the address p. p 20 x
What is a pointer? Declares a pointer to an integer int x = 10; int *p; p = &x; *p = 20; & is address operator gets address of x *dereference operator gets value at p
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 &
1 // Fig. 5.15: fig05_15.cpp 2 // This program puts values into an array, sorts the values into 3 // 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 *, constint ); // prototype 14 void swap( int * const, int * const ); // prototype 15 16 int main() 17 { 18 const intarraySize = 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 fig05_15.cpp(1 of 3)
26 bubbleSort( a, arraySize ); // sort the array 27 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 return0; // indicates successful termination 36 37 } // end main 38 39 // sort an array of integers using bubble sort algorithm 40 void bubbleSort( int *array, const int size ) 41 { 42 // loop to control passes 43 for ( int pass = 0; pass < size - 1; pass++ ) 44 45 // loop to control comparisons during each pass 46 for ( int k = 0; k < size - 1; k++ ) 47 48 // swap adjacent elements if they are out of order 49 if ( array[ k ] > array[ k + 1 ] ) 50 swap( &array[ k ], &array[ k + 1 ] ); Receives size of array as argument; declared const to ensure size not modified. Declare as int *array (rather than int array[]) to indicate function bubbleSort receives single-subscripted array. fig05_15.cpp(2 of 3)
51 52 } // end function bubbleSort 53 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 Pass arguments by reference, allowing function to swap values at memory locations. fig05_15.cpp(3 of 3)fig05_15.cppoutput (1 of 1) 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
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
PolymorphismSection 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)
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
Software Engineering Goals 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
Method calls are known as messages 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 instanceattributes (has-a relationship) • Set of instancemethods • Classes can have a • Set of class attributes • Set of class methods • The entire set of methods of an object is known as the message protocol or the message interface of the object
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
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
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)
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
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
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
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
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
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
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
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
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
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
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'
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
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