Object-Oriented Principles and Practice / C++

Similar documents
Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++

7.1 Optional Parameters

Object-Oriented Principles and Practice / C++

Construction and Destruction

CPSC 427: Object-Oriented Programming

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

Object-Oriented Principles and Practice / C++

Assignment of Structs

Special Member Functions

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

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

COMP6771 Advanced C++ Programming

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming

Midterm Review. PIC 10B Spring 2018

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

Ch. 11: References & the Copy-Constructor. - continued -

Instantiation of Template class

Programming, numerics and optimization

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.

CSE 143. Linked Lists. Linked Lists. Manipulating Nodes (1) Creating Nodes. Manipulating Nodes (3) Manipulating Nodes (2) CSE 143 1

QUIZ. What is wrong with this code that uses default arguments?

C The new standard

CS304 Object Oriented Programming Final Term

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

CSCI-1200 Data Structures Fall 2018 Lecture 7 Templated Classes & Vector Implementation

CSE 303: Concepts and Tools for Software Development

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

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

CPSC 427: Object-Oriented Programming

Interview Questions of C++

An Introduction to C++

Assignment of Objects

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

Object-Oriented Programming for Scientific Computing

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

Objects Managing a Resource

Introduction to Programming Using Java (98-388)

Vector and Free Store (Pointers and Memory Allocation)

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CS32 - Week 1. Umut Oztok. June 24, Umut Oztok CS32 - Week 1

CPSC 427: Object-Oriented Programming

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

Object Oriented Programming. Solved MCQs - Part 2

2 ADT Programming User-defined abstract data types

Overview of C Feabhas Ltd 2012

Program construction in C++ for Scientific Computing

COMP 2355 Introduction to Systems Programming

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

PIC 10B Lecture 1 Winter 2014 Homework Assignment #3

Object Oriented Software Design II

IS0020 Program Design and Software Tools Midterm, Fall, 2004

A brief introduction to C++

From Java to C++ From Java to C++ CSE250 Lecture Notes Weeks 1 2, part of 3. Kenneth W. Regan University at Buffalo (SUNY) September 10, 2009

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

LECTURE 03 LINKED LIST

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

G52CPP C++ Programming Lecture 13

CS201 Latest Solved MCQs

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Rvalue References & Move Semantics

IBS Software Services Technical Interview Questions. Q1. What is the difference between declaration and definition?

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

Chapter 1: Object-Oriented Programming Using C++

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

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

Function Overloading

Data Structures and Algorithms

Advanced Systems Programming

Chapter 17 vector and Free Store

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

Evolution of Programming Languages

Administrivia. CMSC433, Fall 2001 Programming Language Technology and Paradigms. Administrivia (cont.) Project 1. Copy constructor.

Object-Oriented Programming

Object Oriented Software Design - II

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

CSE 12 Week Eight, Lecture One

Classes: Member functions // classes example #include <iostream> using namespace std; Objects : Reminder. Member functions: Methods.

CS11 Advanced C++ Spring 2018 Lecture 1

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

04-19 Discussion Notes

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

An Introduction to Trees

Chapter 6 Introduction to Defining Classes

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

CS 162, Lecture 25: Exam II Review. 30 May 2018

G Programming Languages - Fall 2012

C++11/14 Rocks. Clang Edition. Alex Korban

Vector and Free Store (Vectors and Arrays)

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Where do we go from here?

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

END TERM EXAMINATION

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

Transcription:

Object-Oriented Principles and Practice / C++ Alice E. Fischer May 13, 2013 OOPP / C++ Lecture 7... 1/27

Construction and Destruction Allocation and Deallocation Move Semantics Template Classes Example: The Stack Template Deallocation Example OOPP / C++ Lecture 7... 2/27

Construction and Destruction Ch 10 Allocation and Deallocation: Review Initializing Arrays Six kinds of Constructors But just one Destructor OOPP / C++ Lecture 7... 3/27

Allocation and Deallocation Allocation and Deallocation Ch 10.2 The new function in C++ builds upon C s malloc. Using new or malloc results in the storage you requested + enough to handle deallocation Minimally, the total allocated block length must be stored Thus, allocating a new double uses up 12 bytes of memory, 4 for the block length and 8 for the data. For a struct, it is the overhead + enough bytes to hold the data + padding. New and malloc differ for arrays because new also allocates memory for the array length. (A total of 8 bytes of overhead) OOPP / C++ Lecture 7... 4/27

Allocation and Deallocation Initialization C++11 gives us new ways to initialize arrays. class Tester { private: static int a0[3]; static constexpr int a1[3]{1,2,3}; int a2[3] = {8}; int a3[3]; int* a4; int* a5 = new int[3]{5,6,7}; public: Tester(): a3(), a4(new int[3]{7,8,9}) {} } const int Tester::a1[3]; int Tester::a0[3]{4,5,6}; OOPP / C++ Lecture 7... 5/27

Allocation and Deallocation Six Kinds of Constructors Null constructor: initializes nothing but may print a trace comment. You get an empty null constructor for free if you do not define a real constructor. Default constructor: may do initializations but lacks parameters. Normal constructor: has parameters used to initialize the object. Default copy constructor: initializes an object by shallow-copying another. Copy constructor: replaces the default copy constructor. It can do anything, including making a full copy of the object. Move constructor: moves the contents of one object to another during initialization. OOPP / C++ Lecture 7... 6/27

Allocation and Deallocation Several Constructors but just one Destructor A destructor must handle every class object the same way. Thus, every object must be the same general shape and have the same number of dynamic parts (or NULL pointers) to delete. According to the standard, it is harmless to delete a NULL pointer. Nothing is supposed to happen. You do not need to test a pointer before trying to delete it. However, apparently, some implementations of C++ do not comply to the standard. Normally, a destructor should free all objects that were created by calling new in the constructor or in any other class function, or by inserting an object (created elsewhere) into a class data structure. OOPP / C++ Lecture 7... 7/27

Allocation and Deallocation Revisiting delete and delete[] For non-arrays, the block length is stored just before the data part (just like malloc) For arrays, the array length is stored before beginning of the data area and the block length is stored just before the array length. When you call delete it uses the block length to free memory. When you call delete[] it does two things: First, the array length is used to control a loop that calls delete on each array element. Then the block length is used to free the array allocation. OOPP / C++ Lecture 7... 8/27

Construction and Destruction RValue References Default Class Operations: C++ 11 Control of Defaults: C++ 11 OOPP / C++ Lecture 7... 9/27

RValue References An rvalue reference can bind to an rvalue (but not to an lvalue): X a; X& r1 = a; X&& rr1 = f(); X&& rr2 = a; // bind r1 to a (an lvalue) // bind rr1 to the result of f(). // error: a is an lvalue This idea can be used to speed up execution of any operation that moves values around. If X is a type for which copying is expensive (string, vector) a simple swap becomes an expensive operation. OOPP / C++ Lecture 7... 10/27

RValue Swapping But when we swap, we don t really want new copies at all. We just want to rebind the existing copies. void swap(t& a, T& b) { T tmp = move(a); // Save a s value. a = move(b); // Move b s value to a. b = move(tmp); // Move the saved value to b. Moving is faster than copying for many types because it does not construct a new object. This is very important when you design a template because the template parameter could be any primitive or class type. OOPP / C++ Lecture 7... 11/27

Default Class Operations: C++ 11 By default, a class has these five related operations: destructor: By default, a null destructor. copy constructor: X(const X&) Initialize a new object from an old one of the same type. The contents of the source are unchanged. copy assignment: Y& operator=(const Y&) Copy one object into another of the same type. The contents of the source are unchanged. move constructor: X(const X&&) Initialize a new object by moving the contents of an old object into it. After the move, the contents of the source are set to the initial constructed state. move assignment: Y& operator=(y&&); Move one object into another. OOPP / C++ Lecture 7... 12/27

Default Class Operations: C++ 11 Copy, move, and delete are closely related operations. You can redefine all of them, but only a few combinations make sense. If you declare any of them you must explicitly define or default all the others. If you define any one, movers will not be generated automatically. Copiers will be generated automatically, but this is deprecated. Move constructor and move assignment takes non-const &&. They can, and usually do, write to their argument OOPP / C++ Lecture 7... 13/27

Control of Defaults: C++ 11 The keywords delete and default and can be used to define methods. class X { // These definitions disallow copying. X& operator=(const X&) = delete; X(const X&) = delete; }; class X { // These define the default copy behavior. X& operator=(const X&) = default; X(const X&) = default; }; OOPP / C++ Lecture 7... 14/27

Template Classes and Instantiation Code with a Hole Template Instantiation Derive and Instantiate Overriding functions OOPP / C++ Lecture 7... 15/27

A Template is Code with Holes. Chapter 13 A template is a class definition with parameters. A template is NOT a class and cannot be used directly. Most templates have one type-name parameter; some have two. Integer parameters are also possible. template class NewTemp < class T > {...}; Within the class: bool compareto(t data) {...}; Outside the class braces: template <class T> ostream& NewTemp<T>::print(ostream& out) {...}; OOPP / C++ Lecture 7... 16/27

A Note about Templates Given a template definition, there are three things you can do with it: Instantiate it to get a normal class. Derive from it to get another template. Derive and instantiate in the same step to get a class to which you can add functionality and/or data members. OOPP / C++ Lecture 7... 17/27

From Template to Class. A class is constructed from a template by instantiation. Stack<int> instantiates the Stack template with type int to produce a class named Stack<int>. The instantiation is done at compile time, before the class can be compiled. The compiler will insert the type int everywhere the template code says T, then compile the resulting class. If we later instantiate with double, the resulting class is different and must also be compiled. We can instantiate a template and derive from it in the same line: class mystack : public Stack<int> Derivation + instantiation is a common technique because we often want to modify the basic type provided by the library templates. OOPP / C++ Lecture 7... 18/27

Template problems A template is an abstract data structure that will be instantiated with a specific base type at compile time. To be widely useful, the template should work with many or all possible base types. Functions called by the template must be defined for all instantiation-base types. This is not a problem for primitive numeric, character, and pointer types, since all of the common operations are defined for them: comparisons, input, output. If a class type is used to instantiate a template, then the class must define all the operators and functions used by the template functions. If the template makes copies of the base-type data, and if that base type has dynamic extensions great care must be taken to avoid shallow-copy followed by deep-delete. OOPP / C++ Lecture 7... 19/27

Move Semantics What we really want to do is move all of the data from one array to another, not create a duplicate copy of the data. We certainly do not want to create deep copies! The latest revision of C++ allows us to define a move constructor for each class that is different from the copy constructor. When we deep-copy an object, all of its core parts and all its extensions are duplicated. This consumes time and space. A shallow copy duplicates the core parts but not the extensions, and two copies of the core object end up pointing at the same extensions. When we move an object, we want all parts of the object in the new location, and we want any pointers in the old location nulled-out. OOPP / C++ Lecture 7... 20/27

Stack The Stack Template OOPP / C++ Lecture 7... 21/27

Stack Two Versions To define any linked data structure, we need a master class and a helper class. (e.g. List and Cell) The helper class should be controlled, managed, and used exclusively by its master class. The master class should have full access to helper instances, but they should otherwise be hidden from the world. There are two ways to achieve this: use a friend declaration and use a private inner class. See stack template examples 1 and 2. OOPP / C++ Lecture 7... 22/27

Stack Deriving a Template from a Template The Stack template is derived from a FlexArray template. The FlexArray provides the growable array that implements the stack. There are some difficulties when a template is derived from a template. When the derived template is first parsed by the compiler, the base template has not yet been expanded, so the members of the base class are not yet visible to the compiler. Fix this by using this-> in front of references to base class members, or by using the full name of the base class with :: OOPP / C++ Lecture 7... 23/27

Allocation and Deallocation Example Ch 10.2 Box and Van The Van Class The Output OOPP / C++ Lecture 7... 24/27

Box and Van This program illustrates allocation and deallocation semantics. Box has two constructors: with parameters and without parameters. They could be combined by using default parameters: Box(int ln=1, int wd=1, int ht=1){ length=ln; width=wd; high=ht; cout<<"\n Real Box "; } The destructor prints trace information but does not deallocate anything. This is appropriate because the constructor does not allocate any new objects. Note the dump function: it backs off from the head of an array and prints the secret data. OOPP / C++ Lecture 7... 25/27

The Van Class This class aggregates several Boxes, stored as two arrays. Lines 60 61: the van constructs two arrays of default boxes using the default constructor. These will be overlaid by real boxes later. Line 68 allocates a Box in temporary memory. This Box is deallocated on line 69, immediately after its contents is copied into the box array, Load1. Construction, assignment, and deallocation of the original copy happen every time around the loop. You can follow the progress of this process using the trace information printed by the Box destructor. Again, note the dump function: it prints the address and contents of each part of the Van. OOPP / C++ Lecture 7... 26/27

The Output Looking at the output and the trace we see: 7 default boxes were constructed by lines 60 and 61. Then the loop on lines 64... 69 is executed four times. Three sets of real dimensions are entered, followed by 0 dimensions to end the loop. For each set of real dimensions, line 68 creates a temporary box and copies it into the Load. At the end of the loop (line 69) the temporary box is deleted. The van dump shows that copies of the temporary boxes live on in Load1. After termination, Load2 (which was created last) is deallocated first. Two default boxes are deleted. Then Load1 is deleted, starting with the highest subscript and ending with the first real box. OOPP / C++ Lecture 7... 27/27