SPL/2010 Pointers and Parameter Passing in C++ 1.

Slides:



Advertisements
Similar presentations
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
Advertisements

This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Various languages….  Could affect performance  Could affect reliability  Could affect language choice.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Dynamic Memory Allocation in C++. Memory Segments in C++ Memory is divided in certain segments – Code Segment Stores application code – Data Segment Holds.
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
Pointers “Absolute C++” Section 10.1
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
Review of C++ Programming Part II Sheng-Fang Huang.
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract 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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
CSE 333 – SECTION 4. Overview Pointers vs. references Const Classes, constructors, new, delete, etc. More operator overloading.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
SPL – Practical Session 2 Topics: – C++ Memory Management – Pointers.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
Object-Oriented Programming in C++
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Sadegh Aliakbary Sharif University of Technology Spring 2011.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
Peyman Dodangeh Sharif University of Technology Spring 2014.
Pointers1 WHAT IS A POINTER? Simply stated, a pointer is an address. A running program consists of three parts: execution stack, code, and data. They are.
CS-1030 Dr. Mark L. Hornick 1 References & Pointers.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Pointers in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
Recap Resizing the Vector Push_back function Parameters passing Mechanism Primitive Arrays of Constants Multidimensional Arrays The Standard Library string.
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
Object Lifetime and Pointers
Pointers and Dynamic Arrays
Chapter 7: User-Defined Functions II
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Java Primer 1: Types, Classes and Operators
Pointers and references
Advanced Programming Behnam Hatami Fall 2017.
Pointers and References
Object Oriented Programming COP3330 / CGS5409
Built-In (a.k.a. Native) Types in C++
Pointers and References
Java Programming Language
Pointers and References
Pointers and references
SPL – PS3 C++ Classes.
SPL – PS2 C++ Memory Handling.
Presentation transcript:

SPL/2010 Pointers and Parameter Passing in C++ 1

SPL/2010 In Java ● Primitive types (byte, short, int…) ● allocated on the stack ● Objects ● allocated on the heap 2

SPL/2010 Parameter passing in Java ● Myth: “Objects are passed by reference, primitives are passed by value” ● Truth #1: Everything in Java is passed by value. (Objects, are never passed at all) ● Truth #2: The values of variables are always primitives or references, never objects 3

SPL/2010 ● Pass-by-value ● actual parameter is fully evaluated and the resulting value is copied into a location being used to hold the formal parameter's value during method/function execution. ● location is typically a chunk of memory on the runtime stack for the application 4

SPL/2010 ● Pass-by-reference ● formal parameter merely acts as an alias for the actual parameter. ● anytime the method/function uses the formal parameter (for reading or writing), it is actually using the actual parameter 5

SPL/2010 public void foo(Dog d) { d = new Dog("Fifi"); // creating the "Fifi" dog } Dog aDog = new Dog("Max"); // creating the "Max" dog // at this point, aDog points to the "Max" dog foo(aDog); // aDog still points to the "Max" dog 6

SPL/2010 foo(d); ● passes the value of d to foo; it does not pass the object that d points to! ● The value of the pointer being passed is similar to a memory address. ● The value uniquely identifies some object on the heap. 7

SPL/2010 passing a reference by value Object x = null; giveMeAString (x); System.out.println (x); void giveMeAString (Object y) { y = "This is a string"; } 8

SPL/2010 passing a reference by value int x = 0; giveMeATen (x); System.out.println (x); void giveMeATen (int y) { y = 10; } 9

SPL/2010 ● The primitive value of a parameter is set to the value of another parameter ● the value "0" was passed into the method giveMeTen, not the variable itself. ● same is true of reference variables - value of reference is passed in, not the variable itself 10

SPL/2010 Dog myDog = new Dog("Rover"); foo(myDog); Suppose the Dog object resides at memory address 42. This means we pass 42 to foo(). public void foo(Dog someDog) { someDog.setName("Max"); // AAA someDog = new Dog("Fifi"); // BBB someDog.setName("Rowlf"); // CCC } 11

SPL/2010 In C++ ● both primitives and objects may be allocated on stack or heap. ● anything allocated on the heap can be reached by using a reference to its location ● reference = pointer - holds a memory address 12

SPL/2010 Pointers ● pointers are primitive types themselves ● hold memory address of a primitive or an object which resides either on the heap or on the stack ● pointer to type type_a is of type type_a * ● type_a * is a primitive type ● we can have a pointer to any type ● pointer to a pointer to type_a: type_a **. 13

SPL/

SPL/2010 Code analysis 1. space for primitive of type int* allocated on activation frame of main function 2. space allocated is associated with variable i_ptr 3. space for primitive of type int is allocated on heap (using new), initialized to address of newly allocated integer is saved in i_ptr. 5. operator << is passed content (by value) i_ptr points to. 15

SPL/2010 Operator * ● operator *: whose value is the content of the memory to which the pointer points 16

SPL/2010 Process memory 17

SPL/

SPL/2010 Access through pointers ● member methods of class T are executed always as T *- instance location in memory ● method of an object does not change the object's internal state, method is const ● operator -> access members and methods via pointer to object ● access members / methods of an object not through pointer using (.) dot-operator 19

SPL/2010 instantiate some cows 20

SPL/2010 Analysis - bety ● space for Cow is allocated on activation frame of main function. ● constructor of Cow is called with ● this points to the address of the space allocated on the stack. ● space allocated is associated with variable bety 21

SPL/2010 Analysis - ula ● space for a pointer Cow * is allocated on the activation frame of the main function. ● space allocated is associated with the variable ula. ● space for a Cow is allocated on the heap (using new operator) ● constructor is called with ● this points to the address of the space allocated on the heap. ● address of allocated Cow is saved in ula. 22

SPL/2010 Process memory 23

SPL/2010 Dereferencing /"Address Of” ● dereference a pointer (* operator): ● (*ula).moooo(); ● take the address of something (& operator): ● int i = 10; ● int *i_ptr = &i; ● i_ptr holds the address in which i is stored on the stack 24

SPL/2010 pass pointer arguments to functions 25

SPL/2010 Reference ● is basically a const pointer without using any pointer notations. ● may only be assigned once, when it is declared (initialization of reference) ● may not be altered to reference something else later. 26

SPL/

SPL/2010 const pointers ● Any type in C++ can be marked as const, which means that its value cannot be changed ● const pointer is declared by adding the const keyword after the type ● int *const i_ptr: a const pointer to an int ● cannot have references to references (this is explicitly illegal) 28

SPL/2010 Parameter Passing ● all parameters are either 'in‘ or 'out' ● 'in' parameters - information passed to the function, which the function does not change. ● operation on 'in' parameter - not visible outside ● 'out' parameters are a side-channel for function to return information, in addition to return value. ● changes made to 'out' parameters are visible outside the scope of the function. 29

SPL/2010 Parameter Passing - Java ● 2 forms of passing parameters to methods, ● primitives are passed by value ● objects by reference (possible 'out' parameters). 30

SPL/2010 Parameter Passing – C++ ● 3 forms for parameter passing ● By value, for 'in' parameters. ● By pointer, for 'out' parameters. ● By reference, for 'out' parameters. 31

SPL/2010 By Value ● outputs = 20 32

SPL/2010 By Value ● call byVal - both 30 and the entire content of hemda are copied ● placed on the activation frame of byVal ● byVal performs all of its operations on these local copies - no changes to hemda 33

SPL/2010 By Pointer ● output =30 34

SPL/2010 By Pointer ● byPointer received a pointer to location of hemda on activation frame of calling function ● changed its id 35

SPL/2010 By Reference ● output =30 36

SPL/2010 By Reference ● refrain from using pointers ● inherently unsafe - easily cast to other types ● compiler is allowed to optimize the reference beyond the "const pointer" abstraction 37

SPL/2010 When to Use Each Form of Parameter Passing? ● passing parameters by value comes with a cost - copying and constructing a new object ● change a parameter outside the scope of the local function: by-reference or by-pointer 38

SPL/2010 Recommendations ● For a function that uses passed data without modifying it (In parameter): ● If data object is small (built-in data type or a small structure) - pass it by value. ● If data object is an array, use a pointer because that's your only choice. Make the pointer a pointer to const. ● If the data object is a good-sized structure, use a const reference. ● If the data object is a class object, use a const reference 39

SPL/2010 Recommendations ● For a function that modifies data in the calling function (Out parameter): ● If the data object is a built-in data type, use a pointer or a reference, prefer the later. ● If the data object is an array, use your only choice, a pointer. ● If the data object is a structure, or a class object, use a reference 40

SPL/2010 Recommendations ● When receiving a pointer check pointer for nullity. (A reference cannot be null.) 41

SPL/2010 Returning Values From Functions ● values can be returned: ● either by value (copy) ● by reference* ● by pointer* (*) when returning something by reference or pointer care should be taken ● Is it inside activation frame to be demolished ? 42

SPL/2010 ● Returning a reference / pointer to an invalid address on the stack is one of the main pitfalls of C++ beginners. 43

SPL/

SPL/2010 different level of compiler optimizations ● g++ 1.cpp;./a.out ● 0xbffff xbffff ● g++ 1.cpp -O1;./a.out ● 0xbffff xbffff564 2 ● g++ 1.cpp -O2 ;./a.out ● 0xbffff xbffff ● g++ 1.cpp -O3 ;./a.out ● 0xbffff xbffff

SPL/2010 Memory management ● This is totally bad as we can not predict how our program will work! ● No flag is lifted for us,a.k.a no exception, no segmentation fault. ● It works every time differently. 46

SPL/2010 C++ Arrays ● blocks of continuous memory ● store data of the same type. ● memory image of an array of integers which holds the number 5 in each cell ● cell is of size 4 bytes 47

SPL/2010 C++ Arrays ● Accessing individual cells - dereferencing a pointer to the specific cell. ● assume int *arr_ptr: ● access fourth cell: arr_ptr[3] = *(arr_ptr+3) ● pointer arithmetic: arr_ptr+3 = arr_ptr+3 x sizeof(int) ● add/subtract numbers from pointer - implicitly multiplied by size of data of pointer type 48

SPL/2010 Arrays on the Heap ● everything in C++ may be allocated on Stack or Heap ● allocate array on heap: new [] operator ● deallocating an array: delete [] operator 49

SPL/2010 ● output = 0 ● new [] operator initialize array's elements by calling their default constructor (int - 0). 50

SPL/2010 array of pointers 51

SPL/2010 array of pointers ● allocate a new Cow object on the heap, and store a pointer to it in a cell of Cow* ● delete [] calls destructor of elements in array ● each element in the array is a pointer - destructor of a pointer is a nop ● individual Cows will not be deleted ● delete [] deallocates memory allocated by new [] ● delete each Cow – before deleting the array! 52

SPL/2010 Arrays on the Stack ● array's size must be known in advance: ● Cow cow_arr[5]; ● initialize individual Cows: ● Cow cow_arr[5] = {Cow(1), Cow(21), Cow(454), Cow(8), Cow(88)}; ● accessing cells of the array on the Stack same as through a pointer ● cow_arr is basically a pointer to the beginning of the array of Cows on the Stack. 53