Date post: | 21-Jan-2016 |
Category: |
Documents |
Upload: | vivien-conley |
View: | 213 times |
Download: | 0 times |
10/18/2011 ecs40 fall 2012 1
ecs40 Fall 2012:
Software Development & Object-Software Development & Object-Oriented ProgrammingOriented Programming#02: Chapters 11~14
Dr. S. Felix Wu
Computer Science Department
University of California, Davishttp://www.cs.ucdavis.edu/~wu/
10/18/2011
Object-OrientedObject-Oriented
setTime
Time
printUniversal
printStandard
intConstructor
ecs40 fall 2012
“Separation of Interface and Implementation”
Time.h Time.c main.c
intint
2
OO Paradigm in C++OO Paradigm in C++
Operator Overloading Inheritance Polymorphism Templates
10/18/2011 ecs40 fall 2012 3
OO Paradigm in C++OO Paradigm in C++
Operator Overloading (chapter 11) Inheritance Polymorphism Templates
10/18/2011 ecs40 fall 2012 4
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
10/18/2011 ecs40 fall 2012 7
strcpy, strcmp, strcat
strtok, strncpy, strncmp, strlen
strdup
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
10/18/2011 ecs40 fall 2012 10
Postfix i++
Prefix ++i
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
Operator OverloadingOperator Overloading
= (assignment operator) + - * (binary arithmetic operators) += -= *= (compound assignment operators) == != (comparison operators)
10/18/2011 ecs40 fall 2012 12
10/18/2011 ecs40 fall 2012 13
Binary – the first operand must be the object
Overloading member Operators!
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
10/18/2011 ecs40 fall 2012 15
A couple questions here…
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
10/18/2011 ecs40 fall 2012 19
We will re-visit in Chapter 15!
10/18/2011 ecs40 fall 2012 20
Rules for Operator Overloading
Readability? “>” versus “strcmp”
How would you find out whether a particular operator has been overloaded?
10/18/2011 ecs40 fall 2012 21
Sometimes it’s useful to determine the size of an array dynamically at execution time and then create the array.
C++ enables you to control the allocation and deallocation of memory in a program for objects and for arrays of any built-in or user-defined type.– Known as dynamic memory management; performed with new and delete.
You can use the new operator to dynamically allocate (i.e., reserve) the exact amount of memory required to hold an object or array at execution time.
The object or array is created in the free store (also called the heap)—a region of memory assigned to each program for storing dynamically allocated objects.
Once memory is allocated in the free store, you can access it via the pointer that operator new returns.
You can return memory to the free store by using the delete operator to deallocate it.
10/18/2011 ecs40 fall 2012 22
The new operator allocates storage of the proper size for an object of type Time, calls the default constructor to initialize the object and returns a pointer to the type specified to the right of the new operator (i.e., a Time *).
If new is unable to find sufficient space in memory for the object, it indicates that an error occurred by “throwing an exception.” – Chapter 16, Exception Handling, discusses how to
deal with new failures.
10/18/2011 ecs40 fall 2012 23
To destroy a dynamically allocated object, use the delete operator as follows:
delete ptr;
This statement first calls the destructor for the object to which ptr points, then deallocates the memory associated with the object, returning the memory to the free store.
10/18/2011 ecs40 fall 2012 24
10/18/2011 ecs40 fall 2012 25
You can provide an initializer for a newly created fundamental-type variable, as in
double *ptr = new double( 3.14159 );
The same syntax can be used to specify a comma-separated list of arguments to the constructor of an object.
10/18/2011 ecs40 fall 2012 26
You can also use the new operator to allocate arrays dynamically.
For example, a 10-element integer array can be allocated and assigned to gradesArray as follows:
int *gradesArray = new int[ 10 ];
A dynamically allocated array’s size can be specified using any non-negative integral expression that can be evaluated at execution time.
Also, when allocating an array of objects dynamically, you cannot pass arguments to each object’s constructor—each object is initialized by its default constructor.
10/18/2011 ecs40 fall 2012 27
To deallocate a dynamically allocated array, use the statement
delete [] ptr;
If the pointer points to an array of objects, the statement first calls the destructor for every object in the array, then deallocates the memory.
Using delete on a null pointer (i.e., a pointer with the value 0) has no effect.
10/18/2011 ecs40 fall 2012 28
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
10/18/2011 ecs40 fall 2012 39
Chapter 12: Inheritance
Parent ChildBase DerivedSuper Sub
10/18/2011 ecs40 fall 2012 40
Chapter 12: Inheritance
Parent ChildBase DerivedSuper Sub
Base
Derived
Inherit
Is-A
10/18/2011 ecs40 fall 2012 41
10/18/2011 ecs40 fall 2012 42
10/18/2011 ecs40 fall 2012 43
10/18/2011 ecs40 fall 2012 44
10/18/2011 ecs40 fall 2012 45
10/18/2011 ecs40 fall 2012 46
10/18/2011 ecs40 fall 2012 47
10/18/2011 ecs40 fall 2012 48
Chapter 12: Inheritance
Parent ChildBase DerivedSuper Sub
CommissionEmployee
BasePlusCommissionEmployee
Inherit
Is-A
10/18/2011 ecs40 fall 2012 49
Chapter 12: Inheritance
Parent ChildBase DerivedSuper Sub
CommissionEmployee
BasePlusCommissionEmployee
Inherit
Is-A
InheritanceInheritancethe Software Engineering perspectivethe Software Engineering perspective
Separating Interface from Implementation
Reusability– Interface, design or implementation
Generalization versus Specialization– Polymorphism (Chapter 13)
10/18/2011 ecs40 fall 2012 50
10/18/2011 ecs40 fall 2012 51
10/18/2011 ecs40 fall 2012 52
Inheritance of Interface or Implementation?
10/18/2011
BaseConstructor
ecs40 fall 2012 53
10/18/2011
BaseConstructor
ecs40 fall 2012 54
DerivedConstructor
10/18/2011
BaseConstructor
ecs40 fall 2012 55
DerivedConstructor
DerivedConstructor
Interface
10/18/2011 ecs40 fall 2012 56
10/18/2011
BaseConstructor
ecs40 fall 2012 57
DerivedConstructor
Inheriting “Partially”Inheriting “Partially”
Inherit an interface but NOT the implementation from the base class
10/18/2011 ecs40 fall 2012 58
10/18/2011
BaseConstructor
ecs40 fall 2012 59
DerivedConstructor
10/18/2011
BaseConstructor
ecs40 fall 2012 60
DerivedConstructor
10/18/2011
BaseConstructor
ecs40 fall 2012 61
DerivedConstructor
“protected”
“private”
“private”
“public”
10/18/2011 ecs40 fall 2012 62
10/18/2011 ecs40 fall 2012 63
Public/Protected/PrivatePublic/Protected/Private
class <Derived> : public <base> {…} class <Derived> : protected <base> {…} class <Derived> : private <base> {…}
10/18/2011 ecs40 fall 2012 64
10/18/2011 ecs40 fall 2012 65
10/18/2011 ecs40 fall 2012 66
Chapter 12: Inheritance
Parent ChildBase DerivedSuper Sub
CommissionEmployee
BasePlusCommissionEmployee
Inherit
Is-A
InheritanceInheritancethe Software Engineering perspectivethe Software Engineering perspective
Separating Interface from Implementation
Reusability– Interface, design or implementation
Generalization versus Specialization– Polymorphism (Chapter 13)
10/18/2011 ecs40 fall 2012 67
09/23/2011 ecs150 Fall 2011 68
VM/MVS, DOS, Win95/98/ME/2000/XP, Freebsd/Linux, MacOS-10, Mach, Minix, PalmOS, uCOS, TinyOS, …
09/23/2011 ecs150 Fall 2011 69
10/07/2011 ecs40 fall 2012 70
Memory Cell Layout
mainScan_addressScanf
malloc/free
a.out
10/07/2011 ecs40 fall 2012 71
malloc/free
a.out
7171
setCourseName
GradeBook
getCourseName
displayMessage
string
Course name
C++
10/07/2011 ecs40 fall 2012 72
7272
setCourseName
GradeBook
getCourseName
displayMessage
string
Course name
Java
10/07/2011 ecs40 fall 2012 73
10/07/2011 ecs40 fall 2012 74
09/23/2011 ecs150 Fall 2011 75
Applications……..
Hardware: CPU/Memory/HD/DVD/Wireless…
OS
….where applications meet Hardware!!!
10/18/2011 ecs40 fall 2012 76
09/23/2011 ecs150 Fall 2011 77
09/23/2011 ecs150 Fall 2011 78
Kernel and User SpaceKernel and User Space
Process FOOFOOMemoryspace for thisprocess
System call(or trap into the kernel)
program
System Call
conceptually
Kernel Resources(disk or IO devices)
Process FOOFOOin the Kernel
09/23/2011 ecs150 Fall 2011 79
FreeBSD Kernel: FreeBSD Kernel: ServicesServices
Timer/clock, descriptor, process Memory Management: paging/swapping I/O control and terminal File System Inter-process communication Networking
10/07/2011 ecs40 fall 2012 80
malloc/free
a.out
8080
setCourseName
GradeBook
getCourseName
displayMessage
string
Course name
C++
81
Define a Class HierarchyDefine a Class Hierarchy
Syntax:
class DerivedClassName : access-level BaseClassName
where
– access-level specifies the type of derivation private by default, or public
Any class can serve as a base class– Thus a derived class can also be a base class
82
classclass TimeTime Specification Specification
class Time{
public :
void Set ( int h, int m, int s ) ;void Increment ( ) ;void Write ( ) const ;Time ( int initH, int initM, int initS ) ; // constructor Time ( ) ; // default constructor
protected :
int hrs ; int mins ; int secs ;
} ;
// SPECIFICATION FILE ( time.h)
Time
MyTime
YourTime
10/18/2011 ecs40 fall 2012 83
84
Class Interface Diagram
Protected data:
hrs
mins
secs
Set
Increment
Write
Time
Time
Time class
85
Derived Class Derived Class ExtTimeExtTime // SPECIFICATION FILE ( exttime.h)
#include “time.h”
enum ZoneType {EST, CST, MST, PST, EDT, CDT, MDT, PDT } ;
class ExtTime : public Time // Time is the base class and use public inheritance
{ public :
void Set ( int h, int m, int s, ZoneType timeZone ) ;void Write ( ) const; //overridden
ExtTime (int initH, int initM, int initS, ZoneType initZone ) ; ExtTime (); // default constructor
private :ZoneType zone ; // added data member
} ;
86
Class Interface Diagram
Protected data:
hrs
mins
secs
ExtTime class
Set
Increment
Write
Time
Time
Set
Increment
Write
ExtTime
ExtTime
Private data:zone
87
Class Interface Diagram
Private data:
hrs
mins
secs
ExtTime class
Set
Increment
Write
Time
Time
Set
Increment
Write
ExtTime
ExtTime
Private data:zone
Inheritance– Class CwD: public Time
Composite Object– Class CwD { … public: Time time; …. }
10/18/2011 ecs40 fall 2012 88
89
Implementation of Implementation of ExtTimeExtTime
Default Constructor
ExtTime :: ExtTime ( ){
zone = EST ;}
The default constructor of base class, Time(), is automatically called, when an ExtTime object is created.
ExtTime et1;
hrs = 0mins = 0secs = 0zone = EST
et1
90
Implementation of Implementation of ExtTimeExtTime
Another Constructor
ExtTime :: ExtTime (int initH, int initM, int initS, ZoneType initZone) : Time (initH, initM, initS) // constructor initializer
{ zone = initZone ;}
ExtTime *et2 =
new ExtTime(8,30,0,EST);hrs = 8mins = 30secs = 0zone = EST
et2
5000
???
6000
5000
91
Implementation of Implementation of ExtTimeExtTime
void ExtTime :: Set (int h, int m, int s, ZoneType timeZone)
{
Time :: Set (hours, minutes, seconds); // same name function call
zone = timeZone ;
}
void ExtTime :: Write ( ) const // function overriding
{
string zoneString[8] =
{“EST”, “CST”, MST”, “PST”, “EDT”, “CDT”, “MDT”, “PDT”} ;
Time :: Write ( ) ;
cout <<‘ ‘<<zoneString[zone]<<endl;
}
92
Working withWorking with ExtTimeExtTime
#include “exttime.h”… …
int main() {
ExtTime thisTime ( 8, 35, 0, PST ) ; ExtTime thatTime ; // default constructor called
thatTime.Write( ) ; // outputs 00:00:00 EST
thatTime.Set (16, 49, 23, CDT) ; thatTime.Write( ) ; // outputs 16:49:23 CDT
thisTime.Increment ( ) ;thisTime.Increment ( ) ;thisTime.Write ( ) ; // outputs 08:35:02 PST
}
Time Time
MyTime ItsTime
YourTime
10/18/2011 ecs40 fall 2012 93
Phone Phone
iPhone5 Android
Ecs40_Phone
10/18/2011 ecs40 fall 2012 94
95
Dynamic Binding in OODynamic Binding in OOPP
Time print()
Classes
MyTime/ItsTimeprint()
YourTimeprint()
inherits (isa)
X x;Y y;Z z;X *px;
px = & ??;// can be x,y,or z
px->print(); // ??
Class Interface Diagram
Protected data:
hrs
mins
secs
ExtTime class
Set
Increment
Write
Time
Time
Set
Increment
Write
ExtTime
ExtTime
Private data:zone
97
Polymorphism – An Polymorphism – An IntroductionIntroduction
Definition– noun, the quality or state of being able to
assume different forms - Webster An essential feature of an OO Language It builds upon Inheritance Allows run-time interpretation of object type
for a given class hierarchy– Also Known as “Late Binding”
Implemented in C++ using virtual functions
98
Dynamic BindingDynamic Binding
Is the run-time determination of which function to call for a particular object of a derived class based on the type of the argument
Declaring a member function to be virtual instructs the compiler to generate code that guarantees dynamic binding
Dynamic binding requires pass-by-reference
99
Virtual Member FunctionVirtual Member Function
// SPECIFICATION FILE ( time.h )
class Time{public :
. . .virtual void Write ( ) ; // for dynamic bindingvirtual ~Time(); // destructor
private :
int hrs ; int mins ; int secs ;
} ;
This is the way we like to see…This is the way we like to see… void Print (Time *
someTime ) {
cout << “Time is “ ;someTime->Write ( ) ;cout << endl ;
}
CLIENT CODE
Time startTime( 8, 30, 0 ) ; ExtTime endTime(10, 45, 0, CST) ;
Time *timeptr;timeptr = &startTime;Print ( timeptr ) ;
timeptr = &endTime;Print ( timeptr ) ;
OUTPUT
Time is 08:30:00 Time is 10:45:00 CST
Time::write()
ExtTime::write()
101
Virtual FunctionsVirtual Functions
Virtual Functions overcome the problem of run time object determination
Keyword virtual instructs the compiler to use late binding and delay the object interpretation
How ?– Define a virtual function in the base class. The word virtual appears
only in the base class– If a base class declares a virtual function, it must implement that
function, even if the body is empty – Virtual function in base class stays virtual in all the derived classes– It can be overridden in the derived classes– But, a derived class is not required to re-implement a virtual
function. If it does not, the base class version is used
10/18/2011 ecs40 fall 2012 102
10/18/2011 ecs40 fall 2012 103
Phone Phone
iPhone5 Android
Ecs40_Phone
10/18/2011 ecs40 fall 2012 104
Phone Phone
iPhone5 Android
Ecs40_Phone
105
Dynamic BindingDynamic Binding
Is the run-time determination of which function to call for a particular object of a derived class based on the type of the argument– At the moment of calling “constructor”!
Declaring a member function to be virtual instructs the compiler to generate code that guarantees dynamic binding
Dynamic binding requires pass-by-reference
What should be the What should be the return value?return value?
int Func_Foo(X, Y)
{
int S = 1;
S = X + Y;
return X+Y;
}
10/18/2011 ecs40 fall 2012 106
What should be the What should be the return value?return value?
int Func_Foo(X, Y)
{
int S = 1;
S = X + Y;
return X+Y;
}
10/18/2011 ecs40 fall 2012 107
int S = 3;printf(“%d\n”, Func_Foo(S+2, S+3);
What should be the What should be the return value?return value?
int Func_Foo(S+2, S+3)
{
int S = 1;
S = (S+2) + (S+3);
return (S+2)+(S+3);
}
10/18/2011 ecs40 fall 2012 108
int S = 3;printf(“%d\n”, Func_Foo(S+2, S+3);
10/18/2011 ecs40 fall 2012 109
Substitute argument for parameter at each occurrence of parameter:
Invocation: P(A, B+2, 27+3)
Definition: procedure P(X,Y,Z)
{int I; I=7; X = I + (7/Y)*Z;}
Meaning: P(X,Y,Z) {int I; I=7; A=I+(7/(B+2))*(27+3);}
Templates (Ch.14)Templates (Ch.14)
Name substitution Type substitutions
– Functions– Classes
10/18/2011 ecs40 fall 2012 110
10/18/2011 ecs40 fall 2012 111
Function templates and class templates enable you to specify, with a single code segment, an entire range of related (overloaded) functions—called function-template specializations—or an entire range of related classes—called class-template specializations.
This technique is called generic programming. Note the distinction between templates and template
specializations: – Function templates and class templates are like stencils out of which
we trace shapes.– Function-template specializations and class-template specializations
are like the separate trac-ings that all have the same shape, but could, for example, be drawn in different colors.
In this chapter, we present a function template and a class tem-plate.
10/18/2011 ecs40 fall 2012 112
All function-template definitions begin with keyword template followed by a list of template parameters to the function template enclosed in angle brackets (< and >); each template parameter that represents a type must be preceded by either of the interchangeable keywords class or typename, as in
template<typename T>– Or
template<class ElementType>– Or
template<typename BorderType, typename FillType> The type template parameters of a function-template definition are used
to specify the types of the arguments to the function, to specify the return type of the function and to declare variables within the function.
Keywords typename and class used to specify function-template parameters actually mean “any fundamental type or user-defined type.”
10/18/2011 ecs40 fall 2012 113
10/18/2011 ecs40 fall 2012 114
10/18/2011 ecs40 fall 2012 115
A critical difference between Virtual Functions and Templates…
10/18/2011 ecs40 fall 2012 116
When the compiler detects a printArray function invocation in the client program (e.g., lines 29 and 34), the compiler uses its overload resolution capabilities to find a definition of function printArray that best matches the function call.
In this case, the only printArray function with the appropriate number of parameters is the printArray function template (lines 7–14).
Consider the function call at line 29. The compiler compares the type of printArray’s first argument (int *
at line 29) to the printArray function template’s first parameter (const T * const at line 8) and deduces that replacing the type parameter T with int would make the argument consistent with the parameter.
Then, the compiler substitutes int for T throughout the template definition and compiles a printArray specialization that can display an array of int values.
10/18/2011 ecs40 fall 2012 117
The function-template specialization for type int is void printArray( const int * const array, int count )
{ for ( int i = 0; i < count; i++ ) cout << array[ i ] << " ";
cout << endl;} // end function printArray
As with function parameters, the names of template parameters must be unique inside a template definition.
Template parameter names need not be unique across different function templates.
Figure 14.1 demonstrates function template printArray. It’s important to note that if T (line 7) represents a user-defined type
(which it does not in Fig. 14.1), there must be an overloaded stream insertion operator for that type; otherwise, the first stream insertion operator in line 11 will not compile.
10/18/2011 ecs40 fall 2012 118
10/18/2011 ecs40 fall 2012 119
Call by NameCall by Name
Substitutions essentially
10/18/2011 ecs40 fall 2012 120
10/18/2011 ecs40 fall 2012 121
10/18/2011 ecs40 fall 2012 122
10/18/2011 ecs40 fall 2012 123
10/18/2011 ecs40 fall 2012 124
10/18/2011 ecs40 fall 2012 125
10/18/2011 ecs40 fall 2012 126
When shall we use Templates?
10/18/2011 ecs40 fall 2012 127
When shall we use Templates?
HW#5?
10/18/2011 ecs40 fall 2012 128
10/18/2011 ecs40 fall 2012 129
10/18/2011 ecs40 fall 2012 130