CPSC 427: Object-Oriented Programming

Similar documents
CPSC 427: Object-Oriented Programming

An Introduction to Classes

An Introduction to Classes

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

Object-Oriented Programming for Scientific Computing

CPSC 427: Object-Oriented Programming

COMP 2355 Introduction to Systems Programming

Interview Questions of C++

CPSC 427: Object-Oriented Programming

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

CPSC 427a: Object-Oriented Programming

Object-Oriented Principles and Practice / C++

Linked List using a Sentinel

CPSC 427: Object-Oriented Programming

05-01 Discussion Notes

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

Data Structures and Algorithms

CA341 - Comparative Programming Languages

Common Misunderstandings from Exam 1 Material

7.1 Optional Parameters

Review of the C Programming Language for Principles of Operating Systems

Object-Oriented Principles and Practice / C++

CSC 211 Intermediate Programming. Arrays & Pointers

CSE 303: Concepts and Tools for Software Development

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

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!

CS201 Some Important Definitions

Introduction to C++ Systems Programming

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

The C++ Language. Arizona State University 1

21. Dynamic Datatypes and Memory Management

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

Pointers, Dynamic Data, and Reference Types

Chapter 2. Procedural Programming

CPSC 427: Object-Oriented Programming

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

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

Classes and Pointers: Some Peculiarities

21. Dynamic Datatypes and Memory Management

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

Financial computing with C++

Review of the C Programming Language

CPSC 427: Object-Oriented Programming

Pointers and References

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

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

W3101: Programming Languages C++ Ramana Isukapalli

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

CE221 Programming in C++ Part 1 Introduction

Vector and Free Store (Vectors and Arrays)

C++ For Science and Engineering Lecture 27

A brief introduction to C++

Midterm Review. PIC 10B Spring 2018

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

In Java we have the keyword null, which is the value of an uninitialized reference type

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

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

CS24 Week 3 Lecture 1

Evolution of Programming Languages

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

CS 376b Computer Vision

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #1 Examination 12:30 noon, Tuesday, February 14, 2012

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)

377 Student Guide to C++

CMSC 202 Midterm Exam 1 Fall 2015

Understanding Pointers

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

C++ For Science and Engineering Lecture 15

G52CPP C++ Programming Lecture 13

CS201- Introduction to Programming Current Quizzes

Homework 4. Any questions?

CSCE 110 PROGRAMMING FUNDAMENTALS

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

AN OVERVIEW OF C++ 1

CPSC 427: Object-Oriented Programming

Object-Oriented Programming, Iouliia Skliarova

Initializing and Finalizing Objects

Tokens, Expressions and Control Structures

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each).

Object-Oriented Principles and Practice / C++

! 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)

Constants, References

Computer Programming

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

Chapter 2: Basic Elements of C++

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

! A data structure representing a list. ! A series of nodes chained together in sequence. ! A separate pointer (the head) points to the first

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Object-Oriented Principles and Practice / C++

Fast Introduction to Object Oriented Programming and C++

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

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

CSE au Midterm Exam Nov. 2, 2018 Sample Solution

Object-Oriented Programming

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

Transcription:

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 file Storage Management CPSC 427, Lecture 10, October 1, 2018 2/20

Brackets Example (continued from lecture 8) CPSC 427, Lecture 10, October 1, 2018 3/20

Stack class Stack class Major points: 1. T is the element type of the stack. This code implements a stack of Token. (See typedef declaration.) 2. Storage for stack is dynamically allocated in the constructor using new[] and deleted in the destructor using delete[]. 3. The copy constructor and assignment operator have been deleted to avoid double delete problems with the dynamic extension. 4. The square brackets are needed for both new and delete since the stack is an array. 5. delete[] calls the destructor of each Token on the stack. Okay here because the token destructor is null. CPSC 427, Lecture 10, October 1, 2018 4/20

Stack class Stack class (cont.) 6. push() grows stack by creating a new stack of twice the size, copying the old stack into the new, and deleting the old stack. This results in linear time for the stack operations. 7. If push() only grew the stack one slot at a time, the time would grow quadratically. CPSC 427, Lecture 10, October 1, 2018 5/20

Stack class Stack design questions 1. Should pop() return a value? 2. Why does stack have a name field? 3. size() isn t used. Should it be eliminated? 4. Stack::print() formerly declared p and pend at the top. Now they are declared just before the loop that uses them. Is this better, and why? 5. Could they be declared in the loop? What difference would it make? CPSC 427, Lecture 10, October 1, 2018 6/20

Brackets class Brackets class 1. Data member stk is dynamically allocated in the constructor and deleted in the destructor. It is an object, not an array, and does not use the []-forms of new and delete. 2. The type of stk has changed from Stack* to Stack. We can now print the stack by writing cout << stk. Formerly, we wrote stk->print(cout). 3. in.get(ch) reads the next character without skipping whitespace. There are other ways to do this as well. 4. If read is!in.good(), we break from the loop and do further tests to find the cause. 5. Old functions analyze() and mismatch() have been replaced by checkfile() and checkchar(). This largely separates the file I/O from the bracket-checking logic. CPSC 427, Lecture 10, October 1, 2018 7/20

Brackets class Brackets design questions What are the pros and cons of stk having type Stack& rather than Stack*? The old mismatch() uses the eofile argument to distinguish two different cases. void Brackets:: mismatch( const char* msg, Token tok, bool eofile ) { if (eofile) cout <<"\nmismatch at end of file: " <<msg <<endl; else cout <<"\nmismatch on line " <<lineno <<" : " <<msg <<endl; stk->print( cout ); // print stack contents if (!eofile) // print current token, if any cout <<"The current mismatching bracket is " << tok; fatal("\n"); // Call exit. } Is this a good design? CPSC 427, Lecture 10, October 1, 2018 8/20

Main file Main file 1. main() follows our usual pattern, except that it passes argc and argv on to the function run(), which handles the command line arguments. 2. run() opens the input file and passes the stream in to analyze(). 3. The istream in will not be closed if an error is thrown (except for the automatic cleanup that happens when a program exits). How might we fix the program? 4. Question: Which is better, to pass the file name or an open stream? Why? CPSC 427, Lecture 10, October 1, 2018 9/20

Storage Management CPSC 427, Lecture 10, October 1, 2018 10/20

Objects and storage Objects have several properties: A name. This is one way to access the object. A type. This determines the size and encoding of the allowable data values. A storage block. This is a block of memory big enough to hold any legal value of the specified type. A lifetime. This is the time span between an object s creation and its demise. Data left behind in an object s storage block after it has died is unpredictable and shouldn t be used. A storage class. This determines the lifetime of the object, where the storage block is located in memory, and how it is managed. CPSC 427, Lecture 10, October 1, 2018 11/20

Name An object may have one or more names, or none at all! Not all names are created equal. A name may exist but not be visible in all contexts. It is not visible from outside of the block in which it is defined. For a class data member, the name s visibility may be restricted, e.g., by the private keyword. An object may have more than one name. This is called aliasing. An object may have no name at all. Such an object is called anonymous. It can only be accessed via a pointer or subscript. CPSC 427, Lecture 10, October 1, 2018 12/20

Type of a storage object Declaration: int n = 123; This declares an object of type int, name n, and an int-sized storage block, which will be initialized to 123. It s lifetime begins when the declaration is executed and ends on exit from the enclosing block. The storage class is auto (stack). The unary operator sizeof returns the storage size (in bytes). sizeof can take either an expression or a parentheses-enclosed type name, e.g., sizeof n or sizeof(int). In case of an expression, the size of the result type is returned, e.g., sizeof (n+2.5) returns 8, which is the size of a double on my machine. CPSC 427, Lecture 10, October 1, 2018 13/20

Storage block Every object is represented by a block of storage in memory. This memory has an internal machine address, which is not normally visible to the programmer. The size of the storage block is determined by the type of the object. CPSC 427, Lecture 10, October 1, 2018 14/20

Connecting names to objects A name can be given to an anonymous object at a later time by using a reference type. #include <iostream> using namespace std; int main() { int* p; p = new int; // Creates an anonymous int object *p = 3; // Store 3 into the anonymous object cout << *p << endl; int& x = *p; x = 4; cout << *p << " " << x << endl; } /* Output 3 4 4 */ // Give object *p the name x CPSC 427, Lecture 10, October 1, 2018 15/20

Lifetime Each object has a lifetime. The lifetime begins when the object is created or allocated. The lifetime ends when the object is deleted or deallocated. CPSC 427, Lecture 10, October 1, 2018 16/20

Storage class C++ supports three different storage classes. 1. auto objects are created by variable and parameter declarations. (This is the default.) Their visibility and lifetime is restricted to the block in which they are declared. The are deleted when control finally exits the block (as opposed to temporarily leaving via a function call). 2. new creates anonymous dynamic objects. They exist until explicitly destroyed by delete or the program terminates. 3. static objects are created and initialized at load time and exist until the program terminates. CPSC 427, Lecture 10, October 1, 2018 17/20

Dynamic extensions Recall that objects have a fixed size determined solely by the object type. A variable-sized object is modeled in C++ by an object with a dynamic extension. This object has a pointer (or reference) to a dynamically allocated object (generally an array) of the desired size. Example from stack.hpp. class Stack { private: int max = INIT_DEPTH; // Number of slots in stack. int top = 0; // Stack cursor. T* s = new T[max]; // Pointer to stack base. string name; // Print name of this stack.... CPSC 427, Lecture 10, October 1, 2018 18/20

Copying A source object can be copied to a target object of the same type. A shallow copy copies each source data member to the corresponding target data member. By default, this is done by performing a byte-wise copy of the source object s storage block to the target object s storage block, overwriting its previous contents. For objects with dynamic extensions, the pointer to the extension gets copied, not the extension itself. This causes the target to end up sharing the extension with the source, and the target s previous extension becomes inaccessible. This results in aliasing multiple pointers referring to the same object, which can cause a memory leak. A deep copy recursively copying the extensions as well. CPSC 427, Lecture 10, October 1, 2018 19/20

The double-delete problem An object with dynamic extension typically uses new in the constructor and delete in the destructor to create and free the object. When a shallow copy results in two objects sharing the same extension, then attempts will be made to delete the extension when each of the two copies of the object are deleted or go out of scope. The first delete will succeed; the second will fail since the same object cannot be deleted twice. This is called the double delete problem and is a major source of memory management errors in C++. Takeaway: Don t copy objects with dynamic extensions. CPSC 427, Lecture 10, October 1, 2018 20/20