CPSC 427a: Object-Oriented Programming

Similar documents
CPSC 427: Object-Oriented Programming

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++

Functions and Parameter Passing

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Goals of this Lecture

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming

Procedural Programming

In this chapter, you will learn about: Pointers. Dynamic Arrays. Introduction Computer Science 1 CS 23021

CPSC 427: Object-Oriented Programming

CSE 307: Principles of Programming Languages

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

Pointers and References

CSCI 2212: Intermediate Programming / C Review, Chapters 10 and 11

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Program construction in C++ for Scientific Computing

CPSC 427: Object-Oriented Programming

Object Oriented Programming COP3330 / CGS5409

7.1 Optional Parameters

by Pearson Education, Inc. All Rights Reserved.

BITG 1113: POINTER LECTURE 12

C++ for Java Programmers

CPSC 427: Object-Oriented Programming

Pointers. 10/5/07 Pointers 1

CSE 143. Linked Lists. Linked Lists. Manipulating Nodes (1) Creating Nodes. Manipulating Nodes (3) Manipulating Nodes (2) CSE 143 1

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Procedural Programming & Fundamentals of Programming

Object-Oriented Principles and Practice / C++

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

Weeks 6&7: Procedures and Parameter Passing

Memory and C++ Pointers

Pointers and Dynamic Memory Allocation

CPSC 427: Object-Oriented Programming

CPSC 427a: Object-Oriented Programming

Introduction Of Classes ( OOPS )

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Instantiation of Template class

6.096 Introduction to C++

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

C++ For Science and Engineering Lecture 15

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

CPSC 427: Object-Oriented Programming

Chapter 9. Pointers and Dynamic Arrays

Lecture 05 POINTERS 1

A brief introduction to C programming for Java programmers

Chapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved

CPSC 427: Object-Oriented Programming

CS201- Introduction to Programming Current Quizzes

Programming for Electrical and Computer Engineers. Pointers and Arrays

Scott Gibson. Pointers & Dynamic Memory. Pre & Co Requisites. Random Access Memory. Data Types. Atomic Type Sizes

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

QUIZ. What is wrong with this code that uses default arguments?

CS201 Some Important Definitions

Chapter Overview. Pointers and Dynamic Arrays. Pointers. Pointers. Declaring Pointers. Pointers Tell Where To Find A Variable. 9.

CA31-1K DIS. Pointers. TA: You Lu

Ch. 12: Operator Overloading

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

First of all, it is a variable, just like other variables you studied

Protection Levels and Constructors The 'const' Keyword

UNIT- 3 Introduction to C++

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

References and pointers

Midterm 2. 7] Explain in your own words the concept of a handle class and how it s implemented in C++: What s wrong with this answer?

EL2310 Scientific Programming

12. Pointers Address-of operator (&)

SYSC 2006 C Winter 2012

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

C++ Programming Chapter 7 Pointers

Object Reference and Memory Allocation. Questions:

ENGINEERING 1020 Introduction to Computer Programming M A Y 2 6, R E Z A S H A H I D I

CPSC 427: Object-Oriented Programming

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

NOTE: Answer ANY FOUR of the following 6 sections:

So far, system calls have had easy syntax. Integer, character string, and structure arguments.

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.

G Programming Languages - Fall 2012

a data type is Types

Constants, References

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

From Java to C++ From Java to C++ CSE250 Lecture Notes Weeks 1 2, part of 3. Kenneth W. Regan University at Buffalo (SUNY) September 10, 2009

Object-Oriented Programming, Iouliia Skliarova

Functions, Pointers, and the Basics of C++ Classes

Pointers and Dynamic Arrays

CSCI 171 Chapter Outlines

What have we learned about when we learned about function parameters? 1-1

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

Vector and Free Store (Pointers and Memory Allocation)

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

G Programming Languages - Fall 2012

More on Functions. Lecture 7 COP 3014 Spring February 11, 2018

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records

Outline. Introduction. Pointer variables. Pointer operators. Calling functions by reference. Using const with pointers. Examples.

Programming Lecture 3

EXPRESSIONS AND ASSIGNMENT CITS1001

CSC 211 Intermediate Programming. Arrays & Pointers

Classes and Objects. Class scope: - private members are only accessible by the class methods.

Transcription:

CPSC 427a: Object-Oriented Programming Michael J. Fischer Lecture 5 September 15, 2011 CPSC 427a, Lecture 5 1/35

Functions and Methods Parameters Choosing Parameter Types The Implicit Argument Simple Variables Pointers References CPSC 427a, Lecture 5 2/35

Functions and Methods CPSC 427a, Lecture 5 3/35

Parameters Call by value Like C, C++ passes explicit parameters by value. void f( int y ) {... y=4;... };... int x=3; f(x); x and y are independent variables. y is created when f is called and destroyed when it returns. At the call, the value of x (=3) is used to initialize y. The assignment y=4; inside of f has no effect on x. CPSC 427a, Lecture 5 4/35

Parameters Call by pointer Like C, pointer values (which I call reference values) are the things that can be stored in pointer variables. Also like C, references values can be passed as arguments to functions having corresponding pointer parameters. void g( int* p ) {... (*p)=4;... };... int x=3; g(&x); p is created when g is called and destroyed when it returns. At the call, the value of &x, a reference value, is used to initialize p. The assignment (*p)=4; inside of g changes the value of x. CPSC 427a, Lecture 5 5/35

Parameters Call by reference C++ has a new kind of parameter called a reference parameter. void g( int& p ) {... p=4;... };... int x=3; g(x); This does same thing as previous example; namely, the assignment p=4 changes the value of x. Within the body of g, p is a synonym for x. For example, &p and &x are identical reference values. CPSC 427a, Lecture 5 6/35

Parameters I/O uses reference parameters The first argument to << has type ostream&. cout << x << y; is same as (cout << x) << y;. << returns a reference to its first argument, so this is also the same as cout << x; cout << y; CPSC 427a, Lecture 5 7/35

Choosing Parameter Types How should one choose the parameter type? Parameters are used for two main purposes: To send data to a function. To receive data from a function. CPSC 427a, Lecture 5 8/35

Choosing Parameter Types Sending data to a function: call by value For sending data to a function, call by value copies the data whereas call by pointer or reference copies only an address. If the data object is large, call by value is expensive of both time and space and should be avoided. If the data object is small (eg., an int or double), call by value is cheaper since it avoids the indirection of a reference. Call by value protects the caller s data from being inadvertantly changed. CPSC 427a, Lecture 5 9/35

Choosing Parameter Types Sending data to a function: call by reference or pointer Call by reference or pointer allows the caller s data to be changed. Use const to protect the caller s data from inadvertane change. Ex: int f( const int& x ) or int g( const int* xp ). Prefer call by reference to call by pointer for input parameters. Ex: f( 234 ) works but g( &234 ) does not. Reason: 234 is not a variable and hence can not be the target of a pointer. (The reason f( 234 ) does work is a bit subtle and will be explained later.) CPSC 427a, Lecture 5 10/35

Choosing Parameter Types Receiving data from a function An output parameter is expected to be changed by the function. Both call by reference and call by pointer work. Call by reference is generally preferred since it avoids the need for the caller to place an ampersand in front of the output variable. Declaration: int f( int& x ) or int g( int* xp ). Call: f( result ) or g( &result ). CPSC 427a, Lecture 5 11/35

The Implicit Argument The implicit argument Every call to a class member function has an implicit argument, which is the object written before the dot in the function call. class MyExample { private: int count; // data member public: void advance(int n) { count += n; }... };... MyExample ex; ex.advance(3); Increments ex.count by 3. CPSC 427a, Lecture 5 12/35

The Implicit Argument this The implicit argument is passed by pointer. In the call ex.advance(3), the implicit argument is ex, and a pointer to ex is passed to advance(). The implicit argument can be referenced directly from within a member function using the keyword this. Within the definition of advance(), count and this->count are synonymous. CPSC 427a, Lecture 5 13/35

Simple variables CPSC 427a, Lecture 5 14/35

L-values and R-values Programming language designers have long been bothered by the asymmetry of assignment. x = 3 is a legal assignment statement. 3 = x is not legal. Expressions are treated differently depending on whether they appear on the left or right sides of an assignment statement. Something that can appear on the left is called an L-value. Something that can appear on the right is called an R-value. Intuitively, an L-value is the address of a storage location some place where a value can be stored. An R-value is a thing that can be placed in a storage location. R-values are sometimes called pure data values. CPSC 427a, Lecture 5 15/35

Simple variable declaration The declaration int x = 3; says several things: 1. All values that can be stored in x have type int. 2. The name x is bound (when the code is executed) to a storage location adequate to store an int. 3. The int value 3 is initially placed in x s storage location. The L-value of x is the address of the storage location of x. The R-value of x is the object of type int that is stored in x. CPSC 427a, Lecture 5 16/35

Simple assignment The assignment statement x = 3; means the following: 1. Get an L-value from the left hand side (x). 2. Get an R-value from the right hand side (3). 3. Put the R value from step 2 into the storage location whose address was obtained from step 1. CPSC 427a, Lecture 5 17/35

Automatic dereferencing Given int x = 3; int y = 4; Consider x = y; This is processed as before, except what does it mean to get an R-value from y? Whenever an L-value is presented and an R-value is needed, automatic deferencing occurs. This means to go the storage location specified by the presented L-value (y) and get its R-value (4). Then the assignment takes place as before. CPSC 427a, Lecture 5 18/35

Pointers CPSC 427a, Lecture 5 19/35

Pointer values A pointer [reference value] is a primitive object with an associated L-value. The pointer itself is an R-value. The type of a pointer is the type of the value that can be stored at the associated L-value, followed by * Example: If y is a simple integer variable, then the type of a pointer to y is int*. We say the pointer references y. CPSC 427a, Lecture 5 20/35

Pointer creation Pointers are created by applying the unary operator & to an L-value. Example: If y has type int, then the expression &y is a pointer of type int* that references y. More generally, if x has type T, then the expression &x yields a pointer (R-value) of type T* that references x. CPSC 427a, Lecture 5 21/35

Pointer variables Variables into which pointers can be stored are called (not surprisingly) pointer variables. A pointer variable is no different from any other variable except for the types of values that can be stored in it. int* q declares q to be a variable into which pointers of type int* can be stored. If x is an integer variable, then the assignment q = &x creates a pointer to x and stores it in q. Just as we often conflate integer and integer variable, it is easy to confuse pointer with pointer variable. CPSC 427a, Lecture 5 22/35

Pointer assignment Pointers can be assigned to pointer variables. If p and q are pointer variables of the same type, then p = q; is an assignment statement. It has the same interpretation as any other assignment, i.e., fetch the (pointer) value from q and store it in p. Example: If q = &x as before, then after p = q, p contains a copy of the pointer stored in q. Both of these pointers reference the address of x. Note that the L-value q is dereferenced to an R-value, which is then placed in p. Dereferencing does not follow the pointer. CPSC 427a, Lecture 5 23/35

Following a pointer To follow a pointer means to obtain the L-value it encapsulates. The basic operator for following a pointer is unary *. * is the inverse of &. It takes a pointer and returns its corresponding L-value. If E is a pointer expression, then *E is the L-value encapsulated by the pointer that results from evaluating E. If E has type T*, then the values stored in *E have type T. We say that E points to *E. CPSC 427a, Lecture 5 24/35

Pointer example int x = 3; int y = 4; int* p; int* q; int* r; p = &x; // p points to x. *p = 5; // Now x==5. q = p; // p and q both point to x. *q = *p + 1; // Now x==6. Common mistake dangling pointer *r = x+y; // What s wrong here? CPSC 427a, Lecture 5 25/35

Pointer declaration syntax A word of warning int x, y; is shorthand for int x; int y; but int* p, q; is not same as int* p, int* q. Rather, it means int* p; int q;. For this reason, many authors put the * next to the variable instead of with the type name. Spacing around the star doesn t matter, but logically it belongs with the type. CPSC 427a, Lecture 5 26/35

References CPSC 427a, Lecture 5 27/35

Reference types Recall: Given int x, two types are associated with x: an L-value (the reference to x) and an R-value (the type of its values). C++ exposes this distinction through reference types and declarators. A reference type is any type T followed by &, i.e., T&. A reference type is the internal type of an L-value. Example: Given int x, the name x is bound to an L-value of type int&, whereas the values stored in x have type int This generalizes to arbitrary types T: If an L-value stores values of type T, then the type of the L-value is T&. CPSC 427a, Lecture 5 28/35

Reference declarators The syntax T& can be used to declare names, but its meaning is not what one might expect. int x = 3; // Ordinary int variable int& y = x; // y is an alias for x y = 4; // Now x == 4. The declaration must include an initializer. The meaning of int& y = x; is that y becomes a name for the L-value x. Since x is simply the name of an L-value, the effect is to make y an alias for x. For this to work, the L-value type (int&) of x must match the type declarator (int&) for y, as above. CPSC 427a, Lecture 5 29/35

Use of named references Named references can be used just like any other variable. One application is to give names to otherwise unnamed storage locations. int axis[101]; // values along a graph axis int& first = axis[0] ; // give name to first element int& last = axis[100]; // give name to last element first = -50; last = 50; // use p to scan through the array int* p; for (p=&first; p!=&last; p++) {...} CPSC 427a, Lecture 5 30/35

Reference parameters References are mainly useful for function parameters and return values. When used to declare a function parameter, they provide call-by-reference semantics. int f( int& x ){...} Within the body of f, x is an alias for the actual parameter, which must be the L-value of an int location. CPSC 427a, Lecture 5 31/35

Reference return values Functions can also return references. int& g( bool flag, int& x, int& y ) { if (flag) return x; return y; }... g(x<y, x, y) = x + y; This code returns a reference to the smaller of x and y and then sets that variable to their sum. CPSC 427a, Lecture 5 32/35

Custom subscripting Suppose you would like to use 1-based arrays instead of C++ s 0-based arrays. We can define our own subscript function so that sub(a, k) returns the L-value of array element a[k-1]. sub(a,k) can be used on either the left or right side of an assignment statement, just like the built-in subscript operator. int& sub(int a[], int k) { return a[k-1]; }... int mytab[20]; for (k=1; k<=20; k++) sub(mytab, k) = k; CPSC 427a, Lecture 5 33/35

Constant references Constant reference types allow the naming of pure R-values. const double& pi = 3.1415926535897932384626433832795; Actually, this is little different from const double pi = 3.1415926535897932384626433832795; In both cases, the pure R-value is placed in a read-only variable, and pi is bound to its L-value. CPSC 427a, Lecture 5 34/35

Comparison of reference and pointer A reference (L-value) is the result of following a pointer. A pointer is only followed when explicitly requested (by * or ->). A reference name is bound when it is created. Pointer variables can be initialized at any time (unless declared to be read-only using const). Once a reference is bound to an object, it cannot be changed to refer to another object. Pointer variables can be changed to point to another object at any time using assignment (unless declared to be read-only). You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage. CPSC 427a, Lecture 5 35/35