Comp151. Generic Programming: Container Classes

Similar documents
Review: C++ Basic Concepts. Dr. Yingwu Zhu

class Array; // Class template declaration class Array public: // T="type",e.g.,int or float Array(int n); // Create array of n elements Array(); // C

pointers & references

Structuur van Computerprogramma s 2

Use the dot operator to access a member of a specific object.

CPSC 427: Object-Oriented Programming

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

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

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

การทดลองท 8_2 Editor Buffer Array Implementation

Object oriented programming

CSCI 123 Introduction to Programming Concepts in C++

Introducing C++ to Java Programmers

COMP6771 Advanced C++ Programming

Object-Oriented Programming in C++

Function Overloading

Due Date: See Blackboard

Topics. bool and string types input/output library functions comments memory allocation templates classes

SFU CMPT Topic: Class Templates

W3101: Programming Languages C++ Ramana Isukapalli

Roxana Dumitrescu. C++ in Financial Mathematics

CSE 303: Concepts and Tools for Software Development

Lab 2: ADT Design & Implementation

Due Date: See Blackboard

1 Short Answer (5 Points Each)

CPSC 427: Object-Oriented Programming

Copy Constructor, Assignment, Equality

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

Templates and Vectors

Intermediate Programming, Spring 2017*

Ch 8. Operator Overloading, Friends, and References

Program template-smart-pointers-again.cc

G52CPP C++ Programming Lecture 17

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

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

CSC1322 Object-Oriented Programming Concepts

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

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Chapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved

When we program, we have to deal with errors. Our most basic aim is correctness, but we must

Implementing an ADT with a Class

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

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

Intermediate Programming, Spring 2017*

GEA 2017, Week 4. February 21, 2017

Introduction & Review

Suppose that you want to use two libraries with a bunch of useful classes and functions, but some names collide:

CS24 Week 3 Lecture 1

Inheritance and Polymorphism

CS 247: Software Engineering Principles. ADT Design

Object-Oriented Principles and Practice / C++

EECE.3220: Data Structures Spring 2017

Lecture 23: Pointer Arithmetic

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

377 Student Guide to C++

Programming Abstractions

Where do we go from here?

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Friends and Overloaded Operators

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

Friends and Overloaded Operators

More Advanced Class Concepts

CSCE 110 PROGRAMMING FUNDAMENTALS

Review Questions for Final Exam KEY

Programming in C++: Assignment Week 8

Intermediate Programming, Spring 2017*

CSS 342 Data Structures, Algorithms, and Discrete Mathematics I. Lecture 2. Yusuf Pisan

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47

Special Member Functions

Operator overloading

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

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++

Circle all of the following which would make sense as the function prototype.

EL2310 Scientific Programming

Exam duration: 3 hours Number of pages: 10

IS0020 Program Design and Software Tools Midterm, Fall, 2004

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

COMP322 - Introduction to C++ Lecture 01 - Introduction

C++ Constructor Insanity

Lecture on pointers, references, and arrays and vectors

04-19 Discussion Notes

C++11 Move Constructors and Move Assignment. For Introduction to C++ Programming By Y. Daniel Liang

Iterators. node UML diagram implementing a double linked list the need for a deep copy. nested classes for iterator function objects

Evolution of Programming Languages

CPSC 427a: Object-Oriented Programming

Lecture 2. Binary Trees & Implementations. Yusuf Pisan

A brief introduction to C++

CPSC 427: Object-Oriented Programming

C++: Overview and Features

Sol. Sol. a. void remove_items_less_than(int arr[], int size, int value) #include <iostream> #include <ctime> using namespace std;

Classes in C++98 and C++11

struct Buffer { Buffer(int s) { buf = new char[s]; } ~Buffer() { delete [] buf; } char *buf; };

Shahram Rahatlou. Computing Methods in Physics. Overloading Operators friend functions static data and methods

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

Value Semantics and Concept Based Polymorphism Sean Parent Principal Scientist Adobe Systems Incorporated. All Rights Reserved.

What will happen if we try to compile, link and run this program? Do you have any comments to the code?

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science

Concepts (this lecture) CSC 143. Classes with Dynamically Allocated Data. List of ints w/dups (cont.) Example: List of ints with dups.

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

Transcription:

Comp151 Generic Programming: Container Classes

Container Classes Container classes are a typical use for class templates, since we need container classes for objects of many different types, and the types are not known when the container class is designed. Let s design a container that looks like an array, but that is a firstclass type: so that assignment and call-by-value is possible. We want the container to be homogeneous: all the elements must have the same type. But should a container with 10 int elements be the same type as a container with 20 int elements? Both choices are sensible design decisions. Remark: The vector type in STL is better than the classes we ll write in this lecture, so this is just for understanding. We are doing this to illustrate how C++ s actual vector, list, etc. can be implemented.

Example: Container Class bunch.hpp template<typename T, int N> class Bunch public: Bunch(); Bunch(const Bunch &B); ~Bunch(); int size() const return N; T& operator[ ](int i) return value_m[i]; T& operator=(const Bunch &B); private: T value_m[n]; ;

Example: Use of Class Bunch Bunch<int, 10> a; cout << a[3]; a[7] = 13; ++a[2]; Bunch<string, 50> b; b[49] = ''Hello world''; Bunch<string, 50> c; c = b; Bunch<int, 20> d; d = a; // Legal // Error: d and a are of different types

A More Flexible Container Class array.hpp #ifndef ARRAY_HPP #define ARRAY_HPP class Array private: T* value_m; int size_m; public: Array(int n = 10); Array(const Array& A); ~Array(); // Default/conversion constructor // Copy constructor ; int size() const return size_m; Array<T>& operator=(const Array<T>& A); T& operator[ ](int i) return value_m[i]; ; const T& operator[ ](int i) const return value_m[i]; ; // Assignment operator // Access to an element // Const access to an element #endif

Example: Use of Class Array #include <iostream> #include ''array.hpp'' using namespace std; int main() Array<int> a; cout << a.size() << endl; a[9] = 17; // Ok: uses non-const version of operator[ ] ++a[2]; // Ok: uses non-const version of operator[ ] cout << a[2] << endl; Array<int> b(5); cout << b.size() << endl; const Array<int> c(20); c[1] = 5; cout << c[1] << endl; // Error: assignment to read-only location a = c; cout << a[2] << endl;

Example: Constructors/Destructor of Class Array Array<T>::Array(int n) : value_m( new T[n] ), size_m(n) Array<T>::Array(const Array<T>& A) : value_m( new T[A.size_m] ), _size(a.size_m) for (int i = 0; i < size_m; ++i) value_m[i] = A.value_m[i]; Array<T>::~Array() delete[ ] value_m;

Shallow Copy and Deep Copy Array<int> A(10); Array<int> B(A); Shallow Copy: If you don't define your own copy constructor, the copy constructor provided by the compiler simply does member-wise copy. Then A and B will share to the same value_m array. If you delete A, and then B, you will have an error as you will delete the embedded value_m array twice from the heap. Basically, shallow copy is a bad idea if an object owns data. Deep Copy: To take care of the ownership, redefine the copy constructor so that each object has its own copy of the owned" data members.

Assignment Operator Idea: To assign b = a, first throw away the old data b.value_m, then create a new one and assign the elements from a.value_m. Array<T>& Array<T>::operator=(const Array<T>& A) delete [ ] value_m; size_m = A. size_m; value_m = new T[size_m]; for (int i = 0; i < size_m; ++i) value_m[i] = A.value_m[i]; return *this;

Assignment Operator (cont d) There is a serious problem with the previous code. In the assignment a = a, the data in the container is lost! Solution: When the assignment argument is the same as the object being assigned to, don't do anything. Array<T>& Array<T>::operator=(const Array<T>& A) if (this!= &A) delete [ ] value_m; size_m = A. size_m; value_m = new T[size_m]; for (int i = 0; i < size_m; ++i) value_m[i] = A.value_m[i]; return *this;

Assignment Operator (cont d) Here is another way of implementing the assignment operator. Quiz: Why does this elegant trick work?? Array<T>& Array<T>::operator=(const Array<T>& A) size_m = A.size_m; Array<T> temp(a); std::swap( value_m, temp.value_m); return *this; // Here s what std::swap() basically looks like: void swap(t& a, T& b) T temp = a; a = b; b = temp;

Output Operator The following output operator is not a member of the Array<T> class, but a function template. Function templates and class templates work together very well: We can use function templates to implement functions that will work on any class created from a class template. ostream& operator<<(ostream& os, const Array<T>& A) for (int i = 0; i < A.size(); ++i) os << A[i] << ' '; return os;

Why 2 Different Subscript Operators? We have 2 subscript operators, and it looks as if we are violating the overloading rule. Both have the same name and the same arguments. Array<int> a(3); a[2] = 7; // Quiz: which version of operator[ ] is called? In the above code, we need a subscript operator that returns an int&, not a const int&. But this subscript operator does not work in this code: int last_element(const Array<int>& a) return a[a.size() - 1];

Why 2 Different Subscript Operators? The argument a of last_element() is a const Array<int>&. Therefore it can only call const member functions: in this example, int size() const const T& operator[ ](int i) const Note: On the other hand, if bad programmers are not so strict with const correctness (which is a bad idea), they could simply define one subscript function as: T& operator[ ](int i) const return value_m[i]; // This is dangerous! (Why?)