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

Slides:



Advertisements
Similar presentations
Pointers and Strings. Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close relationship with arrays and strings.
Advertisements

 2006 Pearson Education, Inc. All rights reserved Operator Overloading.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
 2006 Pearson Education, Inc. All rights reserved Stream Input/Output.
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
Input/Output Main Memory istream ostream Disk Drive Keyboard Scanner Disk Drive Monitor Printer stream = sequence of bytes.
 2003 Prentice Hall, Inc. All rights reserved. 1 Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
計算機概論實習 Stream Stream: sequence of bytes Input: from device (keyboard, disk drive) to memory Output: from memory to device (monitor, printer,
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 3 Arrays & Pointers.
C++ fundamentals.
Operator Overloading in C++
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
Chapter 12: Adding Functionality to Your Classes.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Stream Handling Streams - means flow of data to and from program variables. - We declare the variables in our C++ for holding data temporarily in the memory.
Pointer Data Type and Pointer Variables
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream.
You gotta be cool. Stream Stream Output Stream Input Unformatted I/O with read, gcount and write Stream Manipulators Stream Format States Stream Error.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Overloading Binary Operators Two ways to overload –As a member function of a class –As a friend function As member functions –General syntax Data Structures.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Inheritance. Lecture contents Inheritance Class hierarchy Types of Inheritance Derived and Base classes derived class constructors protected access identifier.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
 2008 Pearson Education, Inc. All rights reserved Operator Overloading.
 2000 Deitel & Associates, Inc. All rights reserved Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close.
Lecture Contents I/O Streams. –Input/output streams. –Unformatted vs formatted streams. –Stream manipulators. –Stream error state. –Stream tying. –Examples.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Inheritance Outline 9.1Introduction 9.2Inheritance: Base Classes and Derived Classes 9.3.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 21 - C++ Stream Input/Output Basics Outline 21.1Introduction 21.2Streams Iostream Library.
1 Today’s Objectives  Announcements Turn in Homework 4 Quiz 4 will be on Wednesday, July 19 – It will have questions about inheritance, polymorphism,
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 25 December 1, 2009.
 2003 Prentice Hall, Inc. All rights reserved. 1 Pointers and Strings Outline Introduction Pointer Variable Declarations and Initialization Pointer Operators.
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
 2003 Prentice Hall, Inc. All rights reserved. 1 namespaces Program has identifiers in different scopes –Sometimes scopes overlap, lead to problems Namespace.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
 2003 Prentice Hall, Inc. All rights reserved. 5.11Function Pointers Pointers to functions –Contain address of function –Similar to how array name is.
1 COMS 261 Computer Science I Title: Functions Date: October 24, 2005 Lecture Number: 22.
 2003 Prentice Hall, Inc. All rights reserved. 1 Lecture 5: Pointer Outline Chapter 5 Pointer continue Call by reference Pointer arithmatic Debugging.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Object-Oriented Programming: Inheritance Outline 9.1 Introduction 9.2 Base Classes and Derived.
Object-Oriented Programming (OOP) and C++
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
C++ Programming Lecture 18 Pointers – Part II The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Introduction Every program takes some data as input and generate processed data as out put . It is important to know how to provide the input data and.
Examples (D. Schmidt et al)
Introduction to C++ (Extensions to C)
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Chapter 21 - C++ Stream Input/Output
Chapter 2 part #3 C++ Input / Output
Chapter 3: Input/Output
Introduction to Data Structure
Arrays Arrays A few types Structures of related data items
Capitolo 1 – Introduction C++ Programming
Chapter 2 part #3 C++ Input / Output
C++ Programming Lecture 18 Pointers – Part II
Lecture 2 Arrays & Pointers September 7, 2004
CISC181 Introduction to Computer Science Dr
Input/Output Streams, Part 1
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

 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 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 memory delete 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 allocated char c;// memory allocated char c[10];// memory allocated char *f;// memory NOT allocated student *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 W HY P OINTERS ? 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. Outline 16 fig05_15.cpp (1 of 3) 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 5 6 using std::cout; 7 using std::endl; 8 9 #include using std::setw; void bubbleSort( int *, const int ); // prototype 14 void swap( int * const, int * const ); // prototype int main() 17 { 18 const int arraySize = 10; 19 int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; cout << "Data items in original order\n"; for ( int i = 0; i < arraySize; i++ ) 24 cout << setw( 4 ) << a[ i ]; 25

 2003 Prentice Hall, Inc. All rights reserved. Outline 17 fig05_15.cpp (2 of 3) 26 bubbleSort( a, arraySize ); // sort the array cout << "\nData items in ascending order\n"; for ( int j = 0; j < arraySize; j++ ) 31 cout << setw( 4 ) << a[ j ]; cout << endl; return 0; // indicates successful termination } // end main // 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++ ) // loop to control comparisons during each pass 46 for ( int k = 0; k < size - 1; k++ ) // swap adjacent elements if they are out of order 49 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. Outline 18 fig05_15.cpp (3 of 3) fig05_15.cpp output (1 of 1) } // end function bubbleSort // 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; } // end function swap Data items in original order Data items in ascending order 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 Polymorphism Polymorphism 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 SoftwareEngineeringGoals

 2003 Prentice Hall, Inc. All rights reserved. 23 Encapsulation Classes, 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 known as messages 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 char s (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 – Standard input ( cin ) Standard output ( cout ) Unbuffered error ( cerr ) Buffered error ( clog ) – Formatted I/O with parameterized stream manipulators – 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