Pointers and References

Slides:



Advertisements
Similar presentations
Introduction to Programming Lecture 39. Copy Constructor.
Advertisements

Pointers Revisited l What is variable address, name, value? l What is a pointer? l How is a pointer declared? l What is address-of (reference) and dereference.
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.
A RRAYS, P OINTERS AND R EFERENCES 1. A RRAYS OF O BJECTS Arrays of objects of class can be declared just like other variables. class A{ … }; A ob[4];
CSE 2501 Review Declaring a variable allocates space for the type of datum it is to store int x; // allocates space for an int int *px; // allocates space.
C++ Mini-Course Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion C++ Rulez!
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Memory and C++ Pointers.  C++ objects and memory  C++ primitive types and memory  Note: “primitive types” = int, long, float, double, char, … January.
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.
Intro to C++ And Some Tools Opening Discussion zHave any questions come up since last class? Have you had a chance to look over the project.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Pointers OVERVIEW.
C++ Memory Overview 4 major memory segments Key differences from Java
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
 Managing the heap  Resource acquisition is initialization (RAII)  Overriding operator new and delete  Class-based memory pools.
Object-Oriented Programming in C++
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
C++ REVIEW – POINTERS AND TEST DRIVEN DEVELOPMENT.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
C++ Review Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Acknowledgement: Adapted from: Brown.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 24: Pointers and Dynamic Allocation.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
System Programming Practical Session 7 C++ Memory Handling.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Pointers and References. Pointers & Memory 0x000x040x080x0B0x100x140x180x1B0x20.
1 Ugly Realities The Dark Side of C++ Chapter 12.
Memory Management.
Dynamic Allocation in C
Yan Shi CS/SE 2630 Lecture Notes
Pointers and Dynamic Arrays
Computer Organization and Design Pointers, Arrays and Strings in C
Learning Objectives Pointers as dada members
Overview 4 major memory segments Key differences from Java stack
Motivation and Overview
Pointers Revisited What is variable address, name, value?
Lecture 6 C++ Programming
Templates.
This pointer, Dynamic memory allocation, Constructors and Destructor
Dynamic Memory Review what is static, automatic, dynamic variables? why are dynamic(ally allocated) variables needed what is program stack? function.
Dynamically Allocated Memory
Dynamic Memory Allocation
CSC 253 Lecture 8.
Object Oriented Programming COP3330 / CGS5409
CSC 253 Lecture 8.
Overview 4 major memory segments Key differences from Java stack
understanding memory usage by a c++ program
Chapter 15 Pointers, Dynamic Data, and Reference Types
Overview of Memory Layout in C++
Pointers, Dynamic Data, and Reference Types
Built-In (a.k.a. Native) Types in C++
Dynamic Memory Copy Challenge
Dynamic Memory Allocation
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers And Memory Acknowledgement: THE Slides are Prepared FROM SLIDES PROVIDED By NANCY M. AMATO AND Jory Denny.
Introduction to C++ Linear Linked Lists
Class and Objects In a class, all the functions that operate on the data structure are grouped together in one place along with the data Like a struct.
Dynamic Memory.
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Pointers and dynamic objects
Dynamic Memory Copy Challenge
Dynamic Memory CSCE 121.
Destructors, Copy Constructors & Copy Assignment Operators
Pointers, Dynamic Data, and Reference Types
Destructors, Copy Constructors & Copy Assignment Operators
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Pointers and References CSCE 221H Texas A&M University 1 1

Pointers & Memory 0x00 0x04 0x08 0x0B 0x10 0x14 0x18 0x1B 0x20

5 Pointers & Memory x int x = 5; 0x00 0x04 0x08 0x0B 0x10 0x14 0x18

5 Pointers & Memory x y int x = 5; int* y = &x operator ‘&’ takes the memory address of an object/variable 0x00 0x04 0x08 0x0B 0x10 0x14 0x18 0x1B 0x20 5 0x04 x y

5 Pointers & Memory x y z int x = 5; int* y = &x int* z = y; 0x04 0x04 0x0B 0x10 0x14 0x18 0x1B 0x20 5 0x04 0x04 x y z

Pointers & Memory x y z int x = 5; int* y = &x int* z = y; *z = 0; operator ‘*’ dereferences a pointer in memory to access the underlying object/data 0x00 0x04 0x08 0x0B 0x10 0x14 0x18 0x1B 0x20 0x04 0x04 x y z

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. Just like java. But you have to think about pointers.

Deallocating memory using delete // allocate memory Point *p = new Point(5, 5); ... // free the memory delete p; For every call to new, there must be exactly one call to delete. No garbage collection.

Using new with arrays int x = 10; int* nums1 = new int[10]; // ok int* nums2 = new int[x]; // ok Dynamically allocates an array of 10 integers C++ equivalent of the following C code int* nums = (int*)malloc(x * sizeof(int));

Using delete on arrays // allocate memory int* nums1 = new int[10]; int* nums3 = new int[x][4][5]; ... // free the memory delete[] nums1; delete[] nums3; Have to use delete[].

Destructors delete calls the object’s destructor. delete frees the space occupied by an object. A destructor cleans up after the object. Releases resources such as memory, file handles, locks, etc.

Destructors – an Example class Segment { public: Segment(); virtual ~Segment(); private: Point *m_p0, *m_p1; }; Ask about virtual. (what’s wrong here…)

Destructors – an Example Segment::Segment() { m_p0 = new Point(0, 0); m_p1 = new Point(1, 1); } Segment::~Segment() if(m_p0) delete m_p0; if(m_p1) delete m_p1;

Syntactic Sugar “->” Point *p = new Point(5, 5); // Access a member function: (*p).move(10, 10); // Or more simply: p->move(10, 10); Dereference the object then call one of its functions Using p to “point” at the method.

Stack vs. Heap On the Heap / Point *p = new Point(); Dynamic allocation On the Stack / Automatic allocation Point *p = new Point(); Point *ps = new Point[n]; Point p; Point ps[10]; On the left we have a pointer that we must dereference. Still must delete p on the left – problem. on the right, everything is ok. What happens when p goes out of scope?

Dynamic Memory (resizing an array) 1 2 3 4 5 6 7 S

Dynamic Memory (resizing an array) 1 2 3 4 5 6 7 S 0 0 0 0 0 0 0 0 0 0 0 0 0 0 T int* T = new int[2*n];

Dynamic Memory (resizing an array) 1 2 3 4 5 6 7 S 1 2 3 4 5 6 7 0 0 0 0 0 0 0 T for (i = 0 to n) T[i] = S[i];

Dynamic Memory (resizing an array) 1 2 3 4 5 6 7 S 1 2 3 4 5 6 7 0 0 0 0 0 0 0 T delete[] S;

Dynamic Memory (resizing an array) 1 2 3 4 5 6 7 0 0 0 0 0 0 0 T S = T;

Passing by value void Math::square(int i) { i = i*i; } int main() { cout << i << endl; What’s the output? 5, i was copied. When passing by value, a copy is always induced in c++ (not so in c++11). Only pass ‘trivially-copyable’ objects by value, e.g., int, double, char.

Passing by reference void Math::square(int &i) { i = i*i; } int main() { int i = 5; Math::square(i); cout << i << endl; What’s the output now? 25, i was changed. When passing by reference, a copy of the memory address is passed into a function. Always pass large objects by reference, e.g., string, MyClass, vector<T>, etc.

What is a reference? An alias – another name for an object. int x = 5; int &y = x; // y is a // reference to x y = 10; What happened to x? – it is now 10 What happened to y? – silly question? y is x.

Introducing: const void Math::printSquare(const int &i){ i = i*i; cout << i << endl; } int main() { int i = 5; Math::printSquare(i); Math::printCube(i); Won’t compile. const means that the underlying data should not change. Only const functions can be called on const objects. If you can, you should make this guarantee. const extends the type to allow you to specify which data is read-only Why is this good? --- gets the compiler to help make sure certain values don’t change.

Can also pass pointers to const void Math::printSquare(const int *pi) { *pi = (*pi) * (*pi); cout << pi << endl; } int main() { int i = 5; Math::printSquare(&i); Math::printCube(&i); Still won’t compile. What exactly are we saying is const here? It is the integer *pi that is const, not the pointer. pi can be changed, but we can’t change anything through it.

Declaring things const const River nile; const River* nilePc; River* const nileCp; const River* const nileCpc Disproving Heraclites ? Read pointer declarations from right to left.

Read pointer declarations right to left // A const River const River nile; // A pointer to a const River const River* nilePc; // A const pointer to a River River* const nileCp; // A const pointer to a const River const River* const nileCpc

Lab Assignment Create a class called Point with two private data members, a public function Print, and constructors. Statically allocate an array of 10 Points, initialize them with non-zero data, and print them. Dynamically allocate an array of 10 Points, initialize them with non-zero data, and print them. Loop through the second array using pointer arithmetic and print them again (hint p+1 is a pointer to the second element on the array)