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

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

Basic Array Implementation Exception Safety

Exception Safety. CS 311 Data Structures and Algorithms Lecture Slides Wednesday, October 28, Glenn G. Chappell. continued

Allocation & Efficiency Generic Containers Notes on Assignment 5

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

Intermediate Programming, Spring 2017*

Short Notes of CS201

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

7.1 Optional Parameters

CS201 - Introduction to Programming Glossary By

CS24 Week 3 Lecture 1

Object-Oriented Principles and Practice / C++

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

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

G52CPP C++ Programming Lecture 13

Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370

CPSC 427: Object-Oriented Programming

Operator overloading

CS201 Some Important Definitions

G52CPP C++ Programming Lecture 20

Fast Introduction to Object Oriented Programming and C++

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.

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Binary Search Trees Treesort

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CA341 - Comparative Programming Languages

Homework 4. Any questions?

CS

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

CSC 210, Exam Two Section February 1999

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

CS304 Object Oriented Programming Final Term

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

CS201 Latest Solved MCQs

Software Design and Analysis for Engineers

Come and join us at WebLyceum

Ch. 12: Operator Overloading

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!

EL2310 Scientific Programming

CS201- Introduction to Programming Current Quizzes

Recursive Search with Backtracking

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

CS250 Final Review Questions

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

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

III. Classes (Chap. 3)

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

Object-Oriented Programming

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

C++ (Non for C Programmer) (BT307) 40 Hours

Financial computing with C++

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

CSE 303: Concepts and Tools for Software Development

A brief introduction to C++

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

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

Reminder: compiling & linking

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

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Absolute C++ Walter Savitch

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

CS 247: Software Engineering Principles. ADT Design

nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n

Lecture 15a Persistent Memory & Shared Pointers

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

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

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

Programming, numerics and optimization


A <Basic> C++ Course

Collected By Anonymous

Prefix Trees Tables in Practice

CSCI 102L - Data Structures Midterm Exam #1 Fall 2011

A <Basic> C++ Course

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

Week 8: Operator overloading

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

PIC10B/1 Winter 2014 Exam I Study Guide

Object-Oriented Principles and Practice / C++

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

Pointers. Developed By Ms. K.M.Sanghavi

Chapter 13: Copy Control. Overview. Overview. Overview

PIC 10A Objects/Classes

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard

CS93SI Handout 04 Spring 2006 Apr Review Answers

ComS 228 Exam 1. September 27, 2004

Assignment of Structs

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

EL2310 Scientific Programming

Advanced Systems Programming

CPSC 427: Object-Oriented Programming

Smart Pointers. Some slides from Internet

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

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

Assertions and Exceptions

Review for Test 1 (Chapter 1-5)

G52CPP C++ Programming Lecture 16

Transcription:

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks CHAPPELLG@member.ams.org 2005 2009 Glenn G. Chappell

Unit Overview Advanced C++ & Software Engineering Concepts Major Topics: Advanced C++ Parameter passing (part) The structure of a package Operator overloading Silently written & called functions Pointers & dynamic allocation Managing resources in a class Templates Containers & iterators Error handling Introduction to exceptions Introduction to Linked Lists Major Topics: S.E. Concepts Abstraction Invariants Testing Some principles 11 Sep 2009 CS 311 Fall 2009 2

Review The Structure of a Package A client of a module is code that uses it. Type conversion: take value and return value of another type. Implicit: double d = 4.5 + 3; Explicit: double d = 4.5 + double(3); No conversion: double d = 4.5 + 3.0; 3 has type int. To add 3 to 4.5 (which has type double), we must use a type conversion to get a double. 3.0, on the other hand, has type double. 11 Sep 2009 CS 311 Fall 2009 3

Review Software Engineering Concepts: Abstraction [1/2] Abstraction: Separate the purpose of a module from its implementation. Functional abstraction Data abstraction Recall: Function, class, or other unit of code. Generally smaller than a package. Client Module Client Client Interface (defined by the specification) Implementation (hidden from clients and not part of the abstraction) Key term: Abstract Data Type An abstract data type (ADT) is a collection of data and a set of operations on the data. The implementation is not specified. ADTs will be a major topic of this course. 11 Sep 2009 CS 311 Fall 2009 4

Review Software Engineering Concepts: Abstraction [2/2] void printintarray(const int arr[], std::size_t size) { for (std::size_t i = 0; i < size; ++i) std::cout << arr[i] << " "; std::cout << std::endl; } (Functional) abstraction Function printintarray is given an array of ints called arr and a size_t called size. It executes a for loop in which local size_t variable i is initialized to 0, the loop continues as long as i < size evaluates to true, and i is pre-incremented after each loop iteration. Inside the loop, a reference to an item in array arr is retrieved using the bracket operator, with parameter i, and then inserted in cout (using overloaded operator<<), followed by an array of chars containing a blank and a null. After the loop, stream manipulator endl is inserted in cout. The function then terminates. Describe this function, in detail. Function printintarray prints an array of ints to cout, given the array and its size. Items are separated by blanks, and followed by a blank and a newline. 11 Sep 2009 CS 311 Fall 2009 5

Review Parameter Passing [1/2] By value By reference By referenceto-const Makes a copy YES * NO NO Allows for polymorphism NO * YES YES Allows passing of const values YES NO ** YES Allows implicit type conversions YES NO YES *These are problems when we pass objects. **Maybe this is bad. When we want to send changes back to the client (which is a big reason for passing by reference), disallowing const values is a good thing. So, for most purposes, when we pass objects, reference-to-const combines the best features of the other two methods. 11 Sep 2009 CS 311 Fall 2009 6

Review Parameter Passing [2/2] We pass parameters by reference when we want to modify the client s copy. void addthree(int & theint) { theint += 3; } Otherwise, we generally pass: simple types by value. objects by reference-to-const. void func(double d, const MyClass & q); We usually return by value, unless we return an object not local to this function. Return by reference if we return a pre-existing object for the client to modify. Return by reference-to-const if we return a pre-existing object that the client should not modify (in particular, if the object is const). int & arraylookup(int thearray[], int index); const int & arraylookup(const int thearray[], int index); 11 Sep 2009 CS 311 Fall 2009 7

Review Operator Overloading Operators can be implemented using global or member functions. Global: the parameters are the operands. Member: first operand is *this, the rest are parameters. Postfix increment & decrement (n++, n--) get a dummy int parameter, to distinguish them from the prefix versions (++n, --n). Implement an operator using a member function, unless you have a good reason not to. Good Reason #1: To allow for implicit type conversions on the first argument. Applies to: non-modifying arithmetic, comparison, and bitwise operators. For example: + - * / % ==!= < <= > >= Good Reason #2: When you cannot make it a member, because it would have to be a member of a class you cannot modify. Quintessential examples: stream insertion (<<) and extraction (>>). We usually use operators only for operations that happen quickly. One exception: Assignment for container types. 11 Sep 2009 CS 311 Fall 2009 8

Software Engineering Concepts: Invariants Basics [1/2] An invariant is a condition that is always true at a particular point in an algorithm. Example Suppose that myarray is an array of int s with size myarraysize. We wish to set the variable myitem equal to myarray[i], if possible. if (i < 0) { errormessage("error: i is too small"); return; } // Invariant: i >= 0 if (i >= myarraysize) { errormessage("error: i is too large"); return; } // Invariant: (i >= 0) && (i < myarraysize) myitem = myarray[i]; 11 Sep 2009 CS 311 Fall 2009 9

Software Engineering Concepts: Invariants Basics [2/2] We use invariants: To ensure that we are allowed to perform various operations. To remind ourselves of the information that is implicitly known in a program. To document ways in which code can be used. To help us verify that our programs are correct. 11 Sep 2009 CS 311 Fall 2009 10

Software Engineering Concepts: Invariants Pre & Post [1/3] We are particularly interested in two special kinds of invariants: preconditions and postconditions. A precondition is an invariant at the beginning of a function. The responsibility for making sure the precondition is true rests with the calling code. In practice, a precondition states what must be true for the function to execute properly. A postcondition is an invariant at the end of a function. It tells what services the function has performed for the client code. The responsibility for making sure the postcondition is true rests with the function itself. In practice, postconditions describe the function s effect using statements about objects & values. 11 Sep 2009 CS 311 Fall 2009 11

Software Engineering Concepts: Invariants Pre & Post [2/3] Preconditions and postconditions are the basis of operation contracts. We think of a function call as the carrying out of a contract. The function says to the caller, If you do this [preconditions], then I will do this [postconditions]. If the preconditions are met, then the function is required to make the postconditions true upon its (normal) termination. We consider abnormal termination (exceptions) later. If the preconditions are not met, then the function can be considered to have no responsibilities. Punch Line In this class, we write preconditions and postconditions for every function you write (except, possibly, main). See the Coding Standards. 11 Sep 2009 CS 311 Fall 2009 12

Software Engineering Concepts: Invariants Pre & Post [3/3] Example Write reasonable pre- and postconditions for the following function, which is supposed to store the number 7 in the provided memory. // store7 // Pre: ptr points to a block of memory large // enough to hold an int. // Post: *ptr == 7. void store7(int * ptr) { } *ptr = 7; Postconditions: Describe the function s effect using statements about objects & values. Preconditions: What must be true for the function to execute properly? 11 Sep 2009 CS 311 Fall 2009 13

Software Engineering Concepts: Invariants Class Invariants [1/4] Another important kind of invariant is a class invariant. A class invariant is an invariant that holds whenever an object of the class exists, and execution is not in the middle of a public member function call. Class invariants are true here Constructor Member Func. Member Func. Destructor Class invariants are preconditions of every public member function, except constructors. Class invariants are postconditions for every public member function, except the destructor. Since we know this, you do not need to list class invariants in the pre- and postcondition lists of public member functions. In practice, class invariants are statements about data members that indicate what it means for an object to be valid or usable. 11 Sep 2009 CS 311 Fall 2009 14

Software Engineering Concepts: Invariants Class Invariants [2/4] Write reasonable class invariants for the following class. // class Date // Invariants: // 1 <= mo_ <= 12 Class invariants: statements about data members that indicate what it means for an object to be valid or usable. // 1 <= day_ <= k, where k is no. of days in month mo_ class Date { // Date: public functions public: [Lots of code goes here] // Date: data members private: int mo_; // Month 1..12 int day_; // Day 1..#days in month given by mo_ }; // End class Date 11 Sep 2009 CS 311 Fall 2009 15

Software Engineering Concepts: Invariants Class Invariants [3/4] Think about dynamic allocation. In C, we do: Foo * p = (Foo *)malloc(100 * sizeof(foo)); In C++, we prefer: Foo * p = new Foo[100]; Why? Yes, it s simpler and cleaner. What other reasons are there? Hint: The two lines of code above do not do the same thing. Another hint: We re discussing invariants. See the next slide. 11 Sep 2009 CS 311 Fall 2009 16

Software Engineering Concepts: Invariants Class Invariants [4/4] In C++, using new calls a constructor, thus ensuring that class invariants are true. With Constructor & Destructor Class invariants are true here Constructor Member Func. Member Func. Destructor Without Constructor & Destructor Are class invariants true here? Maybe not Member Func. Member Func. The job of a constructor is to make the class invariants true. 11 Sep 2009 CS 311 Fall 2009 17

Review Silently Written & Called Functions [1/2] C++ will silently write four important member functions: When Default ctor. Copy ctor. Copy assignment. Dctor. The default ctor is silently written when you declare no ctors. The other three are silently written when you do not declare them. The silently written versions: Are public. The Big Three Call the corresponding functions for all data members. 11 Sep 2009 CS 311 Fall 2009 18

Review Silently Written & Called Functions [2/2] Some of these can be silently called as well. The default ctor is called when you declare a variable with no ctor parameters, and when you declare an array (or, generally, any container holding already initialized objects). The copy ctor is called when you pass by value and maybe when you return by value. The dctor is called: On an automatic (local, non-static) object when it goes out of scope. On a static object when the program ends. On a non-static member object when the object it is a member of is destroyed. On a dynamic object when you delete a pointer to it. 11 Sep 2009 CS 311 Fall 2009 19

Silently Written & Called Functions Commenting Them continued Silently written functions are good. Do not waste effort. If the compiler will write a perfectly good function for you, then do not write it yourself. So, use them often. And when you do, indicate this in a comment. This is a reminder that these functions exist and are part of the class design. class Aardvark { public: // Default ctor // Pre: None. // Post: None. Aardvark(); // Compiler-generated copy ctor, copy assn, dctor are used. 11 Sep 2009 CS 311 Fall 2009 20

Silently Written & Called Functions When to Write Them? When should you write these functions yourself? When you need them, but they are not written for you. When the silently written ones do not do what you want. class Llama { private: int * p; Should the copy ctor just copy p (shallow copy) or should it also copy the memory that p points to (deep copy)? The answer depends on what p is for. The silently written copy ctor does a shallow copy. The Law of the Big Three If you need to declare one of the Big Three (copy ctor, copy assignment, dctor), then you probably need to declare all of them. This tends to happen when the class manages a resource (for example, dynamically allocated memory, an open file, etc.). More on this soon. 11 Sep 2009 CS 311 Fall 2009 21

Silently Written & Called Functions Eliminating Them [1/2] We have covered: What the compiler writes for you. How & when to replace these with your own versions. But sometimes we want to eliminate these functions. Why would we want this? Most common reason: making objects uncopyable. This allows us to put strong controls on the creation and destruction of such objects. It also disallows passing by value. So, how do we eliminate the copy ctor and copy assignment? If we do not write them, then the compiler will, right? If we do write them, then they exist, right? define declare Thus: declare them, but do not define them. But what if someone else defines them 11 Sep 2009 CS 311 Fall 2009 22

Silently Written & Called Functions Eliminating Them [2/2] How do we eliminate the copy ctor and copy assignment? Declare the copy ctor and copy assignment private. Do not define them. class Mule { private: // Uncopyable class. // Private copy ctor, copy assn. Do not define these. Mule(const Mule &); Mule & operator=(const Mule &); Now no one can call these functions. You (the class author) cannot accidentally call them, because you did not define them. Client code can define them, but that does not matter; they cannot call them, because they are private. 11 Sep 2009 CS 311 Fall 2009 23

Simple Class Example Write It! TO DO Write a simple class that stores and handles a time of day, in seconds. Call it TimeSec. Give it reasonable ctors, etc. Can we use silently written functions? Yes, for the Big Three. We will write our own default ctor. Give it reasonable operators. Like what? Pre & post ++, --. Equality & inequality: ==,!=. Stream insertion: <<. Note: It would be reasonable to add more. We will not, but only due to time constraints. Partially done. See timesec.h, timesec.cpp, on the web page. 11 Sep 2009 CS 311 Fall 2009 24

Simple Class Example TO BE CONTINUED Simple Class Example will be continued next time. 11 Sep 2009 CS 311 Fall 2009 25