cs 342: object-oriented software development lab a tour ...cse870/materials/c++/c++-tour_4.pdf ·...

31
CS 342: Object-Oriented Software Development Lab A Tour Through C++ David L. Levine Christopher D. Gill Department of Computer Science Washington University, St. Louis levine,[email protected] http://classes.cec.wustl.edu/ cs342/ CS 342: OO Software Development Lab OO Programming with C++ C++ Tour Topics C++ Overview and Design Goals Function Prototypes C++ Classes C++ Objects Inheritance Preview Dynamic Binding Preview Overloading Type-Safe Linkage Inline Functions Dynamic Memory Management Const Type Qualifier Stream I/O Boolean Type References Default Parameters Declaration Statements Static Initialization Copyright c 1997-2000 Dept. of Computer Science, Washington University 1 CS 342: OO Software Development Lab OO Programming with C++ C++ Overview C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80’s The original cfront translated C++ into C for portability However, this was difficult to debug and potentially inefficient Many native host machine compilers now exist e.g., Borland, DEC, GNU, HP, IBM, Microsoft, Sun, Symantec, etc. C++ is a mostly upwardly compatible extension of C that provides: 1. Stronger typechecking 2. Support for data abstraction 3. Support for object-oriented programming 4. Support for generic programming Copyright c 1997-2000 Dept. of Computer Science, Washington University 2 CS 342: OO Software Development Lab OO Programming with C++ C++ Design Goals As with C, run-time efficiency is important Unlike, e.g., Ada and Java, complicated run-time libraries have not traditionally been required for C++ Note, that there is no language-specific support for concurrency, persistence, garbage collection, or distribution in C++ Compatibility with C libraries and UNIX tools is emphasized, e.g., Object code reuse The storage layout of structures is compatible with C Support for X-windows, standard ANSI C library, UNIX system calls via the extern "C" feature Object code analysis tools, such as nm and size C++ works with the make recompilation utility Copyright c 1997-2000 Dept. of Computer Science, Washington University 3

Upload: others

Post on 16-Jun-2020

8 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: Object-Oriented Software Development Lab

A Tour Through C++

David L. LevineChristopher D. Gill

Department of Computer ScienceWashington University, St. Louis

levine,[email protected]

http://classes.cec.wustl.edu/�cs342/

CS 342: OO Software Development Lab OO Programming with C++

C++ Tour Topics

� C++ Overview and DesignGoals

� Function Prototypes

� C++ Classes

� C++ Objects

� Inheritance Preview

� Dynamic Binding Preview

� Overloading

� Type-Safe Linkage

� Inline Functions

� Dynamic Memory Management

� Const Type Qualifier

� Stream I/O

� Boolean Type� References

� Default Parameters

� Declaration Statements

� Static Initialization

Copyright c 1997-2000 Dept. of Computer Science, Washington University 1

CS 342: OO Software Development Lab OO Programming with C++

C++ Overview

� C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in theearly 80’s

– The original cfront translated C++ into C for portability

� However, this was difficult to debug and potentially inefficient– Many native host machine compilers now exist

� e.g., Borland, DEC, GNU, HP, IBM, Microsoft, Sun, Symantec,etc.

� C++ is a mostly upwardly compatible extension of C that provides:

1. Stronger typechecking2. Support for data abstraction3. Support for object-oriented programming4. Support for generic programming

Copyright c 1997-2000 Dept. of Computer Science, Washington University 2

CS 342: OO Software Development Lab OO Programming with C++

C++ Design Goals� As with C, run-time efficiency is important

– Unlike, e.g., Ada and Java, complicated run-time libraries have nottraditionally been required for C++

� Note, that there is no language-specific support for concurrency,persistence, garbage collection, or distribution in C++

� Compatibility with C libraries and UNIX tools is emphasized, e.g.,

– Object code reuse

� The storage layout of structures is compatible with C

� Support for X-windows, standard ANSI C library, UNIX systemcalls via the extern "C" feature

– Object code analysis tools, such as nmand size– C++ works with the make recompilation utility

Copyright c 1997-2000 Dept. of Computer Science, Washington University 3

Page 2: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Progra

C++ Design Goals (cont’d)

� “As close to C as possible, but no closer”

– i.e., C++ is not a proper superset of C, so thatbackwards compatibility is not entirelymaintained

� Typically not a problem in practice ...

� Note, certain C++ design goals conflict withmodern techniques for:

1. Compiler optimization– e.g., pointers to arbitrary memory locations

complicate register allocation and garbagecollection

2. Software engineering– e.g., the class interface exposes its private

data layout to all clients unless certainpatterns/idioms are used

– e.g., separate compilation complicatesinlining due to difficulty of interproceduralanalysis

– Dynamic memory management iserror-prone

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS

342:O

OS

oftware

Developm

entLabO

OP

rogramm

ingw

ithC

++

Major

C++

Features

andE

nhancements

1.C

++

supportsO

Oprogram

ming

features

e.g.,abstractclasses,inheritance,anddynam

icbinding

2.C

++

supportsdata

abstractionfeatures

e.g.,classesand

name

spaces

3.C

++

supportsgeneric

programm

ing

e.g.,parameterized

types

4.C

++

supportssophisticated

errorhandling

e.g.,exceptionhandling

5.C

++

supportsidentifying

anobject’s

typeatruntim

e

e.g.,Run-T

ime

TypeIdentification

(RT

TI)

Copyright

c

1997-2000D

ept.ofC

omputer

Science,W

ashingtonU

niversity5

CS 342: OO Software Development Lab OO Progra

Other Useful Features andEnhancements

� C++ enforces type checking via functionprototypes

� Provides type-safe linkage

� Provides inline function expansion

� Built-in dynamic memory management via newand delete operators

� Default values for function parameters

� References provide call-by-reference parameterpassing

� Declare constants that can be used to definestatic array bounds with the const type qualifier

� Provides a namespace control mechanism forrestricting the scope of classes, functions, andglobal objects

� The name of a struct , class , enum, orunion is a type name

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS 342: OO Software Development Lab OO Progra

Somewhat Useful Features andEnhancements

� Operator and function overloading

� New bool boolean type

� Allows several different commenting styles

� A new set of “function call”-style cast notations

� Variable declarations can occur anywherestatements can appear within a block

� Allows user-defined conversion operators

� Static data initializers may be arbitraryexpressions

� New type-secure extensible I/O interface calledstreams and iostreams

� New mutable type qualifier

Copyright c 1997-2000 Dept. of Computer Science, Washington University

Page 3: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Programming with C++

Language Features Not Part of C++

1. Concurrency

� See Concurrent C by Nehrain Gehani and the Actor++ model byLavender and Kafura

2. Persistence

� See Object Store, Versant, Objectivity, as well as the Exodussystem and E programming language

3. Garbage Collection

� See papers in USENIX C++ 1994

4. Distribution

� See CORBA and DCOM

Copyright c 1997-2000 Dept. of Computer Science, Washington University 8

CS 342: OO Software Development Lab OO Programming with C++

Strategies for Learning C++

� Focus on concepts and programming techniques

– Don’t get lost in language features

� Learn C++ to become a better programmer

– More effective at designing and implementing– Design Patterns

� Recognize that C++ supports many different programming styles

� Learn C++ gradually

– You don’t have to know every detail of C++ to write a good C++program

Copyright c 1997-2000 Dept. of Computer Science, Washington University 9

CS 342: OO Software Development Lab OO Programming with C++

Overview of Remaining Tutorial

� To illustrate C++, we use a detailed case study that examinesseveral alteratives methods of implementing a Stack

– We begin with C and evolve up to various C++ implementations

� Next, we examine many of the key C++ features in more detail

– We’ll cover these features in even more detail over the course ofthe class

Copyright c 1997-2000 Dept. of Computer Science, Washington University 10

CS 342: OO Software Development Lab OO Programming with C++

Stack Example� Consider the following “bare-bones” Stack implementation:

typedef int T;/* const int MAX_STACK = 100; */#define MAX_STACK 100T stack[MAX_STACK];int top = 0;

T item;

stack[top++] = item; // push...item = stack[--top]; // pop

� Obviously, this is not very abstract...

Copyright c 1997-2000 Dept. of Computer Science, Washington University 11

Page 4: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Progra

Data Hiding Implementation in C

� Define the interface to a Stack of integers in C:

/* File stack.h */

/* Type of Stack element. */typedef int T;

/* Stack interface. */int create (int size);int destroy (VOID);void push (T new_item);void pop (T *old_top);void top (T *cur_top);int is_empty (void);int is_full (void);

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS 342: OO Software Development Lab OO Progra

Data Hiding Implementation in C(cont’d)

� /* File stack.c */

#include <stdlib.h>#include "stack.h"

/* Hidden within this file. */static int top_, size_;static T *stack_;

int create (int size) {top_ = 0; size_ = size;stack_ = malloc (size * sizeof (T));return stack_ = = 0 ? -1 : 0;

}void destroy (void) { free ((void *) stack_); }void push (T item) { stack_[top_++] = item;}void pop (T *item) { *item = stack_[--top_]; }void top (T *item) { *item = stack_[top_ - 1]; }int is_empty (void) { return top_ == 0; }int is_full (void) { return top_ == size_; }

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS

342:O

OS

oftware

Developm

entLabO

OP

rogramm

ingw

ithC

++

Data

Hiding

Implem

entationin

C(cont’d)

Use

case

#in

clude

"stack.h

"vo

idfo

o(vo

id)

{T

i;push

(10);

/*O

ops,

forg

ot

toca

llcre

ate

!*/

push

(20);

pop

(&i);

destro

y();

}

Main

problems:

1.T

heprogram

mer

mustcallcre

ate

firstanddestro

ylast!

–C

oulduse

first-time-in

flag...2.

There

isonly

onestack

andonly

onetype

ofstack3.

Nam

espace

pollution...4.

Non-reentrant

Copyright

c

1997-2000D

ept.ofC

omputer

Science,W

ashingtonU

niversity14

CS 342: OO Software Development Lab OO Progra

Data Abstraction Implementation in C

� An ADT Stack interface in C:

/* File stack.h */

/* Type of Stack element. */typedef int T;

/* Type definition for Stack ADT. */typedef struct {

size_t top_, size_;T *stack_;

} Stack;

/* Stack interface. */int Stack_create (Stack *s, size_t size);void Stack_destroy (Stack *s);void Stack_push (Stack *s, T item);void Stack_pop (Stack *, T *item);/* Must call before pop’ing */int Stack_is_empty (Stack *);/* Must call before push’ing */int Stack_is_full (Stack *);/* ... */

Copyright c 1997-2000 Dept. of Computer Science, Washington University

Page 5: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Progra

Data Abstraction Implementation in C(cont’d)

� An ADT Stack implementation in C:

/* File stack.c */#include "stack.h"

int Stack_create (Stack *s, size_t size) {s->top_ = 0; s->size_ = size;s->stack_ = malloc (size * sizeof (T));return s->stack_ == 0 ? -1 : 0;

}void Stack_destroy (Stack *s) {

free ((VOID *) s->stack_);s->top_ = 0; s->size_ = 0; s->stack_ = 0;

}void Stack_push (Stack *s, T item) {

s->stack_[s->top_++] = item;}void Stack_pop (Stack *s, T *item) {

*item = s->stack_[--s->top__];}int Stack_is_empty (Stack *s) {

RETURN s->top_ == 0;}

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS 342: OO Software Development Lab OO Progra

Data Abstraction Implementation in C(cont’d)

� Use case

void foo (void){

/* Multiple stacks! */Stack s1, s2, s3;T item;

/* Pop’d empty stack */Stack_pop (&s2, &item);

/* Forgot to call Stack_create! */Stack_push (&s3, 10);

/* Destroy uninitialized stack! */Stack_destroy (&s1);

}

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS

342:O

OS

oftware

Developm

entLabO

OP

rogramm

ingw

ithC

++

Main

problems

with

Data

Abstraction

inC

1.N

oguaranteed

initialization/termination

2.S

tillonlyone

typeofstack

supported

3.Too

much

overheaddue

tofunction

calls

4.N

ogeneralized

errorhandling...

5.T

heC

compiler

doesnotenforce

information

hidinge.g.,

s1.to

p_

=s2

.stack_

[0];

/*V

iola

teabstra

ction

*/s2

.size_

=s3

.top_;

/*V

iola

teabstra

ction

*/

Copyright

c

1997-2000D

ept.ofC

omputer

Science,W

ashingtonU

niversity18

CS 342: OO Software Development Lab OO Progra

Data Abstraction Implementation inC++

� Question: how to we get encapsulation andmore than one stack?

� Answer: define a Stack ADT using C++:

// File Stack.htypedef int T;class Stack {public:

Stack (size_t size);Stack (const Stack &s);void Stack (const Stack &s);˜Stack (void);void push (const T &item);void pop (T &item);int is_empty (void) const;int is_full (void) const;// ...

private:size_t top_, size_;T *stack_;

};

Copyright c 1997-2000 Dept. of Computer Science, Washington University

Page 6: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Progra

Data Abstraction Implementation inC++ (cont’d)

� Manager operations

Stack::Stack (size_t size): top_ (0), size_ (size),

stack_ (new T[size]) {}

Stack::Stack (const Stack &s):: top_ (s.top_), size_ (s.size_),

stack_ (new T[s.size_]) {}

void Stack::operator = (const Stack &s):if (this == &s) return;delete [] this->stack_;this->stack_ = new T[s.size_];this->top_ = s.top_; this->size_ = s.size_;for (size_t i = 0 ; i < s.size_; i++)

this->stack_[i] = s.stack_[i];}

Stack::˜Stack (void) {delete [] this->stack_;

}

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS 342: OO Software Development Lab OO Progra

Data Abstraction Implementation inC++ (cont’d)

� Accessor and worker operations

int Stack::is_empty (void) const {return this->top_ == 0;

}

int Stack::is_full (VOID) const {return this->top_ == this->size_;

}

void Stack::push (const T &item) {this->stack_[this->top_++] = item;

}

void Stack::pop (T &item) {item = this->stack_[--this->top_];

}

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS 342: OO Software Development Lab OO Progra

Data Abstraction Implementation inC++ (cont’d)

� Use case

#include "Stack.h"void foo (void) {

Stack s1 (1), s2 (100);T item;

if (!s1.is_full ())s1.push (473);

if (!s2.is_full ())s2.push (2112);

if (!s2.is_empty ())s2.pop (item);

// Access violation caught// at compile-time!s2.top_ = 10;

// Termination handled automatically// via destructor.

}

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS

342:O

OS

oftware

Developm

entLabO

OP

rogramm

ingw

ithC

++

Benefits

ofC++

Data

Abstraction

Implem

enation

1.D

atahiding

anddata

abstraction,e.g.,

Sta

cks1

(200);

s1.to

p_

=10

//E

rror

flagged

by

com

pile

r!

2.T

heability

todeclare

multiple

stackobjects

Sta

cks1

(10),

s2(2

0),

s3(3

0);

3.A

utomatic

initializationand

termination

{//

Constru

ctor

auto

matica

llyca

lled.

Sta

cks1

(1000);

//...

//D

estru

ctor

auto

matica

llyca

lled

}

Copyright

c

1997-2000D

ept.ofC

omputer

Science,W

ashingtonU

niversity23

Page 7: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS

342:O

OS

oftware

Developm

entLabO

OP

rogramm

ingw

ithC

++

Draw

backsw

ithC

++D

ataA

bstractionIm

plementation:

1.E

rrorhandling

isobtrusive

Use

exceptionhandling

tosolve

this

2.T

heexam

pleis

limited

toa

singletype

ofstackelem

ent(INT

inthis

case)

We

canuse

C+

+“param

eterizedtypes”

torem

ovethis

limitation

3.F

unctioncalloverhead

We

canuse

C+

+inline

functionsto

remove

thisoverhead

Copyright

c

1997-2000D

ept.ofC

omputer

Science,W

ashingtonU

niversity24

CS 342: OO Software Development Lab OO Progra

Exception Handling Implementation inC++ (cont’d)

� C++ exception handling separates errorhandling from normal processing

// File Stack.htypedef int T;class Stack {public:

class Underflow { /* ... */ };class Overflow { /* ... */ };Stack (size_t size);˜Stack (void);void push (const T &item)

throw (Overflow);void pop (T &item)

throw (Underflow);// ...

private:size_t top_, size_;T *stack_;

};

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS

342:O

OS

oftware

Developm

entLabO

OP

rogramm

ingw

ithC

++

Exception

Handling

Implem

entationin

C++

(cont’d)

Stack.C

void

Sta

ck::push

(const

T&

item

)th

row

(Sta

ck::Ove

rflow

){

if(th

is->is_

full

())th

row

Sta

ck::Ove

rflow

();th

is->sta

ck_[th

is->to

p_+

+]

=ite

m;

}void

Sta

ck::pop

(T&

item

)th

row

(Sta

ck::Underflo

w)

{if

(this->

is_em

pty

())th

row

Sta

ck::Underflo

w();

item

=th

is->sta

ck_[--th

is->to

p_];

}

Copyright

c

1997-2000D

ept.ofC

omputer

Science,W

ashingtonU

niversity26

CS 342: OO Software Development Lab OO Progra

Exception Handling Implementation inC++ (cont’d)

� Use case

#include "Stack.h"void foo (void) {

Stack s1 (1), s2 (100);

try {T item;s1.push (473);// Exception, push’d full stack!s1.push (42);// Exception, pop’d empty stack!s2.pop (item);s2.top_ = 10; // Access violation caught!

} catch (Stack::Underflow) {// Handle underflow...

} catch (Stack::Overflow) {// Handle overflow...

} catch (...) {// Catch anything else...throw;

}

// Termination is handled automatically.}

Copyright c 1997-2000 Dept. of Computer Science, Washington University

Page 8: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Progra

Template Implementation in C++

� A parameterized type Stack class interfaceusing C++

// typedef int T;template <class T>class Stack {public:

Stack (size_t size);˜Stack (void)void push (const T &item);void pop (T &item);int is_empty (void);int is_full (void);// ...

private:size_t top_, size_;T *stack_;

};

� To simplify the following examples we’ll omitexception handling...

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS 342: OO Software Development Lab OO Progra

Template Implementation in C++(cont’d)

� A parameterized type Stack classimplementation using C++

template <class T> inlineStack<T>::Stack (size_t size)

: top_ (0), size_ (size),stack_ (new T[size]) { }

template <class T> inlineStack<T>::˜Stack (void) {

delete [] this->stack_;}

template <class T> inline voidStack<T>::push (const T &item) {

this->stack_[this->top_++] = item;}

template <class T> inline voidStack<T>::pop (T &item) {

item = this->stack_[--this->top_];}

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS

342:O

OS

oftware

Developm

entLabO

OP

rogramm

ingw

ithC

++

Template

Implem

entationin

C++

(cont’d)

Note

them

inorchanges

tothe

codeto

accomm

odateparam

eterizedtypes

#in

clude

"Sta

ck.h"

void

foo

(void

){

Sta

ck<in

t>s1

(1000);

Sta

ck<flo

at>

s2;

Sta

ck<S

tack

<A

ctivatio

n_R

eco

rd>

*>s3

;

s1.p

ush

(-291);

s2.to

p_

=3.1

416;

//A

ccess

viola

tion

caught!

s3.p

ush

(new

Sta

ck<A

ctivatio

n_R

eco

rd>

);S

tack

<A

ctivatio

n_R

eco

rd>

*sar;

s3.p

op

(sar);

dele

tesa

r;//

Term

inatio

nis

handle

dauto

matica

lly}

Copyright

c

1997-2000D

ept.ofC

omputer

Science,W

ashingtonU

niversity30

CS 342: OO Software Development Lab OO Progra

Template Implementation in C++(cont’d)

� Another parameterized type Stack class

template <class T, size_t size>class Stack {public:

Stack (void);˜Stack (void)void push (CONST T &item);void pop (T &item);// ...

private:size_t top_, size_;T stack_[size];

};

� Note, there is no longer any need for dynamicmemory, e.g.,

Stack<int, 200> s1;

Copyright c 1997-2000 Dept. of Computer Science, Washington University

Page 9: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS

342:O

OS

oftware

Developm

entLabO

OP

rogramm

ingw

ithC

++

Object-O

rientedIm

plementation

inC

++

Problem

sw

ithprevious

examples:

–C

hangesto

theim

plementation

willrequire

recompilation

andrelinking

ofclients–

Extensions

willrequire

accessto

source

Solutions

–C

ombine

inheritancew

ithdynam

icbinding

tocom

pletelydecouple

interfacefrom

implem

entationand

bindingtim

e–

This

requiresthe

useofC

++

abstractbaseclasses

Copyright

c

1997-2000D

ept.ofC

omputer

Science,W

ashingtonU

niversity32

CS

342:O

OS

oftware

Developm

entLabO

OP

rogramm

ingw

ithC

++

Object-O

rientedIm

plementation

inC

++(cont’d)

Defining

anabstractbase

classin

C+

+

tem

pla

te<

class

T>

class

Sta

ck{public:

virtual

void

push

(const

T&

item

)=

0;

virtual

void

pop

(T&

item

)=

0;

virtual

int

is_em

pty

(void

)co

nst

=0;

virtual

int

is_fu

ll(vo

id)

const

=0;

//T

em

pla

tem

eth

od

void

top

(T&

item

){

this->

pop

(item

);th

is->push

(item

);}

};

By

using“pure

virtualmethods,”

we

canguarantee

thatthecom

pilerw

on’tallowinstantiation!

Copyright

c

1997-2000D

ept.ofC

omputer

Science,W

ashingtonU

niversity33

CS 342: OO Software Development Lab OO Progra

Object-Oriented Implementation in C++(cont’d)

� Use interface inheritance to create a specializedversion of a “bounded” stack:

#include "Stack.h"#include "Array.h"

template <class T>class B_Stack : public Stack<T>{public:

enum { DEFAULT_SIZE = 100 };B_Stack (size_t size = DEFAULT_SIZE);virtual void push (const T &item);virtual void pop (T &item);virtual int is_empty (void) const;virtual int is_full (void) const;// ...

private:Array<T> stack_; // user-definedsize_t top_; // built-in

};

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS 342: OO Software Development Lab OO Progra

Object-Oriented Implementation in C++(cont’d)

� class B Stack implementation

template <class T>B_Stack<T>::B_Stack (size_t size)

: top_ (0), stack_ (size) {}

template <class T> voidB_Stack<T>::push (const T &item) {

this->stack_.set (this->top_++, item);}

template <class T> voidB_Stack<T>::pop (T &item) {

this->stack_.get (--this->top_, item);}

template <class T> intB_Stack<T>::is_full (void) const {

return this->top_ >= this->stack_.size ();}

Copyright c 1997-2000 Dept. of Computer Science, Washington University

Page 10: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Progra

Object-Oriented Implementation in C++(cont’d)

� Likewise, interface inheritance can create atotally different “unbounded” implementation:

// Forward declaration.template <class T> class Node;template <class T>class UB_Stack : public Stack<T>{public:

enum { DEFAULT_SIZE = 100 };UB_Stack (size_t hint = DEFAULT_SIZE);˜UB_Stack (void);virtual void push (const T &new_item);virtual void pop (T &top_item);virtual int is_empty (void) const {

return this->head_ == 0;}virtual int is_full (void) const { return 0; }// ...

private:// Head of linked list of Node<T>’s.// Note the use of the Cheshire cat...Node<T> *head_;

};

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS

342:O

OS

oftware

Developm

entLabO

OP

rogramm

ingw

ithC

++

Object-O

rientedIm

plementation

inC

++(cont’d)

classN

ode

implem

entation

tem

pla

te<

class

T>

class

Node

{frie

nd

tem

pla

te<

class

T>

class

UB

_S

tack;

public:

Node

(Ti,

Node<

T>

*n=

0)

:ite

m_

(i),next_

(n)

{}priva

te:

Tite

m_;

Node<

T>

*next_

;};

Note

thattheuse

ofthe“C

heshirecat”

idiomallow

sthe

libraryw

riterto

completely

hidethe

representationofclass

UB

Sta

ck...

Copyright

c

1997-2000D

ept.ofC

omputer

Science,W

ashingtonU

niversity37

CS 342: OO Software Development Lab OO Progra

Object-Oriented Implementation in C++(cont’d)

� Class UB Stack implementation:

template <class T>UB_Stack<T>::UB_Stack (size_t hint): head_ (0) {}

template <class T> voidUB_Stack<T>::push (const T &item) {

Node<T> *t = new Node<T> (item, this->head_);assert (t != 0);this->head_ = t;

}

template <class T> voidUB_Stack<T>::pop (T &top_item) {

top_item = this->head_->item_;Node<T> *t = this->head_;this->head_ = this->head_->next_;delete t;

}

template <class T>UB_Stack<T>::˜UB_Stack (void) {

// delete all Nodes...for (T t; this->head_ != 0; this->pop (t))

continue;}

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS 342: OO Software Development Lab OO Progra

Object-Oriented Implementation in C++(cont’d)

� It’s now possible to write code that doesn’tdepend on the stack implementation

� e.g.,// Require recompilation if subclasses changetemplate <class T>Stack<T> *make_stack (int use_B_Stack) {

// Factory pattern...if (use_B_Stack)

return new B_Stack<int>;else

return new UB_Stack<int>;}

// Doesn’t require recompilation if// subclasses changevoid foo (Stack<int> *stack) {

int i;stack->push (100);stack->pop (i);// ...

}

// Call foo().foo (make_stack<int> (0));

Copyright c 1997-2000 Dept. of Computer Science, Washington University

Page 11: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Programming with C++

Object-Oriented Implementation in C++ (cont’d)

� Moreover, we can make changes at run-time without modifying,recompiling, or relinking existing code

– i.e., can use “dynamic linking” to select stack representation atrun-time, e.g.,

char stack_symbol[MAXNAMLEN];char stack_file[MAXNAMLEN];cin >> stack_file >> stack_symbol;void *handle = ::dlopen (stack_file);void *sym = ::dlsym (handle, stack_symbol);// Note use of RTTIif (Stack<int> *sp =

dynamic_cast <Stack<int> *> (sym))foo (sp);

� Note, no need to stop, modify, and restart an executing application!

– Naturally, this requires careful configuration management...

Copyright c 1997-2000 Dept. of Computer Science, Washington University 40

CS 342: OO Software Development Lab OO Programming with C++

Function Prototypes

� C++ supports stronger type checking via function prototypes

– Unlike ANSI-C, C++ requires prototypes for both functiondeclarations and definitions

– Function prototypes eliminate a class of common C errors

� e.g., mismatched or misnumbered parameter values and returntypes

� Prototypes are used for external declarations in header files, e.g.,

extern char *strdup (const char *s);extern int strcmp (const char *s, const char *t);file *fopen (const char *filename, const char *type);extern void print_error_msg_and_die (const char *msg);

Copyright c 1997-2000 Dept. of Computer Science, Washington University 41

CS 342: OO Software Development Lab OO Programming with C++

Function Prototypes (cont’d)#if defined (__STDC__) || defined (__cplusplus)

extern int freopen (const char *nm, const char *tp, file *s);extern char *gets (char *);extern int perror (const char *);

#else /* Original C-style syntax. */extern int freopen (), perror ();extern char *gets ();

#endif /* defined (__STDC__) */

int main (int, char *[]) {char buf[80];if (freopen ("./foo", "r", stdin) == 0)

perror (freopen), exit (1);

while (gets (buf) != 0)/* . . . */;

}

Copyright c 1997-2000 Dept. of Computer Science, Washington University 42

CS 342: OO Software Development Lab OO Programming with C++

Function Prototypes (cont’d)� The preceeding program fails mysteriously if the actual calls are:

/* Extra argument, also out-of-order! */freopen (stdin, "newfile", 10, ’C’);

/* Omitted arguments. */freopen ("newfile", "r");

� A “Classic C” compiler would generally not detect erroneousparameter passing at compile time (though lint would)

– Note, C++ lint utilities are not widely available, but g++ -Walland CC +wprovide similar typechecking facilities

� Function prototypes are used in both definitions and declarations

Copyright c 1997-2000 Dept. of Computer Science, Washington University 43

Page 12: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Programming with C++

Function and Operator OverloadingTwo or more functions or operators may be given the same nameprovided the type signatures are unique

Unique argument types:double square (double);Complex &square (Complex &);

Unique number of arguments:void move (int);void move (int, int);

A function’s return type is not considered when distinguishing betweenoverloaded instances

� e.g., the following declarations are ambiguous to the C++ compiler:

extern double operator / (Complex &, Complex &);extern complex operator / (Complex &, Complex &);

Copyright c 1997-2000 Dept. of Computer Science, Washington University 44

CS 342: OO Software Development Lab OO Programming with C++

C++ Classes

� The class is the basic protection and data abstraction unit in C++

– i.e., rather than “per-object” protection

� The class mechanism facilitates the creation of user-definedAbstract Data Types (ADTs)

– A class declarator defines a type comprised of data members, aswell as method operators

� Data members may be both built-in and user-defined– Classes are “cookie cutters” used to define objects

� a.k.a. instances

Copyright c 1997-2000 Dept. of Computer Science, Washington University 45

CS 342: OO Software Development Lab OO Programming with C++

C++ Classes (cont’d)

� For efficiency and C compatibility reasons, C++ has two typesystems

1. One for built-in types, e.g., int , float , char , double , etc.2. One for user-defined types, e.g., class es, struct s, union s,

enums, etc.

� Note that constructors, overloading, inheritance, and dynamicbinding only apply to user-defined types

– This minimizes surprises, but is rather cumbersome to documentand explain . . .

Copyright c 1997-2000 Dept. of Computer Science, Washington University 46

CS 342: OO Software Development Lab OO Programming with C++

C++ Classes (cont’d)� A class is a type constructor

– e.g., in contrast to an Ada or Java package, or a Modula 2 module

� Note, these are not types, they are encapsulation units– Until recently, C++ did not have a higher-level modularization

mechanism . . .

� This was a problem for large systems, due to lack of librarymanagement facilities and visibility controls

– Recent versions of the ANSI C++ draft standard includemechanisms that addresses namespace control andvisibility/scoping, e.g.,

� Name spaces

� Nested classes

Copyright c 1997-2000 Dept. of Computer Science, Washington University 47

Page 13: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS

342:O

OS

oftware

Developm

entLabO

OP

rogramm

ingw

ithC

++

C++

Classes

(cont’d)

Generalcharacteristics

ofC+

+classes:

–A

nynum

berofclass

objectsm

aybe

defined

i.e.,objects,which

haveidentity,state,and

behavior–

Class

objectsm

aybe

dynamically

allocatedand

deallocated–

Passing

classobjects,pointers

toclass

objects,andreferences

toclass

objectsas

parameters

tofunctions

arelegal

–V

ectorsofclass

objectsm

aybe

defined

Acla

ssserves

thesam

epurpose

asa

Javacla

ss,and

asim

ilarpurpose

toa

Cstru

ct

–H

owever,itis

extendedto

allowuser-defined

behavior,asw

ell

Copyright

c

1997-2000D

ept.ofC

omputer

Science,W

ashingtonU

niversity48

CS 342: OO Software Development Lab OO Progra

Class Vector Example

� There are several significant limitations withbuilt-in C and C++ arrays, e.g.,

– The size must be a compile-time constant,e.g.,void foo (int i) {

int a[100], b[100]; // OKint c[i]; // Error!

}

– Array size cannot vary at run-time– Legal array bounds run from 0 to size - 1– No range checking performed at run-time,

e.g.,int a[10], i;for (i = 0; i <= 10; i++)

a[i] = 0;

– Cannot perform full array assignments, e.g.,a = b; // Error!

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS

342:O

OS

oftware

Developm

entLabO

OP

rogramm

ingw

ithC

++

Class

Vector

Exam

ple(cont’d)

We

canw

ritea

C+

+class

toovercom

esom

eofthese

limitations,

i.e.,

–com

pile-time

constantsize–

lackofrange

checking

Lateron

we’lluse

otherC

++

features,suchas

inheritanceand

parameterized

types,tofinish

thejob, i.e.,

–resizing

–non-zero

lower

bounds–

arrayassignm

ent–

typeparam

eterization

Copyright

c

1997-2000D

ept.ofC

omputer

Science,W

ashingtonU

niversity50

CS 342: OO Software Development Lab OO Progra

Class Vector Interface

// File Vector.h (this ADT is incomplete// wrt initialization & assignment ...!)#ifndef _VECTOR_H#define _VECTOR_H

typedef int T;class Vector {public:

Vector (size_t len = 100);˜Vector (void);size_t size (void) const;

bool set (size_t i, T item);bool get (size_t i, T &item) const;

private:size_t size_;T *buf_;bool in_range (size_t i) const;

};#endif /* _VECTOR_H */

Copyright c 1997-2000 Dept. of Computer Science, Washington University

Page 14: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Progra

Class Vector Implementation// File Vector.cpp.#include Vector.h

bool Vector::in_range (size_t i) const{

return i < this->size ();}

bool Vector::set (size_t i, T item) {if (this->in_range (i)) {

this->buf_[i] = item;return true;

}else return false;

}

bool Vector::get (size_t i, T &item) const {if (this->in_range (i)) {

item = this->buf_[i];return true;

}else return false;

}

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS

342:O

OS

oftware

Developm

entLabO

OP

rogramm

ingw

ithC

++

Class

Vector

Exam

ple(cont’d)

buf

len

dynam

ically

allocated

m

em

ory

ofsizelen

The

controlblockthatrepresents

anobjectof

class

Vector

–N

ote,thecontrolblock

may

beallocated

offthestack,the

globaldata

segment,or

theheap

–H

owever,the

buf

fieldalw

ayspoints

tom

emory

allocatedoffthe

heap

Copyright

c

1997-2000D

ept.ofC

omputer

Science,W

ashingtonU

niversity53

CS 342: OO Software Development Lab OO Progra

Class Vector (Attempted) Usage

// File test.cpp#include <libc.h>#include Vector.hvoid foo (size_t size) {

// Call constructorVector user_vec (size);// Error, no dynamic rangeint c_vec[size];

c_vec[0] = 0;user_vec.set (0, 0);

for (size_t i = 1;i < user_vec.size ();i++) {

int t;user_vec.get (i - 1, t);user_vec.set (i, t + 1);c_vec[i] = c_vec[i - 1] + 1;

}

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS

342:O

OS

oftware

Developm

entLabO

OP

rogramm

ingw

ithC

++

Class

Vector

(Attem

pted)U

sage(cont’d)

//E

rror,

priva

teand

pro

tecte

ddata

inacce

ssible

size=

use

r_ve

c.size_

-1;

use

r_ve

c.buf_

[size]

=100;

//R

un-tim

eerro

r,in

dex

out

of

range

if(u

ser_

vec.se

t(u

ser_

vec.size

(),1000)

==

false

)err

(index

out

of

range);

//In

dex

out

of

range

not

dete

cted

at

runtim

e!

c_ve

c[size]

=1000;

//D

estru

ctor

calle

dw

hen

use

r_ve

cle

ave

ssco

pe

}Copyright

c

1997-2000D

ept.ofC

omputer

Science,W

ashingtonU

niversity55

Page 15: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS

342:O

OS

oftware

Developm

entLabO

OP

rogramm

ingw

ithC

++

Class

Vector

Exam

ple(cont’d)

Note

thatthisexam

plehas

severalunnecessarylim

itationsthatare

addressedby

additionalC+

+features, e.g.,

–se

t/get

paradigmdiffers

fromC

’sbuilt-in

subscriptnotation–

Error

checkingvia

returnvalue

issom

ewhataw

kward

–O

nlyw

orksfor

avector

ofin

ts

–C

lassesthatinheritfrom

Vector

may

notalways

wantthe

extraoverhead

ofrangechecking

..

.

The

following

example

illustratesseveralm

oreadvanced

C+

+features

Copyright

c

1997-2000D

ept.ofC

omputer

Science,W

ashingtonU

niversity56

CS 342: OO Software Development Lab OO Progra

Class Template Vector Interface

// File Vector.h// typedef int T;template <class T>class Vector {public:

struct range_error {};Vector (size_t len = 100);˜Vector (void);size_t size (void) const;

T &operator[] (size_t i)throw (range_error);

protected:T &elem (size_t i) {

return this->buf_[i];}

private:size_t size_;T *buf_;bool in_range (size_t i);

};

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS 342: OO Software Development Lab OO Progra

Class Template Vector (Attempted)Usage

// File test.cpp#include Vector.hvoid foo (size_t size) {

try { // Illustrates exception handling . . .Vector<int> user_vec (size);int c_vec[size]; // Error, no dynamic rangec_vec[0] = user_vec[0] = 0;

for (int i = 1; i < user_vec.size (); i++){

user_vec[i] = user_vec[i - 1] + 1;c_vec[i] = c_vec[i - 1] + 1;

}

// Error, private/protected data inaccessiblesize = user_vec.size_ - 1;user_vec.buf_[size] = 100;user_vec.elem (3) = 120;

// Run-time error!user_vec[user_vec.size ()] = 1000;

// Index range error not detected at runtime!c_vec[size] = 1000;// Destructor called scope is exited.

}catch (Vector<int>::range_error) { /* ... */ }

}

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS

342:O

OS

oftware

Developm

entLabO

OP

rogramm

ingw

ithC

++

C++

Objects

AC

++

objectisan

instanceofa

class

(orany

otherC

++

typefor

thatmatter

..

.)

An

objectcanbe

instantiatedor

disposedeither

implicitly

orexplicitly,depending

onits

life-time

The

life-time

ofaC

++

objectiseither

static,automatic,or

dynamic

–C

++

refersto

thisas

thestorage

classofan

object

Copyright

c

1997-2000D

ept.ofC

omputer

Science,W

ashingtonU

niversity59

Page 16: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Programming with C++

C++ Objects (cont’d)

� Life-time or storage class:

1. Static– i.e., it lives throughout life-time of process– static can be used for local, global, or class-specific objects

(note, their scope is different)2. Automatic

– i.e., it lives only during function invocation, on the run-time stack3. Dynamic

– i.e., it lives between corresponding calls to operators new anddelete

– Or malloc and free– Dynamic objects have life-times that extend beyond their

original scope

Copyright c 1997-2000 Dept. of Computer Science, Washington University 60

CS 342: OO Software Development Lab OO Programming with C++

C++ Objects (cont’d)

Uninitialized

Global Data

Initialized

Global Data

Text

Stack

Heap

Automatic

Variables

Dynamic

Variables

Static

Variables

High

Addresses

Low

Addresses

Read-Only

Code and

Data

� Typical layout of memory objects in the process address space

Copyright c 1997-2000 Dept. of Computer Science, Washington University 61

CS 342: OO Software Development Lab OO Programming with C++

C++ Objects (cont’d)

� Most C++ implementations do not support automatic garbagecollection of dynamically allocated objects

– In garbage collection schemes, the run-time system is responsiblefor detecting and deallocating unused dynamic memory

– Note, it is very difficult to implement garbage collection correctlyin C++ due to pointers and unions

� Therefore, programmers must explicitly deallocate objects whenthey want them to go away

– C++ constructors and destructors are useful for automatingcertain types of memory management . . .

Copyright c 1997-2000 Dept. of Computer Science, Washington University 62

CS 342: OO Software Development Lab OO Programming with C++

C++ Objects (cont’d)� Several workarounds exist, however, e.g.,

– Use Java, Eiffel, or LISP ;-)– Use inheritance to derive from base class Collectible

� However, this only works then for a subset of classes (i.e.,doesn’t work for built-in types . . .)

– Use the class-specific new and delete operators to define amemory management facility using reference counts to reclaimunused memory

– Adapt Hans Boehm’s conservative garbage collector for C to C++. . .

� No solution is optimal, however, so storage management is oftenperformed “by hand” (ugh ;-))

Copyright c 1997-2000 Dept. of Computer Science, Washington University 63

Page 17: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Programming with C++

Reference Counting

ConferenceCall 935-7538

instantiated by first call toConferenceCall::join ("935-7538");

Caller 1Caller 2

Caller 3

Caller 4

Caller 5

public:

unsigned int callers_;private:

join (const PhoneNumber &);static ConferenceCall &

int hangUp ();// . . .

Class ConferenceCall{

};

� When can we deletethe ConferenceCallinstantiation?

Copyright c 1997-2000 Dept. of Computer Science, Washington University 64

CS 342: OO Software Development Lab OO Programming with C++

C++ Object-Oriented Features

� C++ provides three characteristics generally associated withobject-oriented programming:

– Data Abstraction

� Package a class abstraction so that only the public interface isvisible and the implementation details are hidden from clients

� Allow parameterization based on type– Single and Multiple Inheritance

� A derived class inherits operations and attributes from one ormore base classes, possibly providing additional operationsand/or attributes

Copyright c 1997-2000 Dept. of Computer Science, Washington University 65

CS 342: OO Software Development Lab OO Programming with C++

C++ Object-Oriented Features (cont’d)

� Dynamic Binding

– The actual type of an object (and thereby its associatedoperations) need not be fully known until run-time

– Compare with C++ template feature, which are instantiated atcompile-time

� C++’s object-oriented features encourage designs that

1. Explicitly distinguish general properties of related concepts from2. Specific details of particular instantiations of these concepts

� e.g., an object-oriented graphical shapes library design usinginheritance and dynamic binding

� This approach facilitates extensibility and reusability

Copyright c 1997-2000 Dept. of Computer Science, Washington University 66

CS 342: OO Software Development Lab OO Programming with C++

C++ Object-Oriented Features (cont’d)

Point

Shape

TriangleCircle

Color

Rectangle

11

AA11

� The “OOD challenge” isto map arbitrarily complexsystem architectures intoinheritance hierarchies

Copyright c 1997-2000 Dept. of Computer Science, Washington University 67

Page 18: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Programming with C++

C++ Object-Oriented Features (cont’d)

� Inheritance and dynamic binding facilitate the construction ofprogram families and frameworks

– Program families are sets of programs whose common propertiesare so extensive that it is advantageous to study the commonproperties of the programs before analyzing individual members

– A framework is an integrated set of components that collaborateto product a reuseable architecture for a family of relatedapplications

� It also supports the open/closed principle

– i.e., open with respect to extensibility, closed with respect tostability

Copyright c 1997-2000 Dept. of Computer Science, Washington University 68

CS 342: OO Software Development Lab OO Programming with C++

Inheritance Preview

� A type can inherit or derive the characteristics of another base type.These derived types act just like the base type, except for an explicitlist of:

1. Operations that are implemented differently, i.e., overridden2. Additional operations and extra data members3. Modified method access privileges

� C++ supports both single and multiple inheritance, e.g.,

class X { /* . . . */ };class Y : public X { /* . . . */ };class Z : public X { /* . . . */ };class YZ : public Y, public Z { /* . . . */ };

Copyright c 1997-2000 Dept. of Computer Science, Washington University 69

CS 342: OO Software Development Lab OO Programming with C++

Dynamic Binding Preview

� Dynamic binding is a mechanism used along with inheritance tosupport a form of polymorphism

� C++ uses virtual functions to implement dynamic binding:

– The actual method called at run-time depends on the class of theobject used when invoking the virtual method

� C++ allows the class definer the choice of whether to make amethod virtual or not

– This leads to time/space performance vs. flexibility tradeoffs

� Depending on the compiler, virtual methods may introduce asmall amount of overhead for each virtual function call

Copyright c 1997-2000 Dept. of Computer Science, Washington University 70 CS

342:

OO

Sof

twar

eD

evel

opm

entL

abO

OP

rogr

a

Dyn

amic

Bin

ding

Pre

view

(con

t’d)

stru

ctX

{//

Base

class

//N

on-v

irtu

al

int

m(v

oid

){

puts

("X

::m

");

}//

Virtu

al

virt

ual

int

vm(v

oid

){

puts

("X

::vm

");

}}; st

ruct

Y:

public

X{

//D

erive

dcl

ass

//N

on-v

irtu

al

int

m(v

oid

){

puts

("Y

::m

");

}//

Virtu

al

virt

ual

int

vm(v

oid

){

puts

("Y

::vm

");

}}; //

Note

,ca

nals

ouse

refe

rence

s.vo

idfo

o(X

*x)

{x-

>m

();

//direct

call:

_m

_1X

(x);

x->

vm()

;//

indirect

call:

(*x-

>vp

tr[1

])} in

tm

ain

(int,

char

*[])

{X

x;Y

y;fo

o(&

x);

//X

::m

,X

::vm

foo

(&y)

;//

X::m

,Y

::vm

} Cop

yrig

htc

1997

-200

0D

ept.

ofC

ompu

ter

Sci

ence

,Was

hing

ton

Uni

vers

ity

Page 19: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Programming with C++

Dynamic Binding Preview (cont’d)

� Each class with 1 or more virtual functions generates one ormore virtual tables (vtables)

– Note, multiple inheritance creates multiple vtables

� A vtable is logically an array of pointers to methods

– A vtable is typically implemented as an array of pointers to Cfunctions

� Each object of a class with virtual methods contains one or morevirtual pointers (vptrs), which point at the appropriate vtable for theobject

– The constructor automatically assigns the vptrs to point to theappropriate vtable

Copyright c 1997-2000 Dept. of Computer Science, Washington University 72

CS 342: OO Software Development Lab OO Programming with C++

C++ Comments

� C++ allows two commenting styles:

1. The traditional C bracketed comments, which may extend overany number of lines, e.g., /* This is a multi-line C++ comment */

2. The “continue until end-of-line” comment style, e.g., // This is asingle-line C++ or Java comment

� C-style comments do not nest. However, C++ and C styles nest, soit is possible to comment out code containing other comments, e.g.,

/* assert (i < size) // check index range */// if (i != 0 /* check for zero divide */ && 10 / i)

Copyright c 1997-2000 Dept. of Computer Science, Washington University 73

CS

342:

OO

Sof

twar

eD

evel

opm

entL

abO

OP

rogr

a

C++

Com

men

ts(c

ont’d

)

Nat

ural

ly,i

tis

still

poss

ible

tous

eC

/C+

+pr

epro

cess

ordi

rect

ives

toco

mm

ento

utbl

ocks

ofco

de:

#if

0/*

Make

sure

only

valid

C+

+co

de

goes

*//*

here

!i.e

.,don’t

use

apost

rophes!

*/#endif

Bew

are

ofsu

btle

whi

tesp

ace

issu

es.

..

int

b=

a//*

div

ided

by

4*/

4;

-a;

/*C

++

pre

pro

cess

ing

and

pars

ing.

*/in

tb

=a

-a;

/*C

pre

pro

cess

ing

and

pars

ing.

*/in

tb

=a/4

;-a

;

Not

e,in

gene

rali

tis

best

tous

ew

hite

spac

ear

ound

oper

ator

san

dot

her

synt

actic

elem

ents

,

const

char

*x=

"hello

";in

tfo

o(c

onst

char

*=

x);

//O

Kin

tbar

(char*

=x)

;//

Err

or

Cop

yrig

htc

1997

-200

0D

ept.

ofC

ompu

ter

Sci

ence

,Was

hing

ton

Uni

vers

ity

CS 342: OO Software Development Lab OO Programming with C++

Type-Safe Linkage� Type-safe linkage allows the linker to detect when a function is

declared and/or used inconsistently, e.g.,

// File abs.clong abs (long arg){

return arg < 0 ? -arg : arg;}

// File application.c#include <stdio.h>int abs (int arg);int main (int, char *[]) {

printf (%d\n, abs (-1));}

Copyright c 1997-2000 Dept. of Computer Science, Washington University 75

Page 20: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Programming with C++

Type-Safe Linkage (cont’d)

� Without type-safe linkage, this error would remain hidden until theapplication was ported to a machine where int s and long s weredifferent sizes

– e.g., Intel 80286

� Type-safe linkage encodes all C++ function names with the types oftheir arguments, called name mangling, e.g.,

long abs (long arg) -> _abs__Flint abs (int arg) -> _abs__Fi

� Therefore, the linker may be used to detect mismatches betweenfunction prototypes, function definitions, and function usage

Copyright c 1997-2000 Dept. of Computer Science, Washington University 76

CS 342: OO Software Development Lab OO Programming with C++

Type-Safe Linkage (cont’d)

� Name mangling was originally created to support overloadresolution

� Only function names are mangled

– i.e., variables, constants, enums, and types are not mangled . . .

� On older C++ compilers, diagnostic messages from the linker aresometimes rather cryptic!

– See the c++filt program . . .

Copyright c 1997-2000 Dept. of Computer Science, Washington University 77

CS 342: OO Software Development Lab OO Programming with C++

Type-safe Linkage (cont’d)

� Language interoperability issues

– This problem arises as a side effect of using type-safe linkage inC++

– C functions used in C++ code (e.g., standard Unix libraryfunctions) must be explicitly declared as requiring C linkage (i.e.,names are not mangled) via the new extern C declaration

extern "C" int abs (int i);double abs (double d);Complex abs (Complex &c);

int foo (int bar) {cout << abs (Complex (-10, 4.5)) // calls _abs__F7Complex

<< abs (bar) // calls _abs<< abs (3.1416); // calls _abs__Fd

}

Copyright c 1997-2000 Dept. of Computer Science, Washington University 78

CS 342: OO Software Development Lab OO Programming with C++

Type-safe Linkage (cont’d)� Language interoperability issues (cont’d)

– Other syntactic forms of extern blocks:extern "C" {

char *mktemp (const char *);char *getenv (const char *);

}– Encapsulating existing header files

#ifdef __cplusplusextern "C" {#endif /* __cplusplus */#include <string.h>#ifdef __cplusplus}#endif /* __cplusplus */

– Note, extern blocks may also be used to support otherlanguages, e.g., Fortran, Pascal, Java, Basic, Ada, etc.

Copyright c 1997-2000 Dept. of Computer Science, Washington University 79

Page 21: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Programming with C++

Inline Functions

� Many programming languages force developers to choose between:

1. Modularity/abstraction (function call)2. Performance (macro or inline-expansion by-hand)

� C++ allows inline function expansion, which has several advantages:

1. Combines the efficiency of a macro with the type-security andabstraction of a function call

2. Reduces both execution time and code size (potentially)3. Discourages the traditional reliance upon macro preprocessor

statements

Copyright c 1997-2000 Dept. of Computer Science, Washington University 80

CS 342: OO Software Development Lab OO Programming with C++

Inline Functions (cont’d)

� Here’s an example of a common C problem with the preprocessor:

– Classic C macro, no sanity-checking at macro expansion time#define SQUARE(X) ((X) * (X))int a = SQUARE (10); // ok

int b = SQUARE (a++); // trouble!!! (a++) * (a++)– C++ inline function template

template<class T> inlineT square (T x) { return x * x; }

int c = square (a++); // OK

Copyright c 1997-2000 Dept. of Computer Science, Washington University 81

CS 342: OO Software Development Lab OO Programming with C++

Inline Functions (cont’d)

� Points to consider about inline functions:

1. Class methods that are defined in their declaration areautomatically expanded inline

2. It is difficult to debug code where functions have been inlineexpanded and/or optimized

3. Compilers require more time and space to compile when thereare many inline functions

4. Inline functions do not have the pseudo-polymorphic properties ofmacros– However, inline templates approximate this functionality

5. Compilers often have limits on the size and type of function thatcan be inlined.

Copyright c 1997-2000 Dept. of Computer Science, Washington University 82

CS 342: OO Software Development Lab OO Programming with C++

Inline Functions (cont’d)� Size can be deceiving

– e.g., if stack frame is very large:int foo (void) {

int local_array[1000000];// . . .

– This can cause surprising explosion of code/data size, e.g.,int bar (void) { foo (); foo (); }

Copyright c 1997-2000 Dept. of Computer Science, Washington University 83

Page 22: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS

342:O

OS

oftware

Developm

entLabO

OP

rogramm

ingw

ithC

++

InlineF

unctions(cont’d)

Toshow

inliningin

C+

+,w

e’lldiscussa

simple

run-time

functioncall

tracefacility

–P

rovidesa

rudimentary

debuggingtool

e.g.,usefulforlong-running

network

servers

The

goalsare

tobe

ableto:

1.D

etermine

thedynam

icfunction

callingbehavior

oftheprogram

,i.e.,tracing

2.A

llowfor

fine-graincontrolover

whether

tracingis

enabled,e.g.,–

Atcom

pile-time

(remove

alltracesofTrace

andincur

norun-tim

epenalty)

–A

trun-time

(viasignals

and/orcom

mand-line

options)3.

Make

iteasyto

automate

sourcecode

instrumentation

–e.g.,w

ritea

regularexpression

tom

atchfunction

definitionsand

theninsertcode

automatically

Copyright

c

1997-2000D

ept.ofC

omputer

Science,W

ashingtonU

niversity84

CS 342: OO Software Development Lab OO Progra

Inline Functions (cont’d)

� Example output:

% CC -D__INLINE__ main.cpp trace.cpp% a.out 10 1enter int main (int argc, char *argv[]) in file main.cpp on li n

enter void foo (void) (file main.cpp, line 8)enter void foo (void) in (file main.cpp, line 8)

enter void foo (void) in (file main.cpp, line 8)enter void foo (void) in (file main.cpp, line 8)

enter void foo (void) in (file main.cpp, line 8)enter void foo (void) in (file main.cpp, line 8)

enter void foo (void) in (file main.cpp, line 8)enter void foo (void) in (file main.cpp, line 8)

enter void foo (void) in (file main.cpp, line 8)enter void foo (void) in (file main.cpp, line 8)

enter void foo (void) in (file main.cpp, line 8)leave void foo (void)

leave void foo (void)leave void foo (void)

leave void foo (void)leave void foo (void)

leave void foo (void)leave void foo (void)

leave void foo (void)leave void foo (void)

leave void foo (void)leave void foo (void)

leave int main (int argc, char *argv[])

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS 342: OO Software Development Lab OO Progra

Inline Functions (cont’d)#include "Trace.h"

void foo (int max_depth) {T ("void foo (void)");// Trace __ ("void foo (void)", 8, "main.cpp")if (max_depth > 0)

foo (max_depth - 1);// Destructor called automatically.

}

int main (int argc, char *argv[]) {const int max_depth =

argc = = 1 ? 10 : atoi (argv[1]);if (argc > 2)

Trace::set_nesting_indent (atoi (argv[2]));if (argc > 3)

Trace::stop_tracing ();T ("int main (int argc, char *argv[])");foo (max_depth);return 0;// Destructor called automatically.

}

Copyright c 1997-2000 Dept. of Computer Science, Washington University

CS 342: OO Software Development Lab OO Progra

Inline Functions (cont’d)

#ifndef _TRACE_H# define _TRACE_H# ifdef NTRACE /* compile-time omission */# define T(X)# else /* ! NTRACE */# define T(X) Trace __ (X, __LINE__, __FILE__)# endif /* ! NTRACE */

Class Trace { public:Trace (const char *n, int line = 0,

const char *file = );˜Trace (void);static void start_tracing (void);static void stop_tracing (void);static int set_nesting_indent (int indent);

private:static int nesting_depth_;static int nesting_indent_;static int enable_tracing_;const char *name_;

};#ifdef __INLINE__# define INLINE inline# include "Trace.i"#else# define INLINE#endif /* __INLINE__ */#endif /* _TRACE_H */

Copyright c 1997-2000 Dept. of Computer Science, Washington University

Page 23: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Programming with C++

Inline Functions (cont’d)// Trace.i#include <stdio.h>INLINETrace::Trace (const char *n, int line, const char *file){

if (Trace::enable_tracing_)fprintf (stderr, "%*senter %s (file %s, line %d)\n,"

Trace::nesting_indent_ *Trace::nesting_depth_++, "", this->name_ = n, file, line);

}

INLINETrace::˜Trace (void){

if (Trace::enable_tracing_)fprintf (stderr, "*sleave %s\n",

Trace::nesting_indent_ *--Trace::nesting_depth_, "", this->name_);

}

Copyright c 1997-2000 Dept. of Computer Science, Washington University 88 CS

342:

OO

Sof

twar

eD

evel

opm

entL

abO

OP

rogr

a

Inlin

eF

unct

ions

(con

t’d)

//T

race

.cpp

#in

clude

"Tra

ce.h

"

#ifn

def

__IN

LIN

E__

#in

clude

"Tra

ce.i"

#endif

/*__IN

LIN

E__

*/

//S

tatic

initi

aliz

atio

ns

int

Tra

ce::nest

ing_depth

_=

0;

int

Tra

ce::nest

ing_in

den

t_=

3;

int

Tra

ce::enable

_tr

aci

ng_

=1;

void

Tra

ce::st

art

_tr

aci

ng

(void

){

Tra

ce::enable

_tr

aci

ng_

=1;

} void

Tra

ce::st

op_tr

aci

ng

(void

){

Tra

ce::enable

_tr

aci

ng_

=0;

} int

Tra

ce::se

t_nest

ing_in

den

t(int

indent)

{in

tre

sult

=T

race

::nest

ing_in

dent_

;T

race

::nest

ing_in

dent_

=in

dent;

retu

rnre

sult;

} Cop

yrig

htc

1997

-200

0D

ept.

ofC

ompu

ter

Sci

ence

,Was

hing

ton

Uni

vers

ity

CS 342: OO Software Development Lab OO Programming with C++

Dynamic Memory Management

� Dynamic memory management is a built-in language construct, e.g.,

int *a = new int[10];int *b = new int;// . . .delete [] a;delete b;

� Built-in support for memory management improves:

1. Type-security2. Extensibility3. Efficiency

Copyright c 1997-2000 Dept. of Computer Science, Washington University 90

CS 342: OO Software Development Lab OO Programming with C++

Const Type Qualifier� C++ data objects and methods are qualifiable with the keyword

const , making them act as read-only objects

– e.g., placing them in the text segment– const only applies to objects, not to types

Copyright c 1997-2000 Dept. of Computer Science, Washington University 91

Page 24: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Programming with C++

Const Type Qualifier, (cont’d)const char *foo = "on a clear day";char *const bar = "you can C forever!";const char *const zippy = "yow!";

foo = "To C or not to C?"; // OKfoo[7] = ’C’; // error, read-only location

// error, can’t assign to const pointer barbar = "avoid cliches like the plague.";// OK, but be careful of read-only memory!!!bar[1] = ’D’;

const int index = 4 - 3; // index == 1// read-only an array of constant intsconst int array[index + 3] = {2, 4, 8, 16};

Copyright c 1997-2000 Dept. of Computer Science, Washington University 92

CS 342: OO Software Development Lab OO Programming with C++

Const Type Qualifier (cont’d)

� User-defined const data objects:

– A const qualifier can also be applied to an object of auser-defined type, e.g.,const String string_constant (Hi, I’m read-only!);const Complex complex_zero (0.0, 0.0);string_constant = "This will not work!"; // ERRORcomplex_zero += Complex (1.0); // ERRORcomplex_zero == Complex (0.0); // OK

� Ensuring const correctness is an important aspect of designing C++interfaces, e.g.,

1. It ensures that const objects may be passed as parameters2. It ensures that data members are not accidentally corrupted

Copyright c 1997-2000 Dept. of Computer Science, Washington University 93

CS 342: OO Software Development Lab OO Programming with C++

Const Type Qualifier (cont’d)

� const methods may specify that certain read-only operations takeplace on user-defined const objects, e.g.,class String {public:

size_t size (void) const { return this->len_; }void set (size_t index, char new_char);// . . .

private:size_t len;

};

const String string_constant (hello);string_constant.size (); // Fine

� A const method may not directly modify its this pointerstring_constant.set (1, ’c’); // Error

Copyright c 1997-2000 Dept. of Computer Science, Washington University 94

CS 342: OO Software Development Lab OO Programming with C++

Stream I/O� C++ extends standard C library I/O with stream and iostream

classes

� Several goals

1. Type-Security– Reduce type errors for I/O on built-in and user-defined types

2. Extensibility (both above and below)– Allow user-defined types to interoperate syntactically with

existing printing facilities– Contrast with printf/scanf -family– Transparently add new underlying I/O devices to the iostream

model– i.e., share higher-level formatting operations

Copyright c 1997-2000 Dept. of Computer Science, Washington University 95

Page 25: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Programming with C++

Stream I/O (cont’d)

� The stream and iostream class categories replace stdin , stdout ,and stderr with cout , cin , and cerr

� These classes may be used by overloading the ¡¡ and ¿¿ operators

– C++ does not get a segmentation fault since the correct functionis called#include <iostream.h>char *name = joe;int id = 1000;cout << "name = " << name << ", id = " << id << ’\n’;// cout.operator<< (name = ).operator<< (joe) . . .

– In contrast, old C-style I/O offers no protection from mistakes, andgets a segmentation fault on most systems!

printf (name = %s, id = %s\n, name, id);

Copyright c 1997-2000 Dept. of Computer Science, Washington University 96

CS 342: OO Software Development Lab OO Programming with C++

Boolean Type

� C++ a bool built-in type

– The bool values are called true and false– Converting numeric or pointer type to bool takes 0 to false and

anything else to true– bool promotes to int , taking false to 0 and true to 1– Statements such as if and while are converted to bool– All operators that conceptually return truth values return bool

� e.g., the operands of &&, ——, and !, but not &, —, and

Copyright c 1997-2000 Dept. of Computer Science, Washington University 97

CS 342: OO Software Development Lab OO Programming with C++

References

� C++ allows references, which may be:

1. Function parameters2. Function return values3. Other objects

� A reference variable creates an alternative name (alias) for an object

� References may be used instead of pointers to facilitate:

1. Increased code clarity2. Reduced parameter passing costs3. Better compiler optimizations

� References use call-by-value syntax, but possess call-by-referencesemantics

Copyright c 1997-2000 Dept. of Computer Science, Washington University 98

CS 342: OO Software Development Lab OO Programming with C++

References (cont’d)� e.g., consider a swap abstraction:

void swap (int x, int y) // pass by value!{ // requires function call!

int t = x; x = y; y = t;// only works for ints!}

int main (int, char *[]) {int a = 10, b = 20;printf (a = %d, b = %d\n, a, b);swap (a, b);printf (a = %d, b = %d\n, a, b);

}

Copyright c 1997-2000 Dept. of Computer Science, Washington University 99

Page 26: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Programming with C++

References (cont’d)void swap (int *xp, int *yp) {int t = *xp; *xp = *yp; *yp = t; }

int main (int, char *[]) {int a = 10, b = 20;printf (a = %d, b = %d\n, a, b);swap (&a, &b);printf (a = %d, b = %d\n, a, b); }

#define swap(X,Y,T) \do {T __ = (X); (X) = (Y); (Y) = __;} while (0)

int main (int, char *[]) {int a = 10, b = 20;printf (a = %d, b = %d\n, a, b);swap (a, b, int); // beware of a++!printf (a = %d, b = %d\n, a, b); }

Copyright c 1997-2000 Dept. of Computer Science, Washington University 100

CS 342: OO Software Development Lab OO Programming with C++

References (cont’d)template <class T> inline voidswap (T &x, T &y) {

T t = x; x = y; y = t; }

int main () {int a = 10, b = 20;double d = 10.0, e = 20.0;

printf (a = %d, b = %d\n, a, b);printf (d = %f, e = %e\n, d, e);swap (a, b);swap (d, e);printf (a = %d, b = %d\n, a, b);printf (d = %f, e = %e\n, d, e);

}

Copyright c 1997-2000 Dept. of Computer Science, Washington University 101

CS 342: OO Software Development Lab OO Programming with C++

References (cont’d)

10

iir

� With references (as with classes), it is important to distinguishinitialization from assignment, e.g.,

int i = 10;// initialization of irint &ir = i; // Equivalent to: int *const ip = &i;ir = ir + 10; // dereference is automatically done,

// equivalent to: *ip = *ip + 10;

Copyright c 1997-2000 Dept. of Computer Science, Washington University 102

CS 342: OO Software Development Lab OO Programming with C++

References (cont’d)� Once initialized, a reference cannot be changed

– i.e., it may not be reassigned to reference a new location– Note, after initialization all operations affect the referenced object

� i.e., not the underlying const pointer . . .

Copyright c 1997-2000 Dept. of Computer Science, Washington University 103

Page 27: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Programming with C++

Type Cast Syntax

� C++ introduces a new type cast syntax in addition to Classic C stylecasts. This function-call syntax resembles the type conversionsyntax in Ada and Java, e.g.,

// function prototype from math.h libraryextern double log10 (double param);

/* C style type cast notation */if ((int) log10 ((double) 7734) != 0);

// C++ function-style cast notationif (int (log10 (double (7734))) != 7734);

� This “function call” is performed at compile time

Copyright c 1997-2000 Dept. of Computer Science, Washington University 104

CS 342: OO Software Development Lab OO Programming with C++

Type Cast Syntax (cont’d)

� This type cast syntax is also used to specify explicit type conversionin the C++ class mechanism

– This allows multiple-argument casts, i.e., “constructors”, e.g.,

class Complex {public:

Complex (double, double = 0.0);// . . .

private:double real, imaginary;

};// Convert 10.0 and 3.1416 into a Complex objectComplex c = Complex (10.0, 3.1416);// Note that old-style C syntax would not suffice here . .Complex c = (Complex) (10.0, 3.1416);

Copyright c 1997-2000 Dept. of Computer Science, Washington University 105

CS 342: OO Software Development Lab OO Programming with C++

Type Cast Syntax (cont’d)

� Note, there are a variety of syntactical methods for constructingobjects in C++, e.g.,

1. Complex c1 = 10.0;2. Complex c2 = (Complex) 10.0;3. Complex c3 = Complex (10.0);4. Complex c4 (10.0);

� I recommend version 4 since it is the most consistent and alsoworks with built-in types . . .

– It also generalizes to multiple-argument casts . . .

Copyright c 1997-2000 Dept. of Computer Science, Washington University 106

CS 342: OO Software Development Lab OO Programming with C++

Default Parameters� C++ allows default argument values in function definitions

– If trailing arguments are omitted in the actual function call thesevalues are used by default, e.g.,void assign_grade (char *name, char *grade = A);// additional declarations and definitions . . .

assign_grade (Bjarne Stroustrup, C++);// Bjarne needs to work harder on his tasks

assign_grade (Jean Ichbiah);// Jean gets an A for Ada!

� Default arguments are useful in situations when one must change aclass without affecting existing source code

– e.g., add new params at end of argument list (with default values)

Copyright c 1997-2000 Dept. of Computer Science, Washington University 107

Page 28: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Programming with C++

Default Parameters (cont’d)

� Default parameter passing semantics are similar to those inlanguages like Java:

– e.g., only trailing arguments may have defaults// Incorrectint x (int a = 10, char b, double c = 10.1);

– Note, there is no support for named parameter passing

� However, it is not possible to omit arguments in the middle of a call,e.g.,extern int foo (int = 10, double = 2.03, char = ’c’);

foo (100, , ’d’); /* ERROR!!! */foo (1000); /* OK, calls foo (1000, 2.03, ’c’);

� There are several arcane rules that permit successive redeclarationsof a function, each time adding new default arguments

Copyright c 1997-2000 Dept. of Computer Science, Washington University 108

CS 342: OO Software Development Lab OO Programming with C++

Declaration Statements

� C++ allows variable declarations to occur anywhere statementsoccur within a block

– The motivations for this feature are:1. To localize temporary and index variables2. Ensure proper initialization

– This feature helps prevent problems like:int i, j;/* many lines of code . . . */// Oops, forgot to initialize!while (i < j) /* . . . */;

– Instead, you can use the followingfor (int i = x, j = y ; i < j; )

/* . . . */;

Copyright c 1997-2000 Dept. of Computer Science, Washington University 109

CS 342: OO Software Development Lab OO Programming with C++

Declaration Statements (cont’d)

� The following example illustrates declaration statements and alsoshows the use of the scope resolution operator

#include <iostream.h>struct Foo { Static int var; };int Foo::var = 20;const int MAX_SIZE = 100;int var = 10;

Copyright c 1997-2000 Dept. of Computer Science, Washington University 110

CS 342: OO Software Development Lab OO Programming with C++

Declaration Statements (cont’d)intmain (int, char *[]) {

int k;k = call_something ();// Note the use of the scope resolution operator// (::) to access the global variable {\tt var}int var = ::var - k + Foo::var;

for (int i = var; i < MAX_SIZE; i++)for (int j = 0; j < MAX_SIZE; j++) {

int k = i * j;cout << k;double va r = k + ::var * 10.4;cout << var;

}}

Copyright c 1997-2000 Dept. of Computer Science, Washington University 111

Page 29: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Programming with C++

Declaration Statements (cont’d)

� However, the declaration statement feature may encourage ratherobscure code since the scoping rules are not always intuitive ordesirable

� Note, ANSI C++ allows definitions in the switch , while , and ifcondition expressions . . .

� The scope of the definition of i in the following loops is limited to thebody of the for loop:

for (int i = 0; i < 10; i++)/* . . . */;

for (int i = 0; i < 20; i++)/* . . . */;

However, older compilers don’t restrict the scope, so they’ll complainabout multiple declarations of i .

Copyright c 1997-2000 Dept. of Computer Science, Washington University 112

CS 342: OO Software Development Lab OO Programming with C++

Abbreviated Type Names

� Unlike C, C++ allows direct use of user-defined type tag names,without requiring a preceding union , struct , class , or enumspecifier, e.g.,struct Tree_Node { // C code

int item_;struct Tree_Node *l_child_, *_child_;

};

struct Tree_Node { // C++ codeint item_;Tree_Node *l_child_, *r_child_;

}

� Another way of looking this is to say that C++ automaticallytypedef s tag names, e.g.,

typedef struct Tree_Node Tree_Node;

Copyright c 1997-2000 Dept. of Computer Science, Washington University 113

CS 342: OO Software Development Lab OO Programming with C++

Abbreviated Type Names, (cont’d)

� Note, this C++ feature is incompatible with certain classic and ANSIC identifier naming conventions, e.g.,

struct Bar { /* . . . */ };struct Foo { };typedef struct Foo Bar; // Illegal C++, legal C!

Copyright c 1997-2000 Dept. of Computer Science, Washington University 114

CS 342: OO Software Development Lab OO Programming with C++

User-Defined Conversions� The motivation for user-defined conversions are similar to those for

operator and function overloading

– e.g., reduces tedious redundancy in source code– However, both approaches have similar problems with readability

. . .

� User-defined conversions allow for more natural lookingmixed-mode arithmetic for user-defined types, e.g.,Complex a = Complex (1.0);Complex b = 1.0; // implicit 1.0 -> Complex (1.0)

a = b + Complex (2.5);a = b + 2.5 // implicit 2.5 -> Complex (2.5)

String s = a; // implicit a.operator String ()

Copyright c 1997-2000 Dept. of Computer Science, Washington University 115

Page 30: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Programming with C++

User-Defined Conversions (cont’d)

� Conversions come in two flavors:

1. Constructor Conversions: Create a new object from objects ofexisting types

2. Conversion Operators: Convert an existing object into an object ofanother type

class Complex {public:

Complex (double); // convert double to Complexoperator String (); // convert Complex to String// . . .

};int foo (Complex c) {

c = 10.0; // c = Complex (10.0);String s = c; // c.operator String ();cout << s; }

Copyright c 1997-2000 Dept. of Computer Science, Washington University 116

CS 342: OO Software Development Lab OO Programming with C++

User-Defined Conversions (cont’d)

� The compiler first tries a single level of user-defined conversion todetermine if a type-signature matches a particular use, e.g.,

class String {public:

String (const char *s);String &operator += (const String &);

};String s;s += hello; // s += String (hello);

� Note, it is easy to make a big mess by abusing the user-definedconversion language feature . . .

– Especially when conversions are combine with templates,inheritance virtual methods, and overloading, etc.

Copyright c 1997-2000 Dept. of Computer Science, Washington University 117

CS 342: OO Software Development Lab OO Programming with C++

Static Initialization

� Static initializers can be comprised of arbitrary C++ expressions,e.g.,

extern int foo (void); // file scopeint a = 100;int i = 10 + foo ();int j = i + *new int (1);

int foo (void) {static int k = foo ();return 100 + a;

}

� Note, needless to say, this can become rather cryptic, and the orderof initialization is not well defined between modules

Copyright c 1997-2000 Dept. of Computer Science, Washington University 118

CS 342: OO Software Development Lab OO Programming with C++

Miscellaneous Differences� In C++, sizeof (’a’) == sizeof (char); in C, sizeof (’a’) ==

sizeof (int )

– This facilitates more precise overloading . . .

� char str[5] = hello is valid C, but C++ gives error because initializeris too long (because of hidden trailing ’0’)

� In C++, a function declaration int f(); means that f takes noarguments (same as int f(void );). In C it means that f can takeany number of arguments of any type at all!

– C++ would use int f ( . . .);

� In C++, a class may not have the same name as a typedefdeclared to refer to a different type in the same scope

Copyright c 1997-2000 Dept. of Computer Science, Washington University 119

Page 31: CS 342: Object-Oriented Software Development Lab A Tour ...cse870/Materials/C++/c++-tour_4.pdf · function prototypes Provides type-safe linkage Provides inline function expansion

CS 342: OO Software Development Lab OO Programming with C++

Miscellaneous Differences (cont’d)

� In C++, a struct or class is a scope; in C a struct , enum, orenum literal are exported into the global scope e.g., struct Fooenum Bar baz, foobar, bizbuzz; ; /* Valid C, invalid C++ */ enum Barbar = baz; // Valid C++, invalid C Foo::Bar bar = Foo::baz;

� The type of an enum literal is the type of its enumeration in C++; inC it is an int, e.g.,

/* True in C, not necessarily true in C++. */sizeof baz == sizeof (int);/* True in C++, not necessarily true in C. */sizeof Foo::baz == sizeof (Foo::Bar);

Copyright c 1997-2000 Dept. of Computer Science, Washington University 120

CS 342: OO Software Development Lab OO Programming with C++

Miscellaneous Differences (cont’d)

� In ANSI C, a global const has external linkage by default; in C++ ithas internal linkage, e.g., /* In C++, global1 is not visible to othermodules. */ const int global1 = 10; /* Adding extern makes it visibleto other modules. */ extern const int global2 = 100;

� In ANSI C, a void * may be used as the right-hand operand of anassignment or initialization to a variable of any pointer type, whereasin C++ it may not (without using a cast . . .)

void *malloc (size_t);/* Valid C, invalid C++ */int *i = malloc (10 * sizeof *i);/* Valid C, valid C++ */int *i = (int *) malloc (10 * sizeof *i);

Copyright c 1997-2000 Dept. of Computer Science, Washington University 121

CS

342:

OO

Sof

twar

eD

evel

opm

entL

abO

OP

rogr

a

Sum

mar

y

C+

+ad

dsm

any,

man

y,m

any

new

feat

ures

toth

eC

prog

ram

min

gla

ngua

ge

Itis

notn

eces

sary

tous

eal

lthe

feat

ures

inor

der

tow

rite

effic

ient

,und

erst

anda

ble,

port

able

appl

icat

ions

Am

ajor

cont

ribut

ion

ofC

++

isits

supp

ortf

orde

finin

gab

stra

ctda

taty

pes

(AD

Ts)

–e.

g.,c

lass

es,p

aram

eter

ized

type

s,an

dex

cept

ion

hand

ling

For

som

esy

stem

s,C

++

’sA

DT

supp

orti

sm

ore

impo

rtan

ttha

nus

ing

the

OO

feat

ures

ofth

ela

ngua

ge

For

othe

rsy

stem

s,th

eus

eof

C+

+’s

OO

feat

ures

ises

sent

ialt

obu

ildhi

ghly

flexi

ble

and

exte

nsib

leso

ftwar

e

–e.

g.,i

nher

itanc

e,dy

nam

icbi

ndin

g,an

dR

TT

I

Cop

yrig

htc

1997

-200

0D

ept.

ofC

ompu

ter

Sci

ence

,Was

hing

ton

Uni

vers

ity