1 Inside the Vector Class: with additional needed methods CPS212CPS212 Gordon College.

Slides:



Advertisements
Similar presentations
Lists Chapter 6 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved
Advertisements

Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
Introduction to Programming Lecture 39. Copy Constructor.
Review of Stacks and Queues Dr. Yingwu Zhu. Our Focus Only link-list based implementation of Stack class Won’t talk about different implementations of.
Dynamic Allocation Eric Roberts CS 106B February 4, 2013.
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.
Wrap Up and Misc Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
Dynamically Allocated Arrays May 2, Quiz 5 Today.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 22 - C++ Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type.
1 Chapter 6 Lists Plus. ADT Sorted List Operations Transformers n MakeEmpty n InsertItem n DeleteItem Observers n IsFull n LengthIs n RetrieveItem Iterators.
Stacks  Standard operations: IsEmpty … return true iff stack is empty Top … return top element of stack Push … add an element to the top of the stack.
1 Class Constructors a class constructor is a member function whose purpose is to initialize the private data members of a class object the name of a constructor.
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.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Review of C++ Programming Part II Sheng-Fang Huang.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
CSE 333 – SECTION 4. Overview Pointers vs. references Const Classes, constructors, new, delete, etc. More operator overloading.
Copy Control Joe Meehean. More Class Responsibilities When making a new type (i.e., class) we must specify what happens when it is: Copied Assigned Destroyed.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
1 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Modified from the slides by Sylvia Sorkin, Community College of Baltimore County -
Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,
1 Chapter 15-2 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Dynamically Allocated Arrays December 4, Skip the Rest of this PowerPoint.
The Big Three Based on Weiss “Data Structures and algorithm Analysis CS240 Computer Science II.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
More Linking Up with Linked Lists Chapter 11 5/19/2015 Adopted from instructor resource slides Nyhoff, ADTs, Data Structures and Problem Solving with C++,
1 Recall Definition of Stack l Logical (or ADT) level: A stack is an ordered group of homogeneous items (elements), in which the removal and addition of.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Review of Stacks and Queues Dr. Yingwu Zhu. How does a Stack Work? Last-in-First-out (LIFO) data structure Adding an item Push operation Removing an item.
Data Structures Using C++1 Chapter 3 Pointers Dr. Liu.
CS 1704 Introduction to Data Structures and Software Engineering.
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
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.
What happens... l When a function is called that uses pass by value for a class object like our dynamically linked stack? StackType MakeEmpty Pop Push.
Chapter 6 Lists Plus. What is a Class Template? A class template allows the compiler to generate multiple versions of a class type by using type parameters.
TEMPLATESTEMPLATES BCAS,Bapatla B.mohini devi. Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type Parameters 22.4Templates.
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.
Dynamic Memory Review l what is static, automatic, dynamic variables? Why are dynamic(ally allocated) variables needed l what is program stack? Function.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review 2.
PROGRAMMING 1 – HELPER INSTRUCTIONS ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED BY NANCY M. AMATO AND JORY DENNY 1.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Lists Chapter.
1 // SPECIFICATION FILE (dynarray.h) // Safe integer array class allows run-time specification // of size, prevents indexes from going out of bounds, //
Memory Management.
Pointers and Dynamic Arrays
Learning Objectives Pointers as dada members
LinkedList Class.
Memberwise Assignment / Initialization
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
Array Lists Chapter 6 Section 6.1 to 6.3
understanding memory usage by a c++ program
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 15 Pointers, Dynamic Data, and Reference Types
Essential Class Operations
CS148 Introduction to Programming II
9-10 Classes: A Deeper Look.
Data Structures and Algorithms Memory allocation and Dynamic Array
Essential Class Operations
Rule of Three Part 1 & 2.
9-10 Classes: A Deeper Look.
SPL – PS3 C++ Classes.
Presentation transcript:

1 Inside the Vector Class: with additional needed methods CPS212CPS212 Gordon College

2 Inside the Vector Class: class definition template class Vec { public: Vec(int size = 0); Vec(int, T); ~Vec();// destructor T& back(); const T& back() const; T& operator[] (int i); const T& operator[] (int i) const; void push_back(const T& item); void pop_back(); inline int getSize() const {return size;} inline bool isEmpty() const {return (size==0)?true:false;} inline int getCap() const {return cap;} void reserve(int n); private: int cap; int size; T *vPtr; };

3 Inside the Vector Class: the Constructors template Vec ::Vec(int size_): size(0), cap(0), vPtr(NULL) { if (size_ == 0) return; reserve(size_); } template Vec ::Vec(int size_, T value_): size(0), cap(0), vPtr(NULL) { if (size_ == 0) return; reserve(size_); size = size_; for (int i=0;i < size;i++) vPtr[i] = value_; }

4 Inside the Vector Class: the Destructor The new operator is used to perform memory allocation from the heap ptr = new T[20]; Heap before after ptr ? If object dies without first calling the Delete operation then allocated memory is lost - memory leak

5 Inside the Vector Class: the Destructor template Vec ::~Vec() { if (vPtr != NULL) delete [] vPtr; } Used to free a dynamically allocated array from the heap Dynamic Variable Example int *ptr = new int(3); delete ptr; Dynamic Array Example int *ptr = new int[20]; delete [ ] ptr; Note: must free memory before it becomes inaccessible

6 New Functions Needed Destructor –When class object goes out of scope the pointer to the dynamically allocated memory is reclaimed (reused my OS) automatically –The dynamically allocated memory is not –The destructor reclaims dynamically allocated memory

7 Inside the Vector Class: the Allocation template void Vec ::reserve(int n) { T *nPtr; if (size>n) n=size; nPtr = new T[n]; if (nPtr == NULL) throw runtime_error ("Vec reserve(): memory allocation failure"); for(int i = 0; i < size; i++) nPtr[i] = vPtr[i]; if (vPtr != NULL) delete [] vPtr; vPtr = nPtr; cap = n; }

8 Inside the Vector Class: back() template T& Vec ::back() { if (size == 0) throw runtime_error("Vec back(): vector empty"); return vPtr[size-1]; } template const T& Vec ::back() const { if (size == 0) throw runtime_error("Vec back(): vector empty"); return vPtr[size-1]; }

9 Inside the Vector Class: push and pop template void Vec ::push_back(const T& item) { if (size == cap) { if (cap == 0) reserve(1); else reserve(2 * cap); } vPtr[size] = item; size++; } template void Vec ::pop_back() { if (size == 0) throw runtime_error( "Vec pop_back(): vector is empty"); size--; }

10 New Functions Needed: Copy Constructor A copy constructor is called whenever a new variable is created from an object. This happens in the following cases (but not in assignment). 1. A variable is declared which is initialized from another object. Cow q(“Bessie”); // constructor is used to build q. Cow r(p); // copy constructor is used to build r. Cow p = q; // copy constructor is used to initialize in declaration. p = q; // Assignment operator, not constructor or copy constructor. 2. argument is passed as value parameter. f(p); // copy constructor initializes formal value parameter. (method call) 3. An object is returned by a function (returns a local copy).

11 New Functions Needed: Copy Constructor Copy Constructor – makes a "deep copy" of an objectCopy Constructor C++ calls the copy constructor when the previously mentioned “copy constructor” cases are executed. (if copy constructor is not available then the default constructor is called) If copy is not made, observe results (aliasing problem, "shallow" copy)

12 Inside the Vector Class: the copy constructor template Vec ::Vec (const Vec & obj): size(0), cap(0), vPtr(NULL) { if (obj.getCap() == 0) return; reserve(obj.getCap()); size = obj.size; for (int i = 0; i < size; i++) vPtr[i] = obj.vPtr[i]; }

13 Assignment operator –Default assignment operator makes shallow copy –Can cause memory leak, dynamically-allocated memory has nothing pointing to it New Functions Needed: Assignment Operator

14 Inside the Vector Class: the assignment operator template Vec & Vec ::operator= (const Vec & rhs) { if (vPtr!=NULL) delete [] vPtr; vPtr = new T[rhs.getCap()]; if (vPtr == NULL) throw runtime_error("Vec reserve(): memory allocation failure"); size = rhs.size; for (int i = 0; i < size; i++) vPtr[i] = rhs.vPtr[i]; return *this; }

15 Class Design Needs RULE: If a class allocates memory at run time using the new, then it should provide … A destructor A copy constructor An assignment operator These overcome the 2 common dynamic memory allocation problems: memory leak and shallow copy.