Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer...

63
COEN244:Programming Methodology II Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates OOP/C++: General advice Is C++ better than ... About the final exam Sample final exam question c A. Amer COEN244: Introduction 1

Transcript of Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer...

Page 1: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

COEN244:Programming Methodology II

Aishy Amer

Electrical & Computer Engineering

Lecture Outline:

C++/OOP

this pointer

Operator overloading

Polymorphism

Templates

OOP/C++: General advice

Is C++ better than ...

About the final exam

Sample final exam question

c© A. Amer COEN244: Introduction 1

Page 2: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

COEN244

Part I:

data encapsulation and information hiding:

basic principles of OOP with building C++ code and analyzinginteractions between classes

Exceptions handling

Part II:

grouping classes (Software reuse)

class composition and class inheritance

Part III (advanced uses):

Polymorphism, virtual functions, dynamic binding

Abstract classes (software extensibility)

Templates (generic code) and data structurec© A. Amer COEN244: Introduction 2

Page 3: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Shortcomings of functional programming

Functions access the same data? They belong together?

OOP solution: binding together functions and data, classes

Encapsulation is voluntary: client can change any data:

OOP solution: private and public members

Functions are global: names can conflict

OOP solution: class scope

Data has to be initialized by client code

OOP solution: constructors

→ Using functions leaves many issues unsolved

c© A. Amer COEN244: Introduction 3

Page 4: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Object Oriented Programming

OOP is expressed in terms of operations over data

Data and operations are bind together in a class construct

Each class has its own separate scope

Functions with same name but different classes do notconflict

The data becomes the internal state of the object

OOP allows the interface to be visible while hiding theimplementation details

Everything is an object

Objects communicate by messages

c© A. Amer COEN244: Introduction 4

Page 5: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Object Oriented Programming

The state of objects is changed by invoking a method

Each object is an instance of a class

A class defines the behavior of all of its instances

A class has private and public (data & function) members

Private member: can only be accessed from within theclass

Public member: can be accessed from anywhere in aprogram

Classes are organized in an inheritance hierarchy

c© A. Amer COEN244: Introduction 5

Page 6: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Classes

Access member specifiers (public, private, protected)

Member Functions & Member Data

Declaration and Definition

(Inline Implementation)

Creating and Using Objects

Constructor (Default, Overloaded, Copy, Conversion)

Destructorto deallocate memory or/and to change static data (e.g.,count–)

Memberwise Assignment vs. Copy constructor

c© A. Amer COEN244: Introduction 6

Page 7: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Classes

Constant ObjectsNeed const functions

Constant Data MembersMember Initialization List

Static Data MembersInitialized at File Scope

Static Member FunctionsUsed to Access Static Data Members

c© A. Amer COEN244: Introduction 7

Page 8: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Classes

Friend Functions & ClassesAccess to private members

this Pointer:Every object that gets created has access to its ownaddressEvery member function (not friends nor static) hasaccess to the this pointerMain use: defining member functions that manipulatepointers directly

Dynamic Memorynew/delete Operator

c© A. Amer COEN244: Introduction 8

Page 9: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

this pointer

Every object that gets created has access to its ownaddress

An object can be implicitly accessed via the this pointer

It is like a constant private "implicit" data member

Every member function (not friends nor static) has accessto the this pointer

const member functions receive a constant this pointer toconstant data

Non-const member functions receive a constant this pointerto non-constant data

Its main use is for defining member functions thatmanipulate pointers directly

c© A. Amer COEN244: Introduction 9

Page 10: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

this pointer

Class t r i a n g l e {/ / assume pt2d ( a po in t i n 2D) i s a c lass def ined p rev ious l ypr iva te : pt2d∗ v e r t i c e s ;publ ic :/ / cons t ruc to r s/ / copy assignment opera tort r i a n g l e operator =( const t r i a n g l e& t ) ;

. . . . }t r i a n g l e t r i a n g l e : : operator =( const t r i a n g l e& t ){ i f ( th i s !=& t ) / / s e l f−assignment l i k e t = t ?

fo r ( i n t i =0; i <3; i ++) v e r t i c e s [ i ] = t . v e r t i c e s [ i ] ;return ∗ th i s ;

}

c© A. Amer COEN244: Introduction 10

Page 11: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Operator Overloading

Goal: treat programmer-defined and built-in types equally

Overload as Member Function

Overload as Friend FunctionWhy? operators that have another class (or built-in type) asthe left operand, e.g., <<

Stream Insertion/Extraction Overload (as friend)

Special cases:Subscript Operator Subscript OperatorParentheses OperatorIncrement/Decrement Operator

Multi-Overload DefinitionsMay re-overload a function

c© A. Amer COEN244: Introduction 11

Page 12: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Inheritance / Composition

Composition: "has a" relationship (a Rectangle has a Point)

Inheritance: "is a" relationship (a Rectangle is a Shape)

Inheritance: Base and Derived Classes

Protected Access Specifier: a protected member can beaccessed only by members of its class and by derivedclasses

Types of Inheritancepublic (most used): base public members becomepublic of the derived class AND protected becomeprotectedprotected: base public & protected members becomeprotected members of the derived classprivate: all fields of the base class are treated as private

c© A. Amer COEN244: Introduction 12

Page 13: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Inheritance / Composition

Function Overriding

Dealing with Pointers to Base and Derived ClassesCast: explicit conversion of an object type

Multiple Inheritance: When a class has more than one baseclass

c© A. Amer COEN244: Introduction 13

Page 14: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Polymorphism

Static binding:the compiler selects a method from several possiblecandidates at compile time

Dynamic binding:the compiler selects a method from several possiblecandidates at run time

Virtual Functions- A function of the base class that can be over-ridden in aderived class- Virtual functions bind to the code associated with theclass of the object, rather than with the class of thepointer/reference

Polymorphic behavior works with pointers & references of base classes

c© A. Amer COEN244: Introduction 14

Page 15: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Polymorphism

Virtual destructor:

A virtual destructor is a virtual function that is needed if wewill delete (using the delete operator) a derived-class objectvia a base-class pointer

A class should have a virtual destructor unless that classhas NO virtual functions

If we have any virtual functions, then we probably going toprocess derived objects via a base pointer. Suchprocessing may include invoking a destructor (normallydone implicitly via delete)

Why is Polymorphism central to OO?

c© A. Amer COEN244: Introduction 15

Page 16: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Polymorphism

Abstract Base Class:a class with at least one pure virtual function AND an objectof an abstract base class cannot be instantiated

Pure Virtual FunctionsA function of the base that must be over-ridden in a derivedclass

Why is Polymorphism central to OO?

Because an old code (in the base class) call new code (inthe derived class)HOW? Explain!

You do not have to worry about the type of object you’redealing with

c© A. Amer COEN244: Introduction 16

Page 17: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Polymorphism: Using pointers to access objects

Recall:

A derived class is also a base class

A reference refer to a base class

When you pass a derived object to a function, the referenceto the base class will only look at the base portion of thepassed derived object reference

Virtual functions can be called via a base class pointer ORbase class reference

See class notes of week 10

c© A. Amer COEN244: Introduction 17

Page 18: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Using pointers to access objects: Example

/ / L i s t i n g 15.1 Using po in te r s to access ob jec ts o f base and der ived classesclass Base { / / base c lassprotected :

i n t x ;publ ic :

Base ( i n t a ) { x = a ; } / / to be used by Derivedvoid set ( i n t a ) { x = a ; } / / to be i n h e r i t e di n t show ( ) const { return x ; } / / to be i n h e r i t e d

} ;class Derived : publ ic Base { / / der ived c lasspr iva te :

i n t y ;publ ic :

Derived ( i n t a , i n t b ) : Base ( a ) , y ( b ){ } / / empty cons t ruc to r body

void access ( i n t &a , i n t &b ) const / / added i n der ived c lass{ a = Base : : x ; b = y ; } } ; / / OR a=x ;

c© A. Amer COEN244: Introduction 18

Page 19: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Using pointers to access objects: Example

i n t main ( ) {i n t x , y ;Derived ∗pd = new Derived (50 ,80 ) ; / / unnamed der ived ob jec tcout << " 1 . Derived po in te r , ob jec t , and der ived method \ n " ;pd−>access ( x , y ) ; / / no problem : type matchcout <<" x = " <<x <<" y = " <<y <<endl <<endl ; / / x=50 y=80

cout << " 2 . Derived po in te r , der ived ob jec t , base method \ n " ;cout << " x = " << pd−>show ( ) << endl << endl ; / / x = 50Base ∗pb = pd ; / / p o i n t e r to same ob jec t

cout << " 3 . Base po in te r , der ived ob jec t , base method \ n " ;cout << " x = " << pb−>show ( ) << endl << endl ; / / x = 50/ / pb−>access ( x , y ) ; / / e r r o r : no access to der ived method

c© A. Amer COEN244: Introduction 19

Page 20: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Using pointers to access objects: Example

cout << " 4 . Converted po in te r , der ived ob jec t and method \ n " ;( ( Derived ∗ ) pb)−>access ( x , y ) ; / / we know i t i s therecout <<" x = " <<x <<" y = " <<y <<endl <<endl ; / / x=50 y=80pb = new Base ( 6 0 ) ; / / unnamed base ob jec t

cout << " 5 . Base po in te r , base ob jec t , base method \ n " ;cout << " x = " << pb−>show ( ) << endl <<endl ; / / x = 60

cout << " 6 . Converted po in te r , base ob jec t , der ived method \ n " ;( ( Derived ∗ ) pb)−>access ( x , y ) ; / / pass on your own r i s kcout <<" x = " <<x <<" y = " <<y <<endl <<endl ; / / junk ! !delete pd ; delete pb ; / / necessary t i d i n e s s

return 0; }

c© A. Amer COEN244: Introduction 20

Page 21: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Polymorphism: When?

Recall: a derived class pointer can be assigned a baseclass pointer

⇒ Shape ∗ arr[10] : an array of pointers to the base class

Rectangle rec; arr[5] = &rec;

rec is the actual object and arr[5] is a pointer of type Shape

Assume we want to print the content of each object in thearray arr[i]− > print()

Since the pointer points to a Shape object, the print()function of the Shape (base) class is called – not theappropriate derived class function!!

Solution? selecting the appropriate function of a derived class atrun time (using virtual functions)

c© A. Amer COEN244: Introduction 21

Page 22: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Polymorphism: When?–Summary

So: when you have a pointer to an object, this actual objectmay be of a derived class

A pointer to an object of type Vehicle* maybe actuallypointing to a Car objectA pointer to an object of type Shape* maybe actuallypointing to a Rectangle object

Polymorphic behavior works with pointers & referencesof base classes

Dynamic binding implies that a base class pointer figuresout which derived class it really points to at run-time (or atexecution)

C++ dynamic binding is implemented with virtual functions

c© A. Amer COEN244: Introduction 22

Page 23: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Virtual functions

Even if the object is accessed by a base pointer virtual functions

allow derived classes to replace the implementation of a

function provided by the base class at run time.

The replacement is always called whenever the object in

question is of the derived class (even if the object is accessed by

a base pointer)

This allows algorithms in the base class to be replaced in the

derived class, even if users don’t know about the derived class

A function of the base class that can be over-ridden in a derived

class

Virtual functions bind to the code associated with the class of the

object, rather than with the class of the pointer/reference

c© A. Amer COEN244: Introduction 23

Page 24: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Virtual functions: Example

class Shape {protected :

i n t width , he igh t ;publ ic :

void set ( i n t a , i n t b ){ width=a ; he igh t=b ; }

v i r t u a l i n t area ( void ) / / area ( ) as v i r t u a l f u n c t i o n/ / makes here not much sense but we need i t l a t e r

{ return ( 0 ) ; }} ;

class Rectangle : publ ic Shape {publ ic :

i n t area ( void ){ return ( width ∗ he igh t ) ; }

} ;

c© A. Amer COEN244: Introduction 24

Page 25: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Virtual functions: Example

class Tr iang le : publ ic Shape {publ ic :

i n t area ( void ){ return ( width ∗ he igh t / 2 ) ; }

} ;

i n t main ( ) {Rectangle r e c t ;T r i ang le t r g l ;Shape poly ;Shape ∗ppoly1 = &r e c t ;Shape ∗ppoly2 = & t r g l ;Shape ∗ppoly3 = &poly ;

c© A. Amer COEN244: Introduction 25

Page 26: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Virtual functions: Example

ppoly1−>set ( 4 , 5 ) ;ppoly2−>set ( 4 , 5 ) ;ppoly3−>set ( 4 , 5 ) ;

/ / dynamic b ind ing :/ / At run−t ime the implementat ion o f the v i r t u a l f u n c t i o n/ / i s replaced by t h a t o f the der ived c lasscout << ppoly1−>area ( ) << endl ; / / ou tput : 20cout << ppoly2−>area ( ) << endl ; / / ou tput : 10cout << ppoly3−>area ( ) << endl ; / / ou tput : 0

/ / desp i te v i r t u a l i t y we can dec lare an ob jec t o f type Shape/ / and to c a l l i t s area ( ) f u n c t i o n

return 0;}

c© A. Amer COEN244: Introduction 26

Page 27: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Polymorphism: Virtual destructor

A virtual destructor is a virtual function that is needed if wewill delete (using the delete operator) a derived-class objectvia a base-class pointer

A class should have a virtual destructor unless that classhas NO virtual functions

If we have any virtual functions, then we probably going toprocess derived objects via a base pointer

Such processing may include invoking a destructor(normally done implicitly via delete)

the destructor of derived classes of a base class with virtualdestructors are also virtual

c© A. Amer COEN244: Introduction 27

Page 28: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Virtual destructor: Example

class Student {publ ic :

. . .~Student ( ) ; / / need to have i t v i r t u a l ~Student ( ) ;

protected :char ∗ name ;

} ;

class COEN244 : publ ic Student {publ ic :

. . .~COEN244 ( ) ;

pr iva te :char ∗ grade ;

} ;

c© A. Amer COEN244: Introduction 28

Page 29: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Virtual destructor: Example

void main ( ) {Student∗ pStud = new COEN244( " John " , " Smith " ) ;/ / pStud i s o f type Student and po in t s to a COEN244 ob jec t

pStud−>p r i n t ( ) ;. . .delete pStud ; / / w i l l c a l l the Student ob jec t ’ s d e s t r u c t o r}

⇒ The COEN244 object destructor will not be called

Not all memory is deallocated!!!

c© A. Amer COEN244: Introduction 29

Page 30: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Virtual destructor: Example

class Student {publ ic :

. . .v i r t u a l ~Student ( ) ;

protected :char ∗ name ;

} ;

⇒ When a Student pointer, pointing to a COEN244 object, isdeleted, the COEN244 destructor is called which in turn willcall the Student destructor

⇒ Virtual destructor violate the rule of virtual functions?(...name?)but memory leaks are very dangerous

c© A. Amer COEN244: Introduction 30

Page 31: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Virtual destructor: Example 2

class Base {publ ic :

Base ( i n t x ) ;v i r t u a l void p r i n t ( ) const ;v i r t u a l ~Base ( ) ;

protected :i n t a ;

} ;

class Derived : publ ic Base {publ ic :

Derived ( i n t x , i n t ∗ y ) ;void p r i n t ( ) const ;~Derived ( ) ;

protected :i n t ∗ b ;

} ;

c© A. Amer COEN244: Introduction 31

Page 32: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Virtual destructor: Example 2

class DDerived : publ ic Derived {publ ic :

DDerived ( i n t x , i n t ∗ y , i n t ∗ z ) ;void p r i n t ( ) const ;~DDerived ( ) ;

pr iva te :i n t ∗ c ;

} ;

c© A. Amer COEN244: Introduction 32

Page 33: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Virtual destructor: Example 2

Base : : Base ( i n t x ){ a=x ; cout << " Base : cons t ruc to r \ n " ; }Base : : ~ Base ( ) { cout << " Base : d e s t r u c t o r \ n " ; }

Derived : : Derived ( i n t x , i n t ∗ y ) : Base ( x ) {b=new i n t [ 3 ] ;fo r ( i n t i =0; i <5; i ++) b [ i ]= y [ i ] ;cout << " Derived : cons t ruc to r \ n " ;

}Derived : : ~ Derived ( ) { cout << " Derived : d e s t r u c t o r \ n " ; delete [ ] b ; }

DDerived : : DDerived ( i n t x , i n t ∗ y , i n t ∗ z ) : Derived ( x , y ) {c=new i n t [ 3 ] ;fo r ( i n t i =0; i <5; i ++) c [ i ]= z [ i ] ;cout << " DDerived : cons t ruc to r \ n " ;

}

DDerived : : ~ DDerived ( ) { cout << " DDerived : d e s t r u c t o r \ n " ; delete [ ] c ; }

c© A. Amer COEN244: Introduction 33

Page 34: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Virtual destructor: Example 2

i n t main ( ){

i n t y [ ] = { 1 , 2 , 3 } ;i n t z [ ] = { 4 , 5 , 6 } ;i n t x =9;

cout << " \ n−−−− t e s t i n g v i r t u a l l i t y w i th po in te r s \ n " ;Base∗ pa= new DDerived ( x , y , z ) ; / / the three cons t ruc to r s are c a l l e dpa−>p r i n t ( ) ;

delete pa ;/ / i f v i r t u a l d e s t r u c t o r i s not def ined then/ / on ly the base pa r t w i l l be de le ted/ / =>only the base c lass d e s t r u c t o r w i l l be c a l l e d ! ! Memory leak !

return 0;}

c© A. Amer COEN244: Introduction 34

Page 35: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Virtual destructor: Example 2

/∗ Output w i thou t v i r t u a l d e s t r u c t o r :−−−− t e s t i n g v i r t u a l l i t y w i th po in te r sBase : cons t ruc to rDerived : cons t ruc to rDDerived : cons t ruc to rDDerived : p r i n t 9Base : d e s t r u c t o r ∗ /

/∗ Output w i th v i r t u a l d e s t r u c t o r :−−−− t e s t i n g v i r t u a l l i t y w i th po in te r sBase : cons t ruc to rDerived : cons t ruc to rDDerived : cons t ruc to rDDerived : p r i n t 9DDerived : d e s t r u c t o rDerived : d e s t r u c t o rBase : d e s t r u c t o r ∗ /

}

c© A. Amer COEN244: Introduction 35

Page 36: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Polymorphism: Why it is central to OO?

Because an old code (in the base class) call new code (inthe derived class)HOW? Explain!

You do not have to worry about the type of object you’redealing with

... (See class notes of week 10)

c© A. Amer COEN244: Introduction 36

Page 37: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Templates

A template is a "type generator": a way to fabricate manysimilar classes or functions from one piece of code

Function & Class Templates: allows software reuse throughgeneric code

A class template: a class that can be “filled in” with varioustypes

template $<$class AType$>$class Array { pr iva te : AType x ; . . . } ;

Automatically Overloads at Compile Time

c© A. Amer COEN244: Introduction 37

Page 38: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Templates

A template parameter can beType parameter: the special notation ”typename T” or”class T” means T is a type parameter that can be givenany type as a value ORNontype parameter: normal function or class) styleparameters, such as int i specify nontype parametersNontype template arguments must be constant

Using Templates With Inheritance

c© A. Amer COEN244: Introduction 38

Page 39: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Templates

A template is a "type generator": a way to fabricate manysimilar classes or functions from one piece of code

Function & Class Templates: allows software reuse throughgeneric code

A class template: a class that can be “filled in” with varioustypes

template $<$class AType$>$class Array { pr iva te : AType x ; . . . } ;

Automatically Overloads at Compile Time

c© A. Amer COEN244: Introduction 39

Page 40: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Templates

A template parameter can beType parameter: the special notation ”typename T” or”class T” means T is a type parameter that can be givenany type as a value ORNontype parameter: normal function or class) styleparameters, such as int i specify nontype parametersNontype template arguments must be constant

Using Templates With Inheritance

c© A. Amer COEN244: Introduction 40

Page 41: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Containers

A container class includes a ‘dynamically’ createdcollection of components

A container is an object whose main purpose is to holdother objects that can be accessed by iterators and processedusing algorithms such as sort or search

Example: a vector is a container that holds objects of anytype that can be inserted and removed from it

Containers are defined in the namespace std and aredefined as template classes i different header files

Containers are template data structures

c© A. Amer COEN244: Introduction 41

Page 42: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Containers

The standard containers and their basic operations aredesigned to be very similar

For example: to get the number of elements in a containeruse the member function size

Every container provides iterators to traverse along itselements

An iterator is an object of some type and is used to refer toelements in a sequence

Iterators are like pointers to a container

Dereferencing an iterator give access to the container’selement

Using ++ on an iterator move the iterator to the nextelement in the container<

c© A. Amer COEN244: Introduction 42

Page 43: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

STL: Standard Template Library

Composed of Containers, Iterators, and Algorithms

Containers: Vectors, Lists, Deques, Stacks, PriorityQueues, Sets, Maps, Multisets, Multimaps

Iterators: input, output, forward, bidirectional, randomaccess

Algorithms: Sort, Search, Swap, Copy, Fill, Accumulate...

c© A. Amer COEN244: Introduction 43

Page 44: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Data Structures

Two types:

Static & Dynamic

Static:arrays, structs, classes

Dynamic:linked lists, stack, queues, binary trees, ..

Dynamic data structures resize themselves during programexecution

c© A. Amer COEN244: Introduction 44

Page 45: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Exception Handling

Exception handling allows the program to recognize theerror, deal with it (either recover or ”safely” exit), andreturn to program execution

try, throw, catch

Nested try Blocks

Multiple catch Blocks

"Catch-All" Block catch(...)

Re-throw

c© A. Amer COEN244: Introduction 45

Page 46: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

File I/O

Open Files for Input, Output, Append

Close Files

Read and Write Just Like cin and cout

c© A. Amer COEN244: Introduction 46

Page 47: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Summary

OOP is expressed in terms of operations over dataData and operations are bind together in a class construct

In OOP: the interface (i.e., public methods) indicates whatbehavior an object makes available

In OOP: the data becomes the internal state of the object

Overloading: When calling a function runs different codeaccording to the types and number of arguments provided

Polymorphism: not having to worry about the type of objectyou’re dealing with

Virtual function: a function that can be over-ridden in aderived class

c© A. Amer COEN244: Introduction 47

Page 48: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Summary

Abstract Class: a class with at least one pure virtualfunction

Abstract Data Type (ADT ): An abstract class

Pure Virtual function: a function that must be over-ridden ina derived class

Cast: explicit conversion of an object type

Container: A class that can hold other objects

Namespace: a scoping mechanism that can scan files

Template: A class that can be “filled in” with various types

The Standard Library: classes, algorithms, and functionobjects providing support for strings, vectors, lists, maps,strings and random numbers

c© A. Amer COEN244: Introduction 48

Page 49: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

O-OP/C++: General advice

The value of many OOP/C++ features only becomes clear when

you write large programs

Think in terms of objects rather than functions

Groups of objects are easier to organize (using inheritance) than

are groups of functions

Declarations should go in *.h files and definitions in *.cpp files

A OO program needed to be:

Portable: should work on different types of Unix (at least!)

Efficient with time and memory: able to cope with complex

structures (e.g., a tree contains thousands of files)

Customizable: flexible enough to suit various needs

c© A. Amer COEN244: Introduction 49

Page 50: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

O-OP/C++: General advice

Use references rather than pointers when you can

Use strings (not pointer to char when you can)

Create variables just before first use

Use exceptions when the code that has to deal with aproblem is far from the code that discovers the problem

Use const as much as possible: note that in C++, constvariables have internal linkage by default

Avoid pre-processor macros:const, inline, template and namespace replace most of#define usage, leading to stronger typing and better controlof scope

c© A. Amer COEN244: Introduction 50

Page 51: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

O-OP/C++: General advice

Avoid static except within functions

Use namespace rather than files to control scoping:functions can have shorter namesinformation hiding is easierit’s easier to switch between different implementations

c© A. Amer COEN244: Introduction 51

Page 52: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Object Oriented Philosophy

Data Encapsulation – Classes

Software Reuse – Inheritance, Composition, Templates(Generic Code)

Software Extensibility – Polymorphism

Portability (Exceptions, Templates, STL)

c© A. Amer COEN244: Introduction 52

Page 53: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Object Oriented Philosophy

Pushing responsibility from client to server classes

Moving responsibilities among classes to minimizecoordination and communication

Making program code self-explanatory

Minimizing visibility of program elements to other elementsif a function is only used by member function: declare asprivate

c© A. Amer COEN244: Introduction 53

Page 54: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Why is O-OP so important?

The software industry "failed" (?) to meet demands forlarge, complex software systems

But maybe this "failure" is actually due to largetechnological successes

Technological successes created a market where"structured" analysis, design and programming techniquescould not satisfy

This required to create a better paradigm

OOP: A more natural correspondence of the problemstatement to the program design

OOP exploit developer’s intuition through operatoroverloading, inheritance etc.This reduces the learning curve for (re)users

c© A. Amer COEN244: Introduction 54

Page 55: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Why is O-OP so important?

OOP improves the cost of (re)using/changing a software

OOP gives inheritance and dynamic binding:let old code call new code, making it possible to quicklyextend/adapt a software to new applications

Object-oriented techniques are probably the best way todevelop large, complex software systems and applications

c© A. Amer COEN244: Introduction 55

Page 56: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Is C++ better than ...

C++ is an OO programming languageBut C++ can (unfortunately) also be used as a traditionalprogramming language (as "as a better C")

Is C++ a useful language?Yes (and practical)

it includes CC++ has a huge installed base:you will find huge support for tools, environments,consulting services, etc.

c© A. Amer COEN244: Introduction 56

Page 57: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Is C++ better than ...

Is C++ a perfect language?No:

C++ was designed to be a practical tool for solving realworld problemsC++ is "inherited" from CC++ is complex and sometime violate its own rulesC++ includes complex features that produce hugeobject code

c© A. Amer COEN244: Introduction 57

Page 58: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Is C++ better than ...

Programming language selection is dominatedby business considerations NOT by technicalconsiderations

Important factors:availability of a programming environment for thedevelopment machinelicensing/legal issues of environmentsavailability of trained developers (and/or consultingservices)corporate culture/politics...

c© A. Amer COEN244: Introduction 58

Page 59: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Is C++ better than ...

Such considerations generally play a much greater rolethan technical details(such as compile time performance, runtime performance,static vs. dynamic typing, static vs. dynamic binding, etc.)

⇒ "Is language XXX better than ..." cannot be based only on

purely technical factors

c© A. Amer COEN244: Introduction 59

Page 60: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

About the final exam

Focus: problem solving using programming conceptsgiven a problem statement,

correctly analyze its requirements,design a modular general solution, andselect the adequate C++ tools to implement a workableSIMPLE and efficient solution

The final will have the same format as the midterm

30% theoretical questions (no DS, no STL, no multipelinheretance)

70% programming questions on all topics (no DS, no STL,no multiple inheritance)

c© A. Amer COEN244: Introduction 60

Page 61: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

About the final exam

Caution with details:Shape* ptr=D; // D objectno delete of allocated memory (pointers)char ∗ txt; delete[]txt; ⇒ not delettxt;

See online papers of previous final exams for moresample questions

c© A. Amer COEN244: Introduction 61

Page 62: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Sample questions for the final

In class, we will discuss and solve few sample final-exam levelproblems (analysis, design, and implementation)

c© A. Amer COEN244: Introduction 62

Page 63: Aishy Amer - Encsamer/teach/coen244/... · 2008-04-14 · Aishy Amer Electrical & Computer Engineering Lecture Outline: C++/OOP this pointer Operator overloading Polymorphism Templates

Thanks For Your AttentionGOOD LUCK in your exams..

c© A. Amer COEN244: Introduction 63