CS3157: Advanced Programming Lecture #7 June 18 Shlomo Hershkop - - PowerPoint PPT Presentation

cs3157 advanced programming
SMART_READER_LITE
LIVE PREVIEW

CS3157: Advanced Programming Lecture #7 June 18 Shlomo Hershkop - - PowerPoint PPT Presentation

CS3157: Advanced Programming Lecture #7 June 18 Shlomo Hershkop shlomo@cs.columbia.edu 1 Overview More C++ Overloading Classes and hierarchies Software engineering 2 Announcements Remember to submit the code from last


slide-1
SLIDE 1

1

CS3157: Advanced Programming

Lecture #7 June 18

Shlomo Hershkop shlomo@cs.columbia.edu

slide-2
SLIDE 2

2

Overview

More C++

Overloading Classes and hierarchies Software engineering

slide-3
SLIDE 3

3

Announcements

Remember to submit the code from last

Monday tonight as the lab

slide-4
SLIDE 4

4

CPP classes

A class if a collection of functions and

variables

In CPP we also have special functions

called constructors and destructors

Need to understand how to design and

then code classes….think of objects first..

slide-5
SLIDE 5

5

Counting

Say you want to create a counting object,

example a web counter of visitors..

What do you need ?

slide-6
SLIDE 6

6

Simple version I

class Counter { public: int x; void print() { cout << x <<endl; } };

slide-7
SLIDE 7

7

Simple version I b

class Counter { public: int x; void print(); } }; void Counter::print(){ cout<< x <<endl; }

slide-8
SLIDE 8

8

accessing variables

Count mycounter; mycounter.x = 7; mycounter.print(); Counter *countPTR; countPTR = new Count; counterPTR->print();

slide-9
SLIDE 9

9

abstraction

Anyone can program (well almost) Important to use planning when writing code When you define a class separate how to use

the class and how to represent the information in the class

i.e. what belongs in private/public

slide-10
SLIDE 10

10

#include<iostream> using namespace std; int globalcounter = 0; class Counter{ private: int x; public: Counter (){ x = globalcounter++; cout<<"in the cnst "<<x<<endl; } void print() { cout << x <<endl; } ~Counter(){cout<<"in dest for "<<x<<endl;} }; int main(int argc, int *argv){ cout<<"this is a test of counter class"<<endl; Counter c1; Counter *c2; c2 = new Counter; //notice new return 0; }

slide-11
SLIDE 11

11

idea

Since local variable can be changed add a static member ID

Instead of global variable

int Foo::ID = 0;

in global scope of class

slide-12
SLIDE 12

12

Hands on Coding

  • For lab will be coding a fraction class
  • main will look something like:

int main(void) { cout<<“start”<<endl; Fraction f1; cout<<“End”<<endl; return 0; }

  • As we did last week, printout out in the constructor and dest can show you

how things are being manipulated in the memory space..

slide-13
SLIDE 13

13

Remember from last time..

add constructor/destructor add print to them and see what it outputs add a global fraction now add a pointer to a fraction

what happened to the destructor ?

slide-14
SLIDE 14

14

Question on coding

what if we wanted to keep roman

numerals as a counter ?

How robust is your code to this ?? What would the class functions look like ?

slide-15
SLIDE 15

15

Example II

class Counter { private: char * x; char * convertInt(int number); public: Counter() { … } ~Counter { … } void setCount(int newcnt) { x = convertInt(x); } void print() { cout << x <<endl; } }

slide-16
SLIDE 16

16

Implicit assignment

If you don’t define an assignment operator

Will try to figure out how do to it By looking at each field member variable Works with primitives Pointers will get shallow copied

Counter a; Counter b; a.setCount(19); b = a; b.print();

slide-17
SLIDE 17

17

Reminder Constructors

In C++ a class has a default constructor only if

you don’t define any class Example1 { public: int a,b,c; void multiply (int n, int m) { a=n; b=m; c=a*b; }; };

slide-18
SLIDE 18

18

Example

So can say

Example1 ex;

Which will create a constructor for you As soon as you define any constructor (say

taking one arg) the above line stops working

Blame the compiler

slide-19
SLIDE 19

19

surprise

By default Compiler will create

copy constructor copy assignment operator default destructor.

slide-20
SLIDE 20

20

Differences

Should understand the difference between X *X &X X.Y X->Y (*X).Y

slide-21
SLIDE 21

21

friendship

Functions (which you’ve seen) and

classes which can access private class members

So you’ve friend functions for overloading’ Here is an example of friend class

slide-22
SLIDE 22

22

// friend class #include <iostream> using namespace std; class CSquare; class CRectangle { int width, height; public: int area () {return (width * height);} void convert (CSquare a); }; class CSquare { private: int side; public: void set_side (int a) {side=a;} friend class CRectangle; }; void CRectangle::convert (CSquare a) { width = a.side; height = a.side; }

slide-23
SLIDE 23

23

int main () { CSquare sqr; CRectangle rect; sqr.set_side(4); rect.convert(sqr); cout << rect.area(); return 0; }

slide-24
SLIDE 24

24

C++ hierarchy

  • composition:

creating objects with other objects as members

  • derivation:

defining classes by expanding other classes like “extends” in java

class SortedIntArray : public IntArray { public: void sort(); private: int *sortBuf; }; // end of class SortedIntArray

  • “base class” (IntArray) and “derived class” (SortIntArray)
  • derived class can only access public or protected members of base class
slide-25
SLIDE 25

25

public derivation means that users of the derived class

can access the public portions of the base class

private derivation means that all of the base class is

inaccessible to anything outside the derived class

private is the default

slide-26
SLIDE 26

26

slide-27
SLIDE 27

27

Functions can be member or non-member, your

choice!

Non-member as friends if need private data

If its member, can use the this pointer Exception: operators (), [], -> or any

assignments must be class members

When overloading need to follow set function

signature

slide-28
SLIDE 28

28

cout

cout << yourclass left operand is ostream & so non member functions (belongs to

  • stream)

friend if you would like lets code something

slide-29
SLIDE 29

29

String class

lets define a simple string class put output in its const and dest so we can follow constructor should take const char * would like to have following defined:

int length(); int hash();

any ideas on how to do it ?

slide-30
SLIDE 30

30

  • verload printing

friend ostream & operator <<(ostream &, const String &);

  • stream &operator<<(ostream &output, String &str) {
  • utput << “’” << ???? << “’”;

return output; }

slide-31
SLIDE 31

31

note

when you call:

cout << s1 << s2;

it is first:

  • perator<<(cout,s1)

and then

  • perator<<(cout,s2)
slide-32
SLIDE 32

32

Next

want to overload the unary operator ! test if a string is blank int operator!() const;

  • r

friend int operator(const String &); !s1 s.operator!() or operator!(s)

slide-33
SLIDE 33

33

same idea

const String operator+=(const String &) vs friend const String &operator+=(Stirng &,

const String &)

what will s1 += s2 produce ?

slide-34
SLIDE 34

34

Array Class

Arrays are hard to work with directly since

there is no support for out of bounds

lets look at 18.4 from the book

slide-35
SLIDE 35

35

extending

any ideas on how to extend the base class

??

slide-36
SLIDE 36

36

so how can we tell the difference between

++s1 and s1++

slide-37
SLIDE 37

37

signatures

s1++ s1.operator++(0)

  • perator++(s1,0)
slide-38
SLIDE 38

38

++s1; s1.operator++()

  • perator++(s1)
slide-39
SLIDE 39

39

reuse

  • ne of the powers to OOP is the idea of

reuseability

if I spend 5 billion hours working on my

code, I probably want to get some use out

  • f it outside of the specific task

design issues extension issues

slide-40
SLIDE 40

40

inheritance

idea: allow a new class to inherit data

members and functions from a base class

can add members and functions represents a more specific idea vehicle -> minivan

slide-41
SLIDE 41

41

you can access protected members of

parent

can not access private members of parent

can still use public accessors and modifiers

slide-42
SLIDE 42

42

code

class IntArray: public Array {

  • simplest type of inheritance
  • private members not inherited
  • public/protected inherited accordingly
slide-43
SLIDE 43

43

code

create a point class

setPoint <<

derive Square

getArea() <<

slide-44
SLIDE 44

44

  • verriding

we can redefine a base class function in

the derived class and have c++ call the correct one

slide-45
SLIDE 45

45

Question

can Point *pp1; Square *sp1; given Point p = Point(3,4); Square s = Square(.. can we say: pp1 = s ????? sp1 = p ?????

slide-46
SLIDE 46

46

private inheritance

we have used public inheritance private inheritance makes everyone from

the base class come in as private members of the derived class

slide-47
SLIDE 47

47

base class constructors

need to launch base class constructor in

derived class if you don’t want the default to be called

destructors are reversed lets see this in action

slide-48
SLIDE 48

48

is a vs has a

  • ne important design decision is to know

when to derive and when to use member variable

slide-49
SLIDE 49

49

issue

  • ne issue with overriding, is that if the derived

class doesn’t provide a function, we will use the base class definition

this doesn’t always make sense Example I want a function MPG for any type of

vehicle, but doesn’t make sense of base class

slide-50
SLIDE 50

50

virtual functions

solution : declare the function to be virtual virtual double MPG(); allow you to use a base class pointer to call at

runtime the correct function (polymorphism)

slide-51
SLIDE 51

51

abstract class

sometimes its even useful to have a base

class which can’t be instantiated

if any virtual function is declared pure

virtual:

virtual int MPG() = 0;

slide-52
SLIDE 52

52

note

constructors can not be virtual need virtual destructors to make

everything work if you are going to have destructors in any of your classes (do it anyway)

slide-53
SLIDE 53

53

lets look at 20.1 code

slide-54
SLIDE 54

54

slide-55
SLIDE 55

55

Linkage directions

If you want to call a function in another

programming language, the compiler must be told that different rules apply

Linkage directive

Single statement Compound form

Declared outside of functions

slide-56
SLIDE 56

56

Single form

extern “C” void something(int); Keyword String Function Compiler will type check any function calls

slide-57
SLIDE 57

57

Compound form

extern “C” {

int printf(const char * …); int scanf (const char * … ); }

extern “C” {

#include <cmath> }

slide-58
SLIDE 58

58

Other languages

Depends on the compiler For example many support FORTRAN

slide-59
SLIDE 59

59

Dynamic allocation

Local variables have local life and scope If you want to dynamically create and

manage memory, use the new and delete

Using pointers Have to be careful from dangling

pointers…

Ideas?

slide-60
SLIDE 60

60

Reality check

int *p = new int (1024); int *q = new int [1024]; int (*r)[1024] = new int [4][1024];

slide-61
SLIDE 61

61

Abstraction and member functions

How are object internally manipulated by

cpp…..lets take a look at a complex example

slide-62
SLIDE 62

62

Rect

class Rect { // ... private: int top, left; int width, height; .. };

slide-63
SLIDE 63

63

Color

class Color{ // .. private: int data; };

slide-64
SLIDE 64

64

TextBox

class TextBox: public Rect{ //... private: Color txtColor; int frameThick; char *text; };

slide-65
SLIDE 65

65

main

main(){ TextBox source, dest; //... dest = source;

How to get this to work ?

slide-66
SLIDE 66

66

Overloading operator =

class TextBox : public Rect{ public: void operator=(TextBox &source); ..

slide-67
SLIDE 67

67

Equivalent

main(){ TextBox source, dest; //... dest.operator=(source);

slide-68
SLIDE 68

68

Inside

void TextBox::operator=(TextBox &source) { if(this == &source) return; Rect::operator=(source); txtColor = source.txtColor; frameThick = source.frameThick; delete []text; if(source.text != 0) { text = new char[strlen(source.text+1)]; strcpy(text,source.text); } else text = 0; }

slide-69
SLIDE 69

69

Implicit assignment

If you don’t define an assignment operator

Will try to figure out how do to it By looking at each field member variable Works with primitives Pointers will get shallow copied

Difference between

DEEP COPY SHALLOW COPY

slide-70
SLIDE 70

70

Copy constructor

TextBox t2 = t1; Looks like assignment Really a constructor call with object as argument Called copy constructor Combination of constructor and assignment

slide-71
SLIDE 71

71

Defining it

Just overload the constructor TextBox(TextBox &source); Be careful:

When you overload the copy constructor you throw

  • ut a default constructor

Which means you need to explicitly define a default

constructor (no arg)

slide-72
SLIDE 72

72

code

TextBox::TextBox(TextBox &source){ Rect::operator=(source); frameThick = source.frameThick; textColor = source.textColor; etc

slide-73
SLIDE 73

73

Chaining

If you want to be able to say

Textbox a,b,c; //… a = b = c ;

how would the operator overloaded be

different ??

slide-74
SLIDE 74

74

Exception

Like in java , CPP allows you to throw and

catch exceptions

Compiler time exceptions Run time exceptions

slide-75
SLIDE 75

75

Template programming

Allows you to specify a type to pass in to

your class, so can create a collection class to handle many different types, without having the problem if limited casting in the code

Allows you to move errors from run time to

compiler time

slide-76
SLIDE 76

76

slide-77
SLIDE 77

77

virtual functions

in C++ virtual functions allow you to define

a specific function in the base class, which is undefined, and each of the subclasses need to override (implement a definition)

virtual char * md5sum();

slide-78
SLIDE 78

78

so if we use a base class pointer at a

derived class object, calling md5sum will call the correct one

compile time resolution

static binding

slide-79
SLIDE 79

79

Abstract

virtual char * md5sum() =0; any ideas on what error will be thrown if

you instantiate it ?

slide-80
SLIDE 80

80

non virtual base functions

if you have a parent class A.foo() derived class B defines B.foo() A *a_ptr = B_object a_ptr.foo()

which foo will be triggered? why ?

slide-81
SLIDE 81

81

abstract classes II

remember that making a pointer doesn’t

instantiate anything

can create pointers of type abstract

classes

used to enable polymorphic behavior Example: Operating system device

read/write behvaior

slide-82
SLIDE 82

82

destructors

when creating and manipulating objects in

a polymorphic context, destructors will

  • nly be called on base class
slide-83
SLIDE 83

83

solution

define a virtual base class destructor will correct destructor will be called

slide-84
SLIDE 84

84

slide-85
SLIDE 85

85

Virtual functions

Allows you to declare a function in the

base class without a definition

Each of the derived class provide a

definition unique to their implementation

At runtime will allow all derived class

  • bject instances to be manipulated

uniformly

slide-86
SLIDE 86

86

Next

Software engineering

Will cover most in class, you are responsible for

understanding high level overview

slide-87
SLIDE 87

87

What is Software Engineering?

Stephen Schach: “Software engineering is a discipline whose aim is

the production of fault-free software, delivered on time and within budget, that satisfies the user’s needs.”

includes:

requirements analysis human factors functional specification software architecture design methods programming for reliability programming for maintainability team programming methods testing methods configuration management

slide-88
SLIDE 88

88

People

you can’t do everything yourself e.g., your assignment: “write an operating

system”

where do you start? what do you need to write? do you know how to write a device driver? do you know what a device driver is? should you integrate a browser into your

  • perating system?

how do you know if it’s working?

slide-89
SLIDE 89

89

Why

in school, you learn the mechanics of programming you are given the specifications you know that it is possible to write the specified

program in the time allotted

but not so in the real world...

what if the specifications are not possible? what if the time frame is not realistic? what if you had to write a program that would last for 10 years?

in the real world:

software is usually late, over budget and broken software usually lasts longer than employees or hardware

the real world is cruel and software is fundamentally

brittle

slide-90
SLIDE 90

90

Who

the average manager has no idea how software needs to

be implemented

the average customer says: “build me a system to do X” the average layperson thinks software can do anything

(or nothing)

most software ends up being used in very different ways

than how it was designed to be used

slide-91
SLIDE 91

91

Time

you never have enough time software is often under budgeted the marketing department always wants it

tomorrow

even though they don’t know how long it will take

to write it and test it

“Why can’t you add feature X? It seems so

simple...”

“I thought it would take a week...” “We’ve got to get it out next week. Hire 5 more

programmers...”

slide-92
SLIDE 92

92

Complexity

software is complex!

  • r it becomes that way

feature bloat patching

e.g., the evolution of Windows NT

NT 3.1 had 6,000,000 lines of code NT 3.5 had 9,000,000 NT 4.0 had 16,000,000 Windows 2000 has 30-60 million Windows XP has 40-45 million... Vista 50-55 million

slide-93
SLIDE 93

93

Necessity

you will need these skills! risks of faulty software include

loss of money loss of job loss of equipment loss of life

slide-94
SLIDE 94

94

Therac-25

http://sunnyday.mit.edu/papers/therac.pdf therac-25 was a linear accelerator released in 1982 for

cancer treatment by releasing limited doses of radiation

it was software-controlled as opposed to hardware-

controlled (previous versions of the equipment were hardward-controlled)

it was controlled by a PDP-11; software controlled safety in case of error, software was designed to prevent

harmful effects

slide-95
SLIDE 95

95

BUT in case of software error, cryptic codes were displayed to

the operator, such as:

“MALFUNCTION xx” Where 1 < xx < 64

  • perators became insensitive to these cryptic codes

they thought it was impossible to overdose a patient however, from 1985-1987, six patients received massive

  • verdoses of radiation and several died
slide-96
SLIDE 96

96

main cause: a race condition often happened when operators entered

data quickly, then hit the up-arrow key to correct the data and the values were not reset properly

the manufacturing company never tested quick data

entry— their testers weren’t that fast since they didn’t do data entry on a daily basis

apparently the problem had existed on earlier models,

but a hardware interlock mechanism prevented the software race condition from occurring

in this version, they took out the hardware interlock

mechanism because they trusted the software

slide-97
SLIDE 97

97

Example2: Ariane 501

  • next-generation launch vehicle, after ariane 4
  • presigious project for ESA
  • maiden flight: june 4, 1996
  • inertial reference system (IRS), written in ada
  • computed position, velocity, acceleration
  • dual redundancy
  • calibrated on launch pad
  • relibration routine runs after launch (active but not used)
  • ne step in recalibration converted floating point value of horizontal velocity to integer
  • ada automatically throws out of bounds exception if data conversion is out of bounds
  • if exception isn’t handled... IRS returns diagnostic data instead of position, velocity,

acceleration

slide-98
SLIDE 98

98

perfect launch ariane 501 flies much faster than ariane 4 horizontal velocity component goes out of bounds IRS in both main and redundant systems go into diagnostic mode control system receives diagnotic data but interprets it as wierd

position data

attempts to correct it... ka-boom! failure at altitiude of 2.5 miles 25 tons of hydrogen, 130 tons of liquid oxygen, 500 tons of solid

propellant

slide-99
SLIDE 99

99

expensive failure:

ten years $7 billion

horizontal velocity conversion was deliberately left unchecked who is to blame? “mistakes were made” software had never been tested with actual flight parameters problem was easily reproduced in simulation, after the fact

slide-100
SLIDE 100

100

Mythical man-month

Fred Brooks (1975) book written after his experiences in the OS/360 design major themes:

Brooks’ Law: “Adding manpower to a late software project makes it

later.”

the “black hole” of large project design: getting stuck and getting out

  • rganizing large team projects and communication

documentation!!! when to keep code; when to throw code away dealing with limited machine resources

most are supplemented with practical experience

slide-101
SLIDE 101

101

No silver bullet

paper written in 1986 (Brooks) “There is no single development, in either technology or

management technique, which by itself promises even one order-of magnitude improvement within a decade of productivity, in reliability, in simplicity.”

why? software is inherently complex lots of people disagreed, but there is no proof of a counter-argument Brooks’ point: there is no revolution, but there is evolution when it

comes to software development

slide-102
SLIDE 102

102

SE Mechanics

well-established techniques and

methodologies:

team structures software lifecycle / waterfall model cost and complexity planning / estimation reusability, portability, interoperability,

scalability

UML, design patterns

slide-103
SLIDE 103

103

Team Structures

why Brooks’ Law?

training time increased communications

while people/work grows by

how to divide software? this is not task sharing

types of teams

democratic “chief programmer” synchronize-and-stabilize teams eXtreme Programming teams

slide-104
SLIDE 104

104

Lifecycles

software is not a build-one-and-throw-away process that’s far too expensive so software has a lifecycle we need to implement a process so that software is

maintained correctly

examples:

build-and-fix waterfall

slide-105
SLIDE 105

105

Software lifestyle cycle

7 basic phases (Schach):

requirements (2%) specification/analysis (5%) design (6%) implementation (module coding and testing) (12%) integration (8%) maintenance (67%) retirement

percentages in ()’s are average cost of each task during 1976-1981 testing and documention should occur throughout each phase note which is the most expensive!

slide-106
SLIDE 106

106

Requirements

what are we doing, and why? need to determine what the client needs, not what the client wants

  • r thinks they need

worse— requirements are a moving target! common ways of building requirements include:

prototyping natural-language requirements document

use interviews to get information (not easy!) example: your online store

slide-107
SLIDE 107

107

Specifications

  • the “contract”— frequently a legal document
  • what the product will do, not how to do it
  • should NOT be:

ambiguous, e.g., “optimal” incomplete, e.g., omitting modules contradictory

  • detailed, to allow cost and duration estimation
  • classical vs object-oriented (OO) specification

classical: flow chart, data-flow diagram

  • bject-oriented: UML
  • example: your online store
slide-108
SLIDE 108

108

Design Phase

  • the “how” of the project
  • fills in the underlying aspects of the specification
  • design decisions last a long time!
  • even after the finished product
  • maintenance documentation
  • try to leave it open-ended
  • architectural design: decompose project into modules
  • detailed design: each module (data structures, algorithms)
  • UML can also be useful for design
  • example: your online store
slide-109
SLIDE 109

109

Implementation

  • implement the design in programming language(s)
  • bserve standardized programming mechanisms
  • testing: code review, unit testing
  • documentation: commented code, test cases
  • integration considerations

combine modules and check the whole product top-down vs bottom-up ? testing: product and acceptance testing; code review documentation: commented code, test cases done continually with implementation (can’t wait until the last minute!)

  • example: your online store
slide-110
SLIDE 110

110

Maintenance Phase

  • defined by Schach as any change
  • by far the most expensive phase
  • poor (or lost) documentation often makes the situation even worse
  • programmers hate it
  • several types:

corrective (bugs) perfective (additions to improve) adaptive (system or other underlying changes)

  • testing maintenance: regression testing (will it still work now that I’ve fixed

it?)

  • documentation: record all the changes made and why, as well as new test

cases

  • example: your on-line store— how might the system change once it’s been

implemented?

slide-111
SLIDE 111

111

Retirement phase

the last phase, of course why retire?

changes too drastic (e.g., redesign) too many dependencies (“house of cards”) no documentation hardware obsolete

true retirement rate: product no longer useful

slide-112
SLIDE 112

112

Planning and Estimation

we still need to deal with the bottom line

how much will it cost? can you stick to your estimate? how long will it take? can you stick to your estimate?

how do you measure the product (size,

complexity)?

slide-113
SLIDE 113

113

Reusability

impediments:

lack of trust logistics of reuse loss of knowledge base mismatch of features

how to:

libraries APIs system calls

  • bjects (OOP)

frameworks (a generic body into which you add your particular

code)

slide-114
SLIDE 114

114

Portability

Java and C# Java: uses a JVM

write once, run anywhere (sorta, kinda)

C#: also uses a JVM

emphasizes mobile data rather than code

winner?

betting against Microsoft is historically a losing

proposition...

slide-115
SLIDE 115

115

interoperability

e.g., CORBA define abstract services allow programs in any language to access

services in any language in any location

  • bject-ish
slide-116
SLIDE 116

116

Scalability

something to keep in mind don’t worry about scaling beyond the abilities of

the machine

avoid unnecessary barriers from single connection to forking processes to

threads...

slide-117
SLIDE 117

117

homework

Next phase of online project What if you don’t have enough time ☺ Software engineering solution ??