Advanced Object Oriented Programming ( 고급객체지향프로그래밍 ) Lecture Notes developed...

33
Advanced Object Oriented Advanced Object Oriented Programming Programming ( ( 고고고고고고고고고고고 고고고고고고고고고고고 ) ) Lecture Notes developed by Brian J. d’Auriol, permission to use material granted for non-profit, academic use, provided credit is explicitly given; all other use must request prior permission from the author. Brian J. d’Auriol Brian J. d’Auriol Dept. Computer Engineering Dept. Computer Engineering Kyung Hee University, Korea Kyung Hee University, Korea Fall 2011 Fall 2011

Transcript of Advanced Object Oriented Programming ( 고급객체지향프로그래밍 ) Lecture Notes developed...

Advanced Object Oriented Advanced Object Oriented Programming Programming

(( 고급객체지향프로그래밍고급객체지향프로그래밍 ))

Lecture Notes developed by Brian J. d’Auriol, permission to use material granted for non-profit, academic use, provided credit is explicitly given; all other use must request prior permission from the author.

Brian J. d’AuriolBrian J. d’Auriol

Dept. Computer Engineering Dept. Computer Engineering

Kyung Hee University, KoreaKyung Hee University, KoreaFall 2011Fall 2011

Compilation & VariablesCompilation & Variables

Slide Slide 33

AcknowledgementsAcknowledgements

Lecture Notes developed by Brian J. d’Auriol, Lecture Notes developed by Brian J. d’Auriol, permission to use material granted for non-profit, permission to use material granted for non-profit, academic use, provided credit is explicitly given; academic use, provided credit is explicitly given; all other use must request prior permission from all other use must request prior permission from the author.the author.

Presentation contains additional copyrighted Presentation contains additional copyrighted images used herein for purposes of academic images used herein for purposes of academic teaching; all such copyrighted material retains teaching; all such copyrighted material retains the original copyright terms. the original copyright terms.

Slide Slide 44

Language AbstractionsLanguage AbstractionsC

Pointers, direct memory access

Abstract Data Types

Uses file-encapsulation

Pass by value only

Organize functions into objects. Objects code

interfaces and program files (.c) code functions. Use object scope to control public /private

access. Use UML for s/w design.

C++

Objects

Pass by value or by reference

Language constructs (if, for, while, case, etc.)

Organize execution code fragments into functions.

Organize functions into files. Header file (.h) code interfaces,

and program files (.c) code functions. Use file scope and

internal linkage to control public /private access. Use

structure charts for s/w design.

Slide Slide 55

Compilation ProcessCompilation Process

Pre-processor

Compiler

linker

Loader

Header.h

file1.cpp file2.cpp

Pre-processor

Compiler

file1.o file2.o

GlobalDeclarationsneeded byLibraries#include

SpecialProcessingDirectives

#ifndef,#define

run.exe

Load into computer memory

Low-level and frequent functions

Lib1.lib

InternalLinkage:

Variables can only be

accessed in file1.o

External Linkage: Variables can be accessed by any .o file

Programexecution

Slide Slide 66

Compilation ProcessCompilation Process

Pre-processor

Compiler

linker

Loader

file1.cpp

file1.o

run.exe

Global Variables are managed by the compiler and allocated by the compiler, during compile time and are stored in the same area of memory as the program

Local Variables are managed by the compiler and allocated during execution time, and are stored on the system stack.

Programexecution

Slide Slide 77

Variable PropertiesVariable Properties

variable

ScopeDataType

LinkageIdentifier

Int *

double

char file

block

internal

external

Global variables: have file scope, internal linkage

Local variables: have block scope, internal linkage

Describes where the variable can be referenced in the program

Instructs the linker to make the variable accessible between independent

compiled units.

Existance

Global, local (obj: class)

Slide Slide 88

scope.cppscope.cpp#include<iostream>using namespace std;

void fnc2(void); int a=1;

void fnc1(void) {cout << "fnc1 " << a << endl;

//comment this statement out to compile program.//cout << "fnc1 " << b << endl;

}

int b=1;

int main(void) {cout << "Storage class and scoping example" << endl;cout << "main " << a << endl; cout << "main " << b << endl; fnc1();fnc2();

}void fnc2(void) {

int b = 5; cout << "fnc2 " << a << endl; cout << "fnc2 " << b << endl;

}

Global declarations: text/program segment memory, file scope, internal linkage

Local declaration, stack memory, block scope,

internal linkage

Hidden due to definition of

local b

Slide Slide 99

Declaration & DefinitionsDeclaration & Definitions#include<iostream>using namespace std;void fnc2(void); int a=1; void fnc1(void) {

cout << "fnc1 " << a << endl; }

int b=1; int main(int argc, char** argv) {

cout << "Storage …" << endl;cout << "main " << a << endl; cout << "main " << b << endl; fnc1(); fnc2();

}void fnc2(void) {

cout << b;{ int b = 5; cout << "fnc2 " << a << endl; cout << "fnc2 " << b << endl; }

}

Global DefinitionIdentifier: bDatatype: intScope: file scopeLinkage: internal

Global DeclarationIdentifier: fnc2Datatype: function prototypeScope: file scopeLinkage: internal

Global DefinitionIdentifier: aDatatype: intScope: file scopeLinkage: internal

Local DefinitionIdentifier: bDatatype: intScope: block scopeLinkage: internal

Local DefinitionIdentifier: argvDatatype: char**Scope: block (function) scopeLinkage: internal

Slide Slide 1010

Compiler and Execution Compiler and Execution SpecificationSpecification#include<iostream>

using namespace std;void fnc2(void); int a=1; void fnc1(void) {

cout << "fnc1 " << a << endl; }

int b=1; int main(int argc, char** argv) {

cout << "Storage …" << endl;cout << "main " << a << endl; cout << "main " << b << endl; fnc1(); fnc2();

}void fnc2(void) {

cout << b;{ int b = 5; cout << "fnc2 " << a << endl; cout << "fnc2 " << b << endl; }

}

Compiler specification: tells the compiler information about the program: includes scoping, datatype, identifier, linkage, and type of memory allocation.

Compiler specification: tells the compiler to insert code into the runtime (executable) program, mainly for parameter passing and memory allocation.

Execution specification: tells the computer machine to perform operations.

Memory AllocationMemory Allocation

Slide Slide 1212

Data StorageData Storage

ExternalStorage

(disk, tape) Memory

Processor(cache,

registers)

Text Segment(program)

HeapStack

The Operating System loads the object

program into text segment memory. This

memory persists for the entire duration of

the program’s execution.

The Operating System manages a part of memory

as a stack. The stack persists while the

operating system is executing. Programs allocate stack frames.

Stack frames persist for limited duration

The Operating System manages a part of memory as a heap. Heap space can be allocated and freed by

program statements.

Slide Slide 1313

Data StorageData Storage

Memory

Text Segment(program)

HeapStack

Managed by the compiler Managed by the programmer

Programmer specifies:Declaration: description of the storageDefinition: allocation of the storage(A definition is also a declaration)

(global variables) (local variables)

Slide Slide 1414

Memory Allocations (Unix)Memory Allocations (Unix)

OS kernel

Textsegment

data

BSS(unitialized data)

(initialized data)

stack

heap

program

Global variables, static variables

Takes space in .exe disk file

Dynamic allocation (malloc/free, new/delete)

Local variables, function parameters, additional function-related information

(e.g. return address pointer)

Acquired 1

Acquired 2

Acquired 3

Acquired 1

Acquired 3

releasedProblem:

fragmented memory

Frame 1 Frame 1

Frame 2

Frame 1

pushpop

push

Slide Slide 1515

Memory Allocations (Unix)Memory Allocations (Unix)

OS kernel

Textsegment

data

BSS(unitialized data)

(initialized data)

stack

heap

program

Global variables, static variables

Takes space in .exe disk file

Dynamic allocation (malloc/free, new/delete)

Local variables, function parameters, additional function-related information

(e.g. return address pointer)

Frame 1 Frame 1

Frame 2

Frame 1

pushpop

Acquired 1

Acquired 2

Acquired 3

Acquired 1

Acquired 3

releasedProblem:

fragmented memory

Slide Slide 1616

Memory Allocations (Unix)Memory Allocations (Unix)

OS kernel

Textsegment

data

BSS(unitialized data)

(initialized data)

program

Global variables, static variables

Takes space in .exe disk file

char x[1000000];int main (void){ }

memalloc1.c

char x[1000000]={'x'};int main (void){ }

memalloc2.c

-rwxr-xr-x 1 admin None 7691 Sep 16 14:03 memalloc1.exe

-rwxr-xr-x 1 admin None 1008651 Sep 16 14:03 memalloc2.exe

text data bss dec hex filename 912 368 1000064 1001344 f4780 memalloc1.exe 912 1000368 64 1001344 f4780 memalloc2.exe

Memory Layout

Disk Size

File OrganizationFile Organization

Slide Slide 1818

Source: http://cplusplus.com

IOstream Class HierarchyIOstream Class Hierarchy

Classes describe the logical

organization of data+programming

Objects are an instance of a class

therefore represents data and methods

defined for that data

Slide Slide 1919

Source: http://cplusplus.com

IOstream Class HierarchyIOstream Class Hierarchy

Slide Slide 2020

File OrganizationFile Organization

File stream (character by character)

White space charactersblank: ‘ ‘tab: ‘\t’

newline: ‘\n’

Use >> to extract tokens (words) separated by white space characters

End of file character

Use get to extract single characters

Use getline to extract lines separated by newline characters

Slide Slide 2121

File Input / OutputFile Input / Output

File stream (character by character)

White space charactersblank: ‘ ‘tab: ‘\t’

newline: ‘\n’

Use >> to extract tokens (words) separated by white space characters

End of file character

Use get to extract single characters

Use getline to extract lines separated by newline characters

All file input / output can generate errors: e.g. file is not opened; file does not exist, bad format (reading ints but the file contains non-ints)

Slide Slide 2222

File Input / OutputFile Input / Output

File stream (character by character)

Use >> to extract tokens (words) separated by white space characters

End of file character

Use get to extract single characters

Use getline to extract lines separated by newline characters

All file input / output can generate errors: e.g. file is not opened; file does not exist, bad format (reading ints but the file contains non-ints)

Two (2) ways to handle errors:1. use the file state flags (programmer has control over the file input/output)2. Use exception handling (programmer does not have control)

Slide Slide 2323

File Input / OutputFile Input / Output

ifstream file;

file.open(“filename.txt”);

char c;

while (!file.eof()) {

c = file.get();

}

1 2 . 43

Read one character (byte) at a time.

C

1

2

.

4

3

Slide Slide 2424

File Input / OutputFile Input / Output

File read attempts to read a char, but it is already past end of file

ifstream file;

file.open(“filename.txt”);

char c;

while (!file.eof()) {

c = file.get();

}

1 2 . 43

Read one character (byte) at a time.

eofbit is set

failbit is set

No valid character is read, therefore

Possibly some wrong character is returned.Therefore, need to check

the error status after the get()

NOTE: eofbit and failbit are set for different conditions of the file.

C

1

2

.

4

3

?

Slide Slide 2525

#include <iostream> #include <fstream> using namespace std; int main () { char c; ifstream is; is.open (“filename”);

while (is.good()){

c = is.get(); if (is.good()) cout << c; } is.close(); return 0; }

File State Error HandlingFile State Error HandlingRead input file character by character until end of file.

Source: http://cplusplus.com

By default, cout is connected to the monitor, therefore, in most cases, little chance of error (but if re-directing, then must check for errors)

No return value, error sets the fail bit.

“The function returns true if none of the stream's error flags (eofbit, failbit and badbit) are set.”

No return value, errors set• Eof: end of file detected (note: eof detected

because file read is now beyond end of file)• Fail: unusual (may be caused by eof, or the

streambuf overloaded functions)• Bad: any other error.

Slide Slide 2626

#include <iostream> #include <fstream> using namespace std; int main(void) { string s; ifstream f("input.txt"); if (!f) { // process error } else { while (!f.eof()) { f >> s; if (! (f.fail() || f.bad() )){ // process input } } } }

File State Error HandlingFile State Error HandlingRead input file token by token (words) until end of file.

No return value, error sets the fail bit. This is the evaluate stream object function (NOT the boolean not operator), the function returns true if the fail or bad bit is set

No return value, errors set• Eof: end of file detected (note: eof detected if end

of file marker is processed during the reading of valid data.

• Fail: format error (may be caused by eof)• Bad: any other error.

Process the file until end of file is detected.

Must check if >> resulted in fail or bad state: note, eof could be set even if valid data is obtained.

Slide Slide 2727

#include <iostream> #include <fstream> using namespace std; int main(void) { string s; ifstream f("input.txt"); if (!f) { // process error } else { while (!f.eof()) { f >> s; if (! (f.fail() || f.bad() )){ // process input } } } }

File State Error HandlingFile State Error HandlingRead input file token by token (words) until end of file.

No return value, error sets the fail bit. This is the evaluate stream object function (NOT the boolean not operator), the function returns true if the fail or bad bit is set

No return value, errors set• Eof: end of file detected (note: eof detected if end

of file marker is processed during the reading of valid data.

• Fail: format error (may be caused by eof)• Bad: any other error.

Process the file until end of file is detected.

Must check if >> resulted in fail or bad state: note, eof could be set even if valid data is obtained.Not needed as fail() checks

fail and bad bit

Slide Slide 2828

#include <iostream> #include <fstream> using namespace std; int main(void) { string s; ifstream f("input.txt"); if (!f) { // process error } else { while (!f.eof()) { if ( f >> s ) { // process input } } } }

File State Error HandlingFile State Error HandlingRead input file token by token (words) until end of file.

No return value, errors set• Eof: end of file detected (note: eof

detected if end of file marker is processed during the reading of valid data.

• Fail: format error (may be caused by eof)• Bad: any other error.

Must check if >> resulted in fail or bad state: note, eof could be set even if valid data is obtained.

Note: >> returns (*this), so: ! (f >> s ) performs evaluate stream object function, therefore !( !(f>>s))

performs the boolean not operation on the result of the evaluate stream

object function.

if ( !(!(f >> s)) ) {

Slide Slide 2929

#include <iostream> #include <fstream> using namespace std; int main(void) { string s; ifstream f("input.txt"); if (!f) { // process error } else { while (!f.eof()) { if ( f >> s ) { // process input } } } }

File State Error HandlingFile State Error HandlingRead input file token by token (words) until end of file.

No return value, errors set• Eof: end of file detected (note: eof

detected if end of file marker is processed during the reading of valid data.

• Fail: format error (may be caused by eof)• Bad: any other error.

Must check if >> resulted in fail or bad state: note, eof could be set even if valid data is obtained.

Note: >> returns (*this), so: If (f >> s ) is a conditional expression applied to the file object: this situation is identified by the compiler as a type conversion requirement, i.e., the compiler will convert the (*this) object into a boolean value where a NULL value is false and NOT NULL is true - this works since >> returns NULL if no valid input is obtained. NOTE: this method does not check the file state flags.

Slide Slide 3030

File Exception HandlingFile Exception Handling

ifstream file; file.exceptions ( ifstream::eofbit | ifstream::failbit | ifstream::badbit ); try { file.open ("test.txt"); while (!file.eof()) file.get(); } catch (ifstream::failure e) { cout << "Exception opening/reading file"; }

Exceptions are based on the file status flags (bits).

Need to set a mask (a set of bits) to specify what exceptions are to be thrown

This sets all exceptions.

Can set fail bitCan set fail and eof bits

Should check file status bits

Source: http://cplusplus.com

Slide Slide 3131

#include <iostream> #include <fstream> using namespace std; int main () { char c; ifstream file; file.exceptions ( ifstream::eofbit | ifstream::failbit | ifstream::badbit ); try { file.open ("input.txt"); while (!file.eof()) { c = file.get(); cout << c; } } catch (ifstream::failure e) { cout << "Exception opening/reading file\n"; cout << e.what() << endl; if (file.good()) cerr << "good, "; if (file.eof()) cerr << "eof, "; if (file.fail()) cerr << "fail, "; if (file.bad()) cerr << "bad. "; cout << endl; exit(1); } file.close(); return 0; }

File Exception HandlingFile Exception Handling

This sets all exceptions.

Can set fail and eof bits

Should check file status bits

Source: http://cplusplus.com

Normal end of file processing

Output Filea1 a2 a3 Exception opening/reading file basic_ios::clear eof, fail,

a1 a2 a3

Input File

Object Static DefinitionObject Static Definition

Slide Slide 3333

Static Storage Class: GlobalStatic Storage Class: Global// static members in classes#include <iostream>using namespace std;

class CDummy { public: static int n; CDummy () { n++; }; ~CDummy () { n--; };};

int CDummy::n=0;

int main () { CDummy a; CDummy b[5]; CDummy * c = new CDummy; cout << a.n << endl; delete c; cout << CDummy::n << endl; return 0;}

Inline functions: for efficiency / speed

Static class variable declaration (global variable, class scope)

Constructor / destructor: counts number of objects created

7

6

Source: http://cplusplus.com/doc/tutorial/classes2/

Static class variable definition (compile-time initialization)Exists before the program

executes.

Constructors can not be used to

initialize

Compiler must be directed to initialize