Copy Constructors & Destructors

Similar documents
Exercise 6.2 A generic container class

CPSC 427: Object-Oriented Programming

Chapter 19 Vector, templates, and exceptions

Vector and Free Store (Vectors and Arrays)

pointers & references

Implementing vector<>

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

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

PIC 10B Lecture 1 Winter 2014 Homework Assignment #3

Vector and Free Store (Pointers and Memory Allocation)

Object-Oriented Principles and Practice / C++

CS11 Intro C++ Spring 2018 Lecture 2

Chapter 17 vector and Free Store

CPSC 427: Object-Oriented Programming

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

Intermediate Programming & Design (C++) Classes in C++

class Polynomial { public: Polynomial(const string& N = "no name", const vector<int>& C = vector<int>());... };

Chapter 17 vector and Free Store

The vector Class and Memory Management Chapter 17. Bjarne Stroustrup Lawrence "Pete" Petersen Walter Daugherity Fall 2007

Sixth lecture; classes, objects, reference operator.

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

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.

Chapter 7 Constructors and Other Tools. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

COP4530 Data Structures, Algorithms and Generic Programming Recitation 4 Date: September 14/18-, 2008

Programmazione. Prof. Marco Bertini

Object-Oriented Principles and Practice / C++

CS201 Some Important Definitions

Short Notes of CS201

Chapter 17 vector and Free Store. Bjarne Stroustrup

And Even More and More C++ Fundamentals of Computer Science

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

CPSC 427: Object-Oriented Programming

CS201 - Introduction to Programming Glossary By

Chapter 5. The Standard Template Library.

Chapter 18 Vectors and Arrays [and more on pointers (nmm) ] Bjarne Stroustrup

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

Chapter 13: Copy Control. Overview. Overview. Overview

Abstract. Vector. Overview. Building from the ground up. Building from the ground up 1/8/10. Chapter 17 vector and Free Store

Chapter 7. Constructors and Other Tools. Copyright 2016 Pearson, Inc. All rights reserved.

Assignment of Structs

Slide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

Lecture 5. Function Pointers

18. Dynamic Data Structures I. Dynamic Memory, Addresses and Pointers, Const-Pointer Arrays, Array-based Vectors

Programming, numerics and optimization

Common Misunderstandings from Exam 1 Material

Ch. 12: Operator Overloading

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.

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++

Special Member Functions

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming

Lecture 8. Exceptions, Constructor, Templates TDDD86: DALP. Content. Contents Exceptions

CS11 Advanced C++ Fall Lecture 7

C++ PROGRAMMING LANGUAGE: CLASSES. CAAM 519, CHAPTER 13

Doubly-Linked Lists

Copy Control 2008/04/08. Programming Research Laboratory Seoul National University

C++ Object-Oriented Programming

Advanced Systems Programming

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. C++ Kitchen Sink. Lecture 14.

Comp151. Construction & Initialization

Financial computing with C++

Allocation & Efficiency Generic Containers Notes on Assignment 5

Special Member Functions. Compiler-Generated Destructor. Compiler-Generated Default Constructor. Special Member Functions

Pointers. Developed By Ms. K.M.Sanghavi

Tell compiler ValueType is a generic type. public: void push_back(const ValueType& elem); // rest of implementation }

Chapter 17: Linked Lists

Link-Based Implementations. Chapter 4

CSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation

Praktikum: Entwicklung interaktiver eingebetteter Systeme

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

Midterm Review. PIC 10B Spring 2018

Lecture 15a Persistent Memory & Shared Pointers

CS304 Object Oriented Programming

More class design with C++ Starting Savitch Chap. 11

Working with Batches of Data

Stream Computing using Brook+

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

Lecture 12. Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 1

More C++ : Vectors, Classes, Inheritance, Templates

STL: C++ Standard Library

Announcements. Lecture 04b Header Classes. Review (again) Comments on PA1 & PA2. Warning about Arrays. Arrays 9/15/17

CS11 Advanced C++ Spring 2018 Lecture 2

Object-Oriented Principles and Practice / C++

Pointers and Memory 1

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Algorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

Chapter 17: Linked Lists

04-19 Discussion Notes

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

Purpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures

Announcements. Lecture 05a Header Classes. Midterm Format. Midterm Questions. More Midterm Stuff 9/19/17. Memory Management Strategy #0 (Review)

vector and Free Store

CS197c: Programming in C++

Templates and Vectors

CSC 210, Exam Two Section February 1999

Object-Oriented Programming

Advanced C++ Topics. Alexander Warg, 2017

Transcription:

Copy Constructors & Destructors 2-07-2013

Implementing a vector class local functions implicit constructors Destructors Copy Constructors Project #1: MiniMusicPlayer Quiz today 2/7/13 vectors and reading from a text file

template <class T> // version 1.0 class Vector { public: Vector(): buffer_(null), size_(0) { explicit Vector (int n); int size() const { return size_; T& operator[ ] (int i) { return buffer_[i]; const T& operator[ ] (int i) const { return buffer_[i]; void resize (int n); private: T* buffer_; // dynamic array containing the elements int size_; // current number of elements

template <class T> // version 1 class Vector { public: /* as in previous slide */ private: T* buffer_; int size_; /* create_new_buffer is a private method */ T* create_new_buffer ( int n ) const { return (n > 0)? new T[n] : NULL);

public: Vector (int n) : size_(n) { buffer_ = create_new_buffer(n); Problem: implicit conversions private: T* create_new_buffer ( int n ) const { return (n > 0)? new T[n] : NULL);

By default, a single argument constructor also defines an implicit conversion e.g. complex z = 2; // initialize z with complex(2) But this doesn t work for Vector e.g. Vector<string> v = 2; converts the 2 to a vector of size 2 Solution: explicit constructor prevents implicit conversions Note: Google C++ Style guidelines recommends that you always use the explicit keyword for any constructor of one argument (except for copy constructors)

public: explicit Vector (int n) : size_(n) { buffer_ = create_new_buffer(n); private: T* create_new_buffer ( int n ) const { return (n > 0)? new T[n] : NULL);

template <class T> void Vector<T>::resize ( int new_size ) { T* new_buffer = create_new_buffer(new_size); // copy elements to new buffer int min_size = (size_ < new_size)? size_ : new_size; for (int i = 0; i < min_size; i++) new_buffer[i] = buffer_[i]; // deallocate old buffer, if there is one if (buffer_!= NULL) delete[] buffer_; buffer_ = new_buffer; size_ = new_size;

Additional Vector methods Vector<T>::back() returns the last element in the vector Vector<T>:: push_back() adds an element to the end of the vector Vector<T>::pop_back() removes the last element from the vector

You can access the last element of a vector with v[ v.size() 1 ] Will add another method to simplify this v.back( )

template<class T> T& Vector<T>::back( ) { return buffer_ [ size_ - 1 ]; template<class T> const T& Vector<T>::back( ) const { return buffer_ [ size_ - 1 ] ;

template<class T> void Vector<T>::push_back( const T& new_element ) { resize( size( ) + 1 ); back( ) = new_element; template<class T> void Vector<T>::pop_back( ) { resize( size( ) 1 );

The current implementation of Vector has a memory leak! void f ( ) { Vector<string> v1( 3 ); v1.push_back( here ); v1.push_back( and ); v1.push_back( there ); allocates a dynamic array of size 3 When the function f returns, v1 is destroyed, but the array remains

template <class T> // version 1.0 class Vector { public: Vector( ): buffer_(null), size_(0) { explicit Vector (int n); ~Vector( ) { if (buffer_!= NULL) delete[ ] buffer_; A class can have any number of constructors, but only one destructor

FAQ 30.02 What are the Big Three? Destructor Copy Constructor Assignment operator A class that dynamically allocates memory or other resources should implement the big three. FAQ 30.06 What is the law of the Big Three? If a class needs any of the Big Three, it needs them all.

A copy constructor creates a copy of an existing object There are three circumstances when a copy constructor is called: (1) When an object is created and initialized to be a copy of another one (2) When an object is passed by value to a function (3) When a function returns an object

Vector<int> v1; v1.push_back(24); v1.push_back(15); v1.push_back(36); Vector<int> v2(v1); // v2 is a copy of v1 Can also write this as: Vector<int> v2 = v1;

void f ( Vector<int> a ) { int main( ) { Vector<string> v; f( v ); // the argument a is a copy of v...

Vector<int> g ( ) { Vector<int> t; return t; int main( ) { Vector<string> v; v = g( ) ; // the vector returned from g is // copied into v...

class Item { public: Item(); Item(const Item& x); class Chart { public: Chart(); // no explicit copy constructor private: Item z;

consider: Chart c1; Chart c2 = c1; // initialization by copy By default, the copy of a class object is a copy of each data member, so if Chart does not have an explicit copy constructor, the compiler will synthesize one which copy constructs each data member of Chart (that is, it calls the copy constructor for Item) This is called memberwise copy construction, otherwise known as a shallow copy.

class Item { int main() { public: Chart c1; Item( ); Chart c2 = c1; Item(const Item& x); /* compiler-synthesized copy class Chart { constructor for Chart is called public: and it calls Item::Item(const Chart( ); Item&) automatically */ // no explicit copy constructor private: Item z;

Destroying & Copying Vectors Maciel: Chapter 7, sections 7.4