Lecture Topics. Administrivia

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

Ch. 12: Operator Overloading

About this exam review

Fast Introduction to Object Oriented Programming and C++

Vector and Free Store (Vectors and Arrays)

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.

A Fast Review of C Essentials Part I

Chapter 5 Errors. Bjarne Stroustrup

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

Chapter 5 Errors. Hyunyoung Lee. Based on slides by Bjarne Stroustrup.

HW1 due Monday by 9:30am Assignment online, submission details to come

EL2310 Scientific Programming

Introduction to Linked Lists. Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms

Intro. Scheme Basics. scm> 5 5. scm>

Vector and Free Store (Pointers and Memory Allocation)

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

C++ for Java Programmers

Chapter 17 vector and Free Store. Bjarne Stroustrup

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

Project Compiler. CS031 TA Help Session November 28, 2011

These are notes for the third lecture; if statements and loops.

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

CS 231 Data Structures and Algorithms, Fall 2016

G52CPP C++ Programming Lecture 20

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

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

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

Introduction to C++ with content from

Part X. Advanced C ++

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

A brief introduction to C++

Let return Be Direct and explicit

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

Chapter 17 vector and Free Store

Lecture 3: C Programm

BLM2031 Structured Programming. Zeyneb KURT

C++ Programming Lecture 4 Software Engineering Group

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

Chapter 1 Getting Started

Pointers and Memory 1

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

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

Item 4: Extensible Templates: Via Inheritance or Traits?

Principles of Programming Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?

C++ Programming: Polymorphism

Pointers and References

PIC 10A Objects/Classes

04-19 Discussion Notes

Chapter 17 vector and Free Store

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

Design Patterns: State, Bridge, Visitor

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6

Introduction to Programming Using Java (98-388)

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

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

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

CS61C : Machine Structures

Object-Oriented Principles and Practice / C++

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

COMP Lecture Notes Iterative and Recursive Procedures for Strings

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

Tokens, Expressions and Control Structures

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.

C++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete.

2 ADT Programming User-defined abstract data types

COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions

STRUCTURING OF PROGRAM

QUIZ. How could we disable the automatic creation of copyconstructors

More C Pointer Dangers

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Operator overloading

Errors. Lecture 6. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture

QUIZ. How could we disable the automatic creation of copyconstructors

CS 251 Intermediate Programming Java Basics

CS 220: Introduction to Parallel Computing. Arrays. Lecture 4

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz

AIMS Embedded Systems Programming MT 2017

QUIZ. What are 3 differences between C and C++ const variables?

Lecture 2: C Programm

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Types. Type checking. Why Do We Need Type Systems? Types and Operations. What is a type? Consensus

Expressions and Casting

Homework 4. Any questions?

Chapter 2. Procedural Programming

VARIABLES AND TYPES CITS1001

Name: Username: I. 20. Section: II. p p p III. p p p p Total 100. CMSC 202 Section 06 Fall 2015

More on Functions. Lecture 7 COP 3014 Spring February 11, 2018

1 Shyam sir JAVA Notes

Instantiation of Template class

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31.

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

Object Oriented Software Design II

COSC 2P91. Bringing it all together... Week 4b. Brock University. Brock University (Week 4b) Bringing it all together... 1 / 22

Transcription:

ECE498SL Lec. Notes L8PA Lecture Topics overloading pitfalls of overloading & conversions matching an overloaded call miscellany new & delete variable declarations extensibility: philosophy vs. reality Administrivia check Lab #1 progress see web board post ok to finish by next Tuesday?

ECE498SL Lec. Notes L8P1 Pitfalls of Overloading and Conversions here s a real danger that can be hard to foresee two natural interpretations of one set of types watch out! instead, make up new names for BOTH options similar to need for explicit keyword, but no easy solution minimizing surprises caused by implicit conversions is inherently difficult Doug McIlroy, as quoted by Str, p. 227 Consider the following class MyObject friend function MyObject operator+ (MyObject& a, MyObject& b); MyObject x; What does MyObject y = x + 42; do? Does answer depend on which of the following are defined? MyObject (int num); // conversion from int to MyObject operator int (); // conversion from MyObject to int What if they re both defined? What happens if I change my answer (e.g., create the constructor after using the code for a while)? you need both functions to compile when both defined: convert x to int, add, then convert sum to MyObject Why isn t this ambiguous? Compiler can t use constructor on 42 because operator reference argument is non-const! Oops! when you add const friend operator+ (const MyObject& a, const MyObject& b); having both constructor and cast operator creates ambiguity having only constructor works fine (opposite order as before ) so: forgetting const changed both legal options and their meanings

ECE498SL Lec. Notes L8P2 Better Matching the hazards of matching No one I ve asked has ever remembered these rules, even people whose primary computer language is C++. when you think that you ve come up with something cool (i.e., subtle) using overloading likely to be hard to recognize, understand a couple of asides [not for board] I can t even make sense of the rules when I read them (p. 228); to wit, Stroustrup just said (p. 225) that he wanted to differentiate const from non-const args, and in the rules he says that such conversions don t count (and are thus ambiguous, making them illegal to ever use ); I can only guess that such oddities are the result of the slight simplification he mentions My first attempt to create a pitfall example using IBM s online version of the rules also failed; gcc is either more strict or I mis-read them. BUT: less complicated than I remember (I remember something about counting args being converted; maybe in the ARM?)

ECE498SL Lec. Notes L8P3 why is matching challenging? for starters, C s implicit conversions are NOT acyclic ( most derived? ) but Stroustrup wanted to get rid of implicit narrowing anyway yet g++ still allows narrowing, even for matching rule: pick lowest numbered match, which must be unique (or causes error) 1: no conversions (non-const to const, array name to pointer, etc.) 2: integral promotions (widening/sign removal) 3: standard conversions (int to double, derived* to base*, etc.) 4: user-defined conversions (single-arg. constructors) 5: ellipsis ( ) [See ARM for more precise version] For >1 argument, matched function must be at least as good in all arguments and better in at least one argument. a simple call stealing case [more complex examples in Lec. 7 notes] int func (char arg); // original function int answer = func (42); // code calls original function int func (int arg); // new function added later // call shown is stolen silently

ECE498SL Lec. Notes L8P4 Overloading Miscellany consider overloading array syntax (operator []) Did you think of overloading reads, writes, or both? X[i] = X[j]; left side is an L-value right side is some data type stored in X at index j implementation right side probably pretty easy (look up and return) if X is a complicated data structure, left side may be slower/harder Can you define one function (operator []) that works? not really should there be two versions of operator []? or find a workaround? example workaround (see Str. Sec. 3.7.1) use an extra data structure to hack it given class ALPHA that stores objects of class BETA create helper class ALPHA_REF containing ALPHA* and integer operator[] returns new ALPHA_REF ALPHA_REF has two operators cast operator to BETA (do the actual lookup) assignment operator from BETA (do an insertion) now X1[i] = X2[j] becomes X1.operator[] (i).operator=(x2.operator[](j).operator BETA ())

ECE498SL Lec. Notes L8P5 not all operators can be overloaded member access (. ) pointer to member function invocation (.* ) conditional expressions (?:) scope identification (::) overloading can break C s duality pointer-like objects and array-like objects not necessarily equal pointer vs. array array[10] *(array+10) pointer dereference inst->member (*inst).member inst[0].member not possible to change definitions equivalently because. can t be overloaded copying vs. constructing What s the difference between the two assignments below? ALPHA a; ALPHA b = a; // copy constructor b = a; // assignment declaration has no old version may need work to destroy previous version e.g., rehash instance in a lookup table these two are NOT equivalent in C++ default version is memberwise copy for both overriding one does NOT catch the other (other version will use default copy) compiler will NOT warn you

ECE498SL Lec. Notes L8P6 Overloading New and Delete Str. Ch. 10 discusses memory management in detail both operators can be overloaded overloading of new is fairly flexible can overload delete, but not all versions can be reached when overriding default memory management include C++ standard header #include <new> overloading operator new std::size_t argument (implicit in calls) must appear as first argument in all operator new signatures holds number of bytes needed when called array and instance allocation are distinct even by default signatures void* operator new (std::size_t size); void* operator new[] (std::size_t size); for a class ALPHA: ALPHA* a; a = new ALPHA (1, 2, 3); // operator new a = new ALPHA[10]; // operator new[] note: array allocation requires a constructor with no arguments can extend either/both versions with arbitary arguments for example operator new (std::size_t size, int region_id); other arguments are then passed to new as follows a = new(42) ALPHA (17, "potato");

ECE498SL Lec. Notes L8P7 overloading operator new (cont d) one use of extra arguments: placement want some control over location of dynamic allocation e.g., sometimes necessary to locate instances in DMA-accessible memory (low physical addresses) default placement locate at a specific place (provided as argument to new) void* operator new (std::size_t size, void* p) {return p;} exception handling header file <new> also defines an exception for allocation failure std::bad_alloc derived from std::exception versions of new discussed so far can generate exceptions void* operator new (std::size_t size) throw (std::bad_alloc); void* operator new[] (std::size_t size) throw (std::bad_alloc); notation implies that no other exceptions are thrown default versions also exist that return NULL instead header file <new> defines structure and static variable to allow pseudo-argument void* operator new (std::size_t size, const std::nothrow_t&) throw (); notation here implies that no exceptions are thrown to invoke this form, use something like a = new(std::nothrow) ALPHA (42, no exceptions );

ECE498SL Lec. Notes L8P8 [skip most of this slide in lecture; leave in notes] exception handling before exceptions some of the C++ support pre-dates the exception-handling mechanisms this support is not thread-safe, and you should generally avoid it default operator new behavior try to allocate on failure, check whether a handler has been registered for failures if so, call it and try again if not, throw an exception you can register a handler with new_handler set_new_handler (new_handler) throw (); new_handler is a pointer to a function that takes no arguments returns nothing (void) set_new_handler returns the previous handler pointer note that the default behavior keeps calling the handler if handler can t fix the allocation problem e.g., by garbage collection it must throw an exception to avoid an infinite loop again this mechanism IS NOT THREAD-SAFE your program has one global variable for the handler pointer

ECE498SL Lec. Notes L8P9 overloading operator delete gcc will let you define many versions but only two versions are usable non-array void operator delete (void* p); delete a; array void operator delete[] (void* p); delete[] a; note compiler does not check that you used the correct version it does not remember which version of new you used it allows either version of delete without warning the book rambles for a while on rationale tries to establish the difficulty for programmers to track types of allocations and use proper deallocations instead, have new record type and delete make use of it except that the array version allows exactly that type of oddity what s the real reason? probably the fact that the following are synonymous delete(a) delete a similar to people writing return (42); and thus lots of code might break to support argument-passing to delete