Pointers. Developed By Ms. K.M.Sanghavi

Size: px
Start display at page:

Download "Pointers. Developed By Ms. K.M.Sanghavi"

Transcription

1 Pointers Developed By Ms. K.M.Sanghavi

2 Memory Management : Dynamic Pointers Linked List Example Smart Pointers Auto Pointer Unique Pointer Shared Pointer Weak Pointer

3 Memory Management In order to create an array in C/C++ you have to know its size in advance during compile time, in other words it has to be a constant int size; cout << Enter size of array : ; cin >> size; int array[size]; // ERROR size has to be a constant Solution in C++, use vector class from the STL which is expandable

4 Memory Management Date* void CreateDate() // allows the user to create a date object int day, month, year; char dummy; cout << Enter dd/mm/yyyy : ; cin >> day >> dummy >> month >> dummy >> year; Date date(day, month, year); return &date; // ERROR!! Scope of date ends with end of function Date *ptr; ptr=createdate(); // call CreateDate() to generate a new date cout << You entered << *ptr << endl; // variable to which ptr points no longer exist, segmentation fault!!!

5 Memory Management The new operator in C++ can be used to create objects that can be used after returning from a function Objects allocated in dynamic memory are called heap objects or to be on free store and have a permament existence Date* CreateDate() // allows the user to create a date object int day, month, year; char dummy; cout << Enter dd/mm/yyyy : ; cin >> day >> dummy >> month >> dummy >> year; Date *tmpptr = new Date date(day, month, year); return tmpptr; // returns pointer to heap object Date *ptr; ptr=createdate(); // call CreateDate() to generate a new date cout << You entered << *ptr << endl; // ok, ptr refers to heap object

6 Memory Management New can also be used to allocate blocks of memory The delete operator is used to release the memory allocated with new once it is no longer needed #include <cstring> char *str = This is an old C-style string ; int len=strlen(str); // computes the length of str char *ptr; // create a pointer to char ptr = new char[len+1]; // set aside memory string + \0 strcpy(ptr,str); // copy str to new memory cout << ptr= << ptr << endl; delete [] ptr; // release ptr s memory

7 Linked List Example struct link // one element of list int data; // data item link *next; // pointer to next element ; class linklist private: link* first; // pointer to first link public: linklist() first = NULL; // no argument constructor void additem(int d); // add data item (one link) void display(); // display all links

8 Linked List Example void linklist::additem(int d) // add data item link* newlink = new link; // create a new link newlink->data = d; // give it data d newlink->next=first; // it points to the next link first = newlink; // now first points to this link void linklist::display() // display all links link* current=first; // set ptr to first link while(current!= NULL) // until ptr points beyond last link cout << current->data << ; // print data current=current->next; // move to next link

9 Smart Pointers Consider the following simple C++ code with normal pointers. MyClass *ptr = new MyClass(); ptr->dosomething(); // We must do delete(ptr) to avoid memory leak Using smart pointers, we can make pointers to work in way that we don t need to explicitly call delete.

10 Smart Pointers Smart pointer is a wrapper class over a pointer with operator like * and -> overloaded. The objects of smart pointer class look like pointer, but can do many things that a normal pointer can t like automatic destruction reference counting and more. The idea is to make a class with a pointer, destructor and overloaded operators like * and ->.

11 Smart Pointers Since destructor is automatically called when an object goes out of scope, the dynamically allocated memory would automatically deleted (or reference count can be decremented).

12 Example for Smart Pointers #include<iostream> using namespace std; class SmartPtr int *ptr; // Actual pointer public: // Constructor explicit SmartPtr(int *p = NULL) ptr = p;

13 Example for Smart Pointers // Destructor ~SmartPtr() delete(ptr); // Overloading dereferencing operator int &operator *() return *ptr; int *operator ->() //Overloading Access operator return ptr; ;

14 Example for Smart Pointers int main() SmartPtr ptr(new int()); *ptr = 20; cout << *ptr; // We don't need to call delete ptr: when the object // ptr goes out of scope, destructor for it is automatically // called and destructor does delete ptr. return 0;

15 Use of Smart Pointers Automatic cleanup. Automatic initialization Ownership transfer Reference counting To shorten allocation and deallocation time. Since C++ does not provide automatic garbage collection like some other languages, smart pointers can be used for that purpose.

16 Smart Pointers We can make Smart pointers to work on all types. For this we need to use Templates (covered in next unit) C++ libraries provide implementations of smart pointers in the form of auto_ptr : deprecated unique_ptr : Same as auto_ptr shared_ptr and weak_ptr All these pointers exist in <memory> header file

17 Unique Pointers unique_ptr is a container for a raw pointer, which the unique_ptr is said to own. A unique_ptr explicitly prevents copying of its contained pointer (as would happen with normal assignment), But the std::move function can be used to transfer ownership of the contained pointer to another unique_ptr. A unique_ptr cannot be copied because its copy constructor and assignment operators are explicitly deleted.

18 Unique Pointers std::unique_ptr<int> p1(new int(5)); std::unique_ptr<int> p2 = p1; //Compile error. std::unique_ptr<int> p3 = std::move(p1); //Transfers ownership. p3 now owns the memory and p1 is rendered invalid. p3.reset(); //Deletes the memory. p1.reset(); //Does nothing.

19 Shared Pointers Shared_ptr is a container for a raw pointer. It maintains reference counting ownership of its contained pointer in cooperation with all copies of the shared_ptr. An object referenced by the contained raw pointer will be destroyed when and only when all copies of the shared_ptr have been destroyed.

20 Shared Pointers std::shared_ptr<int> p1(new int(5)); std::shared_ptr<int> p2 = p1; //Both now own the memory. p1.reset(); //Memory still exists, due to p2. p2.reset(); //Deletes the memory, since no one else owns the memory.

Pointers. Pointers. Pointer Variables. Pointers

Pointers. Pointers. Pointer Variables. Pointers Pointers Pointers Pointers Pointers and Arrays Pointers and function arguments Dynamic memory management New and delete Pointers are used to: Access array elements Passing arguments to functions when the

More information

Unit III Virtual Functions. Developed By Ms. K.M.Sanghavi

Unit III Virtual Functions. Developed By Ms. K.M.Sanghavi Unit III Virtual Functions Developed By Ms. K.M.Sanghavi Topics Pointers- indirection Operators Memory Management: new and delete : Slide 23-24 / (Covered In Unit I Too) Accessing Arrays using pointers

More information

Smart Pointers. Some slides from Internet

Smart Pointers. Some slides from Internet Smart Pointers Some slides from Internet 1 Part I: Concept Reference: Using C++11 s Smart Pointers, David Kieras, EECS Department, University of Michigan C++ Primer, Stanley B. Lippman, Jesee Lajoie, Barbara

More information

RAII and Smart Pointers. Ali Malik

RAII and Smart Pointers. Ali Malik RAII and Smart Pointers Ali Malik malikali@stanford.edu Game Plan Recap Conversion Operators RAII Smart Pointers Recap Initialisation: Initialisation vs Assignment Transforms an object s initial junk data

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1.. COMP6771 Advanced C++ Programming Week 5 Part Two: Dynamic Memory Management 2016 www.cse.unsw.edu.au/ cs6771 2.. Revisited 1 #include 2 3 struct X { 4 X() { std::cout

More information

Lecture 15a Persistent Memory & Shared Pointers

Lecture 15a Persistent Memory & Shared Pointers Lecture 15a Persistent Memory & Shared Pointers Dec. 5 th, 2017 Jack Applin, Guest Lecturer 2017-12-04 CS253 Fall 2017 Jack Applin & Bruce Draper 1 Announcements PA9 is due today Recitation : extra help

More information

CSE 333 Lecture smart pointers

CSE 333 Lecture smart pointers CSE 333 Lecture 14 -- smart pointers Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia Midterm Friday - Review in sections this week - Closed book; topic list

More information

CSCI-1200 Data Structures Fall 2011 Lecture 24 Garbage Collection & Smart Pointers

CSCI-1200 Data Structures Fall 2011 Lecture 24 Garbage Collection & Smart Pointers CSCI-1200 Data Structures Fall 2011 Lecture 24 Garbage Collection & Smart Pointers Review from Lecture 23 Basic exception mechanisms: try/throw/catch Functions & exceptions, constructors & exceptions Today

More information

CSE 333 Lecture smart pointers

CSE 333 Lecture smart pointers CSE 333 Lecture 14 -- smart pointers Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia New exercise out today, due Wednesday morning Exam Friday

More information

Memory Leak. C++: Memory Problems. Memory Leak. Memory Leak. Pointer Ownership. Memory Leak

Memory Leak. C++: Memory Problems. Memory Leak. Memory Leak. Pointer Ownership. Memory Leak Memory Leak C++ Memory Problems or When Good Memory Goes Bad A bug in a program that prevents it from freeing up memory that it no longer needs. As a result, the program grabs more and more memory until

More information

Homework 4. Any questions?

Homework 4. Any questions? CSE333 SECTION 8 Homework 4 Any questions? STL Standard Template Library Has many pre-build container classes STL containers store by value, not by reference Should try to use this as much as possible

More information

CSCI-1200 Data Structures Spring 2017 Lecture 27 Garbage Collection & Smart Pointers

CSCI-1200 Data Structures Spring 2017 Lecture 27 Garbage Collection & Smart Pointers CSCI-1200 Data Structures Spring 2017 Lecture 27 Garbage Collection & Smart Pointers Announcements Please fill out your course evaluations! Those of you interested in becoming an undergraduate mentor for

More information

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms AUTO POINTER (AUTO_PTR) //Example showing a bad situation with naked pointers void MyFunction()

More information

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak! //Example showing a bad situation with naked pointers CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms void MyFunction() MyClass* ptr( new

More information

ALL ABOUT POINTERS C/C++ POINTERS

ALL ABOUT POINTERS C/C++ POINTERS ALL ABOUT POINTERS CS 403: Pointers, References, and Management Stefan D. Bruda Fall 2017 http://xkcd.com/138/ CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 1 / 27 POINTERS C/C++

More information

Pointers! Arizona State University 1

Pointers! Arizona State University 1 Pointers! CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 10 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Smart Pointers and Constness Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de Summer

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

C++ Programming Lecture 7 Software Engineering Group

C++ Programming Lecture 7 Software Engineering Group C++ Programming Lecture 7 Software Engineering Group Philipp D. Schubert Contents 1. Template metaprogramming 2. Variadic template arguments 3. Smart pointer Template metaprogramming Template metaprogramming

More information

Project. C++: Smart Pointers. The Plan. Announcement. Memory Leak. Pointer Ownership. Today: STL 1 Wednesday: STL 2 Thursday: Smart Pointers

Project. C++: Smart Pointers. The Plan. Announcement. Memory Leak. Pointer Ownership. Today: STL 1 Wednesday: STL 2 Thursday: Smart Pointers Project C++: Smart Pointers Takeaway submitted. Next submission: Nim Oct 26 th Remember: okay to change framework Make sure all games work with framework Memory checks Your program should do proper memory

More information

04-19 Discussion Notes

04-19 Discussion Notes 04-19 Discussion Notes PIC 10B Spring 2018 1 Constructors and Destructors 1.1 Copy Constructor The copy constructor should copy data. However, it s not this simple, and we need to make a distinction here

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

CA341 - Comparative Programming Languages

CA341 - Comparative Programming Languages CA341 - Comparative Programming Languages David Sinclair Dynamic Data Structures Generally we do not know how much data a program will have to process. There are 2 ways to handle this: Create a fixed data

More information

C++ Smart Pointers. CSE 333 Autumn 2018

C++ Smart Pointers. CSE 333 Autumn 2018 C++ Smart Pointers CSE 333 Autumn 2018 Instructor: Hal Perkins Teaching Assistants: Tarkan Al-Kazily Renshu Gu Trais McGaha Harshita Neti Thai Pham Forrest Timour Soumya Vasisht Yifan Xu Administriia New

More information

04-17 Discussion Notes

04-17 Discussion Notes 04-17 Discussion Notes PIC 10B Spring 2018 1 RAII RAII is an acronym for the idiom Resource Acquisition is Initialization. What is meant by resource acquisition is initialization is that a resource should

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Dynamic Memory Management Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de 2. Mai 2017

More information

Assertions and Exceptions

Assertions and Exceptions CS 247: Software Engineering Principles Assertions and Exceptions Reading: Eckel, Vol. 2 Ch. 1 Exception Handling U Waterloo CS247 (Spring 2017) p.1/32 Defensive Programming The question isn t whether

More information

CSE 333 Lecture smart pointers

CSE 333 Lecture smart pointers CSE 333 Lecture 13 -- smart pointers Steve Gribble Department of Computer Science & Engineering University of Washington Administrivia HW2 is due on Thursday! - check out the discussion board for a few

More information

Pointers, Dynamic Data, and Reference Types

Pointers, Dynamic Data, and Reference Types Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple

More information

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi Modern C++ for Computer Vision and Image Processing Igor Bogoslavskyi Outline Move semantics Classes Operator overloading Making your class copyable Making your class movable Rule of all or nothing Inheritance

More information

Midterm Review. PIC 10B Spring 2018

Midterm Review. PIC 10B Spring 2018 Midterm Review PIC 10B Spring 2018 Q1 What is size t and when should it be used? A1 size t is an unsigned integer type used for indexing containers and holding the size of a container. It is guarenteed

More information

CSCI-1200 Data Structures Spring 2018 Lecture 25 Garbage Collection & Smart Pointers

CSCI-1200 Data Structures Spring 2018 Lecture 25 Garbage Collection & Smart Pointers CSCI-1200 Data Structures Spring 2018 Lecture 25 Garbage Collection & Smart Pointers Announcements Please fill out your course evaluations! Those of you interested in becoming an undergraduate mentor for

More information

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011 More C++ David Chisnall March 17, 2011 Exceptions A more fashionable goto Provides a second way of sending an error condition up the stack until it can be handled Lets intervening stack frames ignore errors

More information

Smart Pointers - What, Why, Which?

Smart Pointers - What, Why, Which? Page 1 of 7 Smart Pointers - What, Why, Which? Yonat Sharon What are they? Why would I use them? Less bugs Exception Safety Garbage collection Efficiency STL containers Which one should I use? Local variables

More information

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am CMSC 202 Section 010x Spring 2007 Computer Science II Final Exam Name: Username: Score Max Section: (check one) 0101 - Justin Martineau, Tuesday 11:30am 0102 - Sandeep Balijepalli, Thursday 11:30am 0103

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

C++ is Evolving. std::array

C++ is Evolving. std::array C++ is Evolving C++ is an evolving language. A committee of the ISO (International Organization for Standards) ratifies proposed changes to C++. New standards have been released every few years. In this

More information

Smart Pointers, deleted functions, and 2-3 trees

Smart Pointers, deleted functions, and 2-3 trees Smart Pointers, deleted functions, and 2-3 trees But first Any questions about your current homework assignment? Due Thursday night by 11:59pm Make-up oral exam: I will have a sign-up sheet on Thursday

More information

Consider the program...

Consider the program... Smart Pointers Consider the program... When the scope of foo is entered storage for pointer x is created The new allocates storage on the heap class X {... When the scope foo is left, the storage for x

More information

AN OVERVIEW OF C++ 1

AN OVERVIEW OF C++ 1 AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function

More information

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management Session 8 Memory Management The issues Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) Programs manipulate data, which must be stored

More information

G52CPP C++ Programming Lecture 16

G52CPP C++ Programming Lecture 16 G52CPP C++ Programming Lecture 16 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last Lecture Casting static cast dynamic cast const cast reinterpret cast Implicit type conversion 2 How

More information

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors Arrays Returning arrays Pointers Dynamic arrays Smart pointers Vectors To declare an array specify the type, its name, and its size in []s int arr1[10]; //or int arr2[] = {1,2,3,4,5,6,7,8}; arr2 has 8

More information

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2 Discussion 1E Jie(Jay) Wang Week 10 Dec.2 Outline Dynamic memory allocation Class Final Review Dynamic Allocation of Memory Recall int len = 100; double arr[len]; // error! What if I need to compute the

More information

Variables, Memory and Pointers

Variables, Memory and Pointers Variables, Memory and Pointers A variable is a named piece of memory The name stands in for the memory address int num; Variables, Memory and Pointers When a value is assigned to a variable, it is stored

More information

MM1_ doc Page E-1 of 12 Rüdiger Siol :21

MM1_ doc Page E-1 of 12 Rüdiger Siol :21 Contents E Structures, s and Dynamic Memory Allocation... E-2 E.1 C s Dynamic Memory Allocation Functions... E-2 E.1.1 A conceptual view of memory usage... E-2 E.1.2 malloc() and free()... E-2 E.1.3 Create

More information

More Tutorial on C++:

More Tutorial on C++: More Tutorial on C++: OBJECT POINTERS Accessing members of an object by using the dot operator. class D { int j; void set_j(int n); int mul(); ; D ob; ob.set_j(4); cout

More information

cout << "How many numbers would you like to type? "; cin >> memsize; p = new int[memsize];

cout << How many numbers would you like to type? ; cin >> memsize; p = new int[memsize]; 1 C++ Dynamic Allocation Memory needs were determined before program execution by defining the variables needed. Sometime memory needs of a program can only be determined during runtime, or the memory

More information

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers and Arrays CS 201 This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers Powerful but difficult to master Used to simulate pass-by-reference

More information

G52CPP C++ Programming Lecture 20

G52CPP C++ Programming Lecture 20 G52CPP C++ Programming Lecture 20 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Wrapping up Slicing Problem Smart pointers More C++ things Exams 2 The slicing problem 3 Objects are not

More information

Assignment operator string class c++ Assignment operator string class c++.zip

Assignment operator string class c++ Assignment operator string class c++.zip Assignment operator string class c++ Assignment operator string class c++.zip Outside class definitions; Addition assignment: a += b: The binding of operators in C and C++ is specified (character string)

More information

COMP 2355 Introduction to Systems Programming

COMP 2355 Introduction to Systems Programming COMP 2355 Introduction to Systems Programming Christian Grothoff christian@grothoff.org http://grothoff.org/christian/ 1 Today Class syntax, Constructors, Destructors Static methods Inheritance, Abstract

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty! Chapter 6 - Functions return type void or a valid data type ( int, double, char, etc) name parameter list void or a list of parameters separated by commas body return keyword required if function returns

More information

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini bertini@dsi.unifi.it http://www.dsi.unifi.it/~bertini/ Resource Management Memory, auto_ptr and RAII The most commonly used resource in

More information

Programmazione. Prof. Marco Bertini

Programmazione. Prof. Marco Bertini Programmazione Prof. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Resource Management Memory, smart pointers and RAII Resource management The most commonly used resource in C++

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

Laboratorio di Tecnologie dell'informazione

Laboratorio di Tecnologie dell'informazione Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Resource Management Memory, smart pointers and RAII Resource management The most

More information

Laboratorio di Tecnologie dell'informazione

Laboratorio di Tecnologie dell'informazione Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Resource Management Memory, smart pointers and RAII Resource management The most

More information

G52CPP C++ Programming Lecture 13

G52CPP C++ Programming Lecture 13 G52CPP C++ Programming Lecture 13 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture Function pointers Arrays of function pointers Virtual and non-virtual functions vtable and

More information

Advanced C++ 4/13/2017. The user. Types of users. Const correctness. Const declaration. This pointer and const.

Advanced C++ 4/13/2017. The user. Types of users. Const correctness. Const declaration. This pointer and const. The user. Advanced C++ For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 #define private public #define protected public #define class struct Source: Lutz

More information

Introducing C++ to Java Programmers

Introducing C++ to Java Programmers Introducing C++ to Java Programmers by Kip Irvine updated 2/27/2003 1 Philosophy of C++ Bjarne Stroustrup invented C++ in the early 1980's at Bell Laboratories First called "C with classes" Design Goals:

More information

Smart Pointers in C++11

Smart Pointers in C++11 Smart Pointers in C++11 Karl Stratos 1 Background 1.1 Pointers When we write T x to create an instance x of type T, we allocate the amount of memory required for T and names it as x. We can reference (i.e.,

More information

Homework #3 CS2255 Fall 2012

Homework #3 CS2255 Fall 2012 Homework #3 CS2255 Fall 2012 MULTIPLE CHOICE 1. The, also known as the address operator, returns the memory address of a variable. a. asterisk ( * ) b. ampersand ( & ) c. percent sign (%) d. exclamation

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++ CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many

More information

Chapter 9: Pointers. Copyright 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved.

Chapter 9: Pointers. Copyright 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 9: Pointers 9.1 Getting the Address of a Variable Getting the Address of a Variable Each variable in program is stored at a unique address Use address operator & to get address of a variable: int

More information

Chapter 9: Getting the Address of a Variable. Something Like Pointers: Arrays. Pointer Variables 8/23/2014. Getting the Address of a Variable

Chapter 9: Getting the Address of a Variable. Something Like Pointers: Arrays. Pointer Variables 8/23/2014. Getting the Address of a Variable Chapter 9: Pointers 9.1 Getting the Address of a Variable Getting the Address of a Variable Each variable in program is stored at a unique address Use address operator & to get address of a variable: int

More information

Linked List using a Sentinel

Linked List using a Sentinel Linked List using a Sentinel Linked List.h / Linked List.h Using a sentinel for search Created by Enoch Hwang on 2/1/10. Copyright 2010 La Sierra University. All rights reserved. / #include

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010 CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)

More information

Programming C++ Lecture 2. Howest, Fall 2014 Instructor: Dr. Jennifer B. Sartor

Programming C++ Lecture 2. Howest, Fall 2014 Instructor: Dr. Jennifer B. Sartor Programming C++ Lecture 2 Howest, Fall 2014 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Arrays and Pointers void myprint(const char *); int main() { char *phrasey = C++Fun ; myprint(phrasey);

More information

CS 376b Computer Vision

CS 376b Computer Vision CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves

More information

CS 103 Unit 11. Linked Lists. Mark Redekopp

CS 103 Unit 11. Linked Lists. Mark Redekopp 1 CS 103 Unit 11 Linked Lists Mark Redekopp 2 NULL Pointer Just like there was a null character in ASCII = '\0' whose ue was 0 There is a NULL pointer whose ue is 0 NULL is "keyword" you can use in C/C++

More information

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS Pages 792 to 800 Anna Rakitianskaia, University of Pretoria INITIALISING POINTER VARIABLES Pointer variables are declared by putting

More information

Financial computing with C++

Financial computing with C++ Financial Computing with C++, Lecture 6 - p1/24 Financial computing with C++ LG Gyurkó University of Oxford Michaelmas Term 2015 Financial Computing with C++, Lecture 6 - p2/24 Outline Linked lists Linked

More information

C++11 and Compiler Update

C++11 and Compiler Update C++11 and Compiler Update John JT Thomas Sr. Director Application Developer Products About this Session A Brief History Features of C++11 you should be using now Questions 2 Bjarne Stroustrup C with Objects

More information

Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am

Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am Exam 1 on July 18, 2005 10:00-11:40am Pointers Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is the

More information

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi Modern C++ for Computer Vision and Image Processing Igor Bogoslavskyi Outline Using pointers Pointers are polymorphic Pointer this Using const with pointers Stack and Heap Memory leaks and dangling pointers

More information

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

G52CPP C++ Programming Lecture 14. Dr Jason Atkin G52CPP C++ Programming Lecture 14 Dr Jason Atkin 1 Last Lecture Automatically created methods: A default constructor so that objects can be created without defining a constructor A copy constructor used

More information

Using C++11 s Smart Pointers

Using C++11 s Smart Pointers Using C++11 s Smart Pointers David Kieras, EECS Department, University of Michigan May 2015 This tutorial deals with C++11's smart pointer facility, which consists unique_ptr, shared_ptr and its partner,

More information

Vector and Free Store (Vectors and Arrays)

Vector and Free Store (Vectors and Arrays) DM560 Introduction to Programming in C++ Vector and Free Store (Vectors and Arrays) Marco Chiarandini Department of Mathematics & Computer Science University of Southern Denmark [Based on slides by Bjarne

More information

CS201- Introduction to Programming Current Quizzes

CS201- Introduction to Programming Current Quizzes CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 10 October 1, 2018 CPSC 427, Lecture 10, October 1, 2018 1/20 Brackets Example (continued from lecture 8) Stack class Brackets class Main

More information

C++11: 10 Features You Should be Using. Gordon R&D Runtime Engineer Codeplay Software Ltd.

C++11: 10 Features You Should be Using. Gordon R&D Runtime Engineer Codeplay Software Ltd. C++11: 10 Features You Should be Using Gordon Brown @AerialMantis R&D Runtime Engineer Codeplay Software Ltd. Agenda Default and Deleted Methods Static Assertions Delegated and Inherited Constructors Null

More information

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31.

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31. Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172 The lab will be on pointers In compensation, no class on Friday, Jan. 31. 1 Consider the bubble function one more

More information

Outline. A C++ Linked Structure Class A C++ Linked List C++ Linked Dynamic Memory Errors In-class work. 1 Chapter 11: C++ Linked Structures

Outline. A C++ Linked Structure Class A C++ Linked List C++ Linked Dynamic Memory Errors In-class work. 1 Chapter 11: C++ Linked Structures Outline 1 Chapter 11: C++ Linked Structures A ListNode Class To support a Linked List container class LList, a ListNode class is used for the individual nodes. A ListNode object has two attributes: item

More information

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell

More information

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects Vectors of Objects As we have mentioned earlier, you should almost always use vectors instead of arrays. If you need to keep track of persons (objects of class Person), you must decide what to store in

More information

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED. Constructor and Destructor Member Functions Constructor: - Constructor function gets invoked automatically when an object of a class is constructed (declared). Destructor:- A destructor is a automatically

More information

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC CSCI 262 Data Structures 9 Dynamically Allocated Memory POINTERS AND ARRAYS 2 Arrays Arrays are just sequential chunks of memory: Arrays and Pointers Array variables are secretly pointers: x19 x18 x17

More information

Memory Management: The Details

Memory Management: The Details Lecture 10 Memory Management: The Details Sizing Up Memory Primitive Data Types Complex Data Types byte: char: short: basic value (8 bits) 1 byte 2 bytes Pointer: platform dependent 4 bytes on 32 bit machine

More information

CS24 Week 3 Lecture 1

CS24 Week 3 Lecture 1 CS24 Week 3 Lecture 1 Kyle Dewey Overview Some minor C++ points ADT Review Object-oriented Programming C++ Classes Constructors Destructors More minor Points (if time) Key Minor Points const Motivation

More information

Vector and Free Store (Pointers and Memory Allocation)

Vector and Free Store (Pointers and Memory Allocation) DM560 Introduction to Programming in C++ Vector and Free Store (Pointers and Memory Allocation) Marco Chiarandini Department of Mathematics & Computer Science University of Southern Denmark [Based on slides

More information

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

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo Chapter 10 Pointers and Dynamic Arrays 1 Learning Objectives Pointers Pointer variables Memory management Dynamic Arrays Creating and using Pointer arithmetic Classes, Pointers, Dynamic Arrays The this

More information

dynamically allocated memory char* x = new char; int* x = new int[n]; ???...?

dynamically allocated memory char* x = new char; int* x = new int[n]; ???...? dynamically allocated memory char* x = new char; yields a memory address 1. allocates memory for a char 2. declares a pointer to a char 3. sets pointer to memory address x pointer? memory (1 byte) int*

More information

Modernizing legacy C++ code

Modernizing legacy C++ code Modernizing legacy C++ code Marius Bancila mariusbancila marius.bancila Agenda Short intro Legacy and modernization Good practices Q&A Containers Resource management correctness Const correctness Type

More information

Advanced Systems Programming

Advanced Systems Programming Advanced Systems Programming Introduction to C++ Martin Küttler September 19, 2017 1 / 18 About this presentation This presentation is not about learning programming or every C++ feature. It is a short

More information

C++ Primer. CS 148 Autumn

C++ Primer. CS 148 Autumn C++ Primer CS 148 Autumn 2018-2019 1 Who is this for? If you are taking this class and are not familiar with some of the features of C++, then this guide is for you. In other words, if any of these words

More information

OBJECT ORIENTED PROGRAMMING

OBJECT ORIENTED PROGRAMMING Classes and Objects So far you have explored the structure of a simple program that starts execution at main() and enables you to declare local and global variables and constants and branch your execution

More information

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int, Classes Starting Savitch Chapter 10 l l A class is a data type whose variables are objects Some pre-defined classes in C++ include int, char, ifstream Of course, you can define your own classes too A class

More information