Top Banner
1 Chapter 14 Object-Oriented Software Development
95
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 1 Chapter 14 Object-Oriented Software Development.

1

Chapter 14

Object-Oriented Software Development

Page 2: 1 Chapter 14 Object-Oriented Software Development.

2

Object-Oriented Design

A technique for developing a program in which the solution is expressed in terms of objects -- self- contained entities composed of data and operations on that data.

Page 3: 1 Chapter 14 Object-Oriented Software Development.

3

Object Oriented Programming

Programmer thinks about and defines the attributes and behavior of objects.

Often the objects are modeled after real-world entities.

Very different approach than function-based programming (like C).

Page 4: 1 Chapter 14 Object-Oriented Software Development.

4

Reasons for OOP

Abstraction

Polymorphism

Inheritance

Encapsulation

Software Engineering Issues

Page 5: 1 Chapter 14 Object-Oriented Software Development.

5

Objects to Classes

• A class defines the pattern used when

instantiating an object of that type.

• A class generally contains private data and

public operations (called methods).

Page 6: 1 Chapter 14 Object-Oriented Software Development.

6

Class: Object Types

A C++ class is an object type.

When you create the definition of a class you are defining the attributes and behavior of a new type.

Attributes are data members. Behavior is defined by methods.

Page 7: 1 Chapter 14 Object-Oriented Software Development.

7

Creating an object

Defining a class does not result in creation of an object.

Declaring a variable of a class type creates an object. You can have many variables of the same type (class).

Instantiation

Page 8: 1 Chapter 14 Object-Oriented Software Development.

8

Superclass and Subclass

• Inheritance enables us to define a new class (called a subclass) that inherits the properties of an already existing class.

• The newly derived class is then specialized by adding properties specific to it.

• The class being inherited from is the superclass.• The class that inherits properties is the subclass.

Page 9: 1 Chapter 14 Object-Oriented Software Development.

9

Defining Objects

• An object-oriented program consists of many objects.

• An object is composed of identity, state (attributes, data, and their current values) and behavior (operations) .

Page 10: 1 Chapter 14 Object-Oriented Software Development.

10

Identity, State, Behavior

• Identity is the property of an object that distinguishes it from all other objects.

• The failure to recognize the difference between the name of the object and the object itself is the source of many errors in object-oriented (OO) programming.

Page 11: 1 Chapter 14 Object-Oriented Software Development.

11

Identity, State, Behavior

• The state of an object encompasses all of the (static) properties of the object plus the current (dynamic) values of each of these properties

• A property is an inherent or distinctive characteristic, trait, quality, or feature that contribute to making an object uniquely that object

• We will use the word attribute, or data member, to refer to the state of an object

Page 12: 1 Chapter 14 Object-Oriented Software Development.

12

Examples of State

• Properties• Elevators travel up or down• Vending machines accept coins• Clocks indicate the current time

• Values• Current floor• Number of coins deposited• The number of minutes since the last

hour

Page 13: 1 Chapter 14 Object-Oriented Software Development.

13

Identity, State, Behavior

• Behavior is how an object acts and reacts, in terms of state changes and interactions with other objects.

• An operation is some action that one object performs upon another in order to elicit a reaction.

• We will use the word method to describe object behavior in C++.

• Invoking a method causes the behavior to take place.

Page 14: 1 Chapter 14 Object-Oriented Software Development.

14

Classes

• Classes are the definitions (or blueprints) used to create objects. I’d say: descriptions of objects.

• To make a car the manufacturer must first have a design from which to build the first car. Then, once all the problems are worked out, the design is used to build all the cars of that model.

Page 15: 1 Chapter 14 Object-Oriented Software Development.

15

Objects

• An object is an instance of a class.

• If we have a class definition called Car, then we can think of Audi, BMW, and Corvette as each being an instance (object) of the class Car, i.e., they are each a type of car.

Page 16: 1 Chapter 14 Object-Oriented Software Development.

16

Object example

Audi 6 BMW Z3 Corvette

• Notice that all objects are of the same type. All objects are cars!

Car Car Car

Page 17: 1 Chapter 14 Object-Oriented Software Development.

17

Classes and Objects

• An object is an instance of exactly one class• Corvette can not be an instance of a car class

and an instance of a plane class at the same time.

• An instance of a class, an object, belongs to that particular class.• A Corvette is a car Corvette belongs to the

class Car.

Page 18: 1 Chapter 14 Object-Oriented Software Development.

18

Classes

• Once a class is defined you can create as many instances of the class (objects from the class) as you would like.

• Once a blue print is completed for the 2004 Porsche 911, Porsche will use an assembly line to build as many instances of the 2004 Porsche 911 as they wish.

Page 19: 1 Chapter 14 Object-Oriented Software Development.

19

Defining a class

• Properties are variables which describe the essential characteristics of an object.• Properties of a car: color, model, make, how many

doors, transmission type, direction of movement, etc.

• Behaviors are methods that describe how the object behaves and how the properties may be modified. • Behavior of a car: braking, changing gears, opening

doors, moving forwards or backwards, etc.

Page 20: 1 Chapter 14 Object-Oriented Software Development.

20

Instance variables

• The class definition will include parameter definitions (properties) that represent data about a particular object, instance variables.

• Example, Joe's car may have 4 gallons of gas in it while John's car has 10 gallons.

• The amount of gas in each car may change without affecting the amount of gas in the any other cars.

• All instances (objects) of a class will have a set of instance variables that are specific to that individual object.

• The combination of the values of these instance variables is known as the object’s state.

Page 21: 1 Chapter 14 Object-Oriented Software Development.

21

Instance variables

Audi 6 BMW Z3 Corvette

Car Car Car

Car

MaxSpeed = 155 MaxSpeed = 165 MaxSpeed = 145

MaxSpeed

Page 22: 1 Chapter 14 Object-Oriented Software Development.

22

Class variables

• The class definitions may also include parameter definitions that represent data that is shared by all class instances (objects), called class variables.

• In the case of the car class, we will define a maximum allowed speed, by the law (variable MaxSpeed). This will be the same for each individual car.

Page 23: 1 Chapter 14 Object-Oriented Software Development.

23

Class variables

Audi 6 BMW Z3 Corvette

Car Car Car

Car

MaxSpeed = 155 MaxSpeed = 165 MaxSpeed = 145

MaxSpeed

MaxSpeed=155

Page 24: 1 Chapter 14 Object-Oriented Software Development.

24

Class variables

• Class variables may also be used to keep track of things such as how many instances of a class exist.

• Example: let’s create a counter the records how many cars are in the garage.

Page 25: 1 Chapter 14 Object-Oriented Software Development.

25

Class variables

Audi 6 BMW Z3 Corvette

Car Car Car

Car

MaxSpeed = 155 MaxSpeed = 165 MaxSpeed = 145

MaxSpeed

MaxSpeed=155

NumCars = 3

Page 26: 1 Chapter 14 Object-Oriented Software Development.

26

Messages

• For Objects• The object to whom

the message is being sent.

• The name of the method that object is to execute.

• Any parameters (variables) needed by that method.

For Humans• Who the message

is for.• What we want the

person to do.• What information

is needed to do it.

Audi 6 • turnOnHazard()

Page 27: 1 Chapter 14 Object-Oriented Software Development.

27

Messages and Methods

• In order to process a message, an object needs to have a method defined for the requested task.

• A method is a small, well-defined piece of code that completes a specific task.

• For our previous example, we need to define a method to turn on the car's hazard lights.

Page 28: 1 Chapter 14 Object-Oriented Software Development.

28

Messages and Methods

Audi 6 BMW Z3 Corvette

Car Car Car

Car

MaxSpeed = 155

turnOnHazard()

MaxSpeed = 165

turnOnHazard()

MaxSpeed = 145

turnOnHazard()

MaxSpeed

MaxSpeed=155

NumCars = 3

turnOnHazard()

Page 29: 1 Chapter 14 Object-Oriented Software Development.

29

Instance methods

• Each class can have methods that are specific to each object, called instance methods.

• These can only affect that object's parameters, i.e., it’s instance variables.

• Example: If BMW has 4 gallons of gas and someone puts 6 more gallons of gas in his/her car, the car now has 10 gallons. The amount of gas in Audi and Corvette is unchanged.

Page 30: 1 Chapter 14 Object-Oriented Software Development.

30

Messages and Methods

Audi 6 BMW Z3 Corvette

Car Car Car

Car

MaxSpeed = 155

turnOnHazard()addGass(amount)

MaxSpeed = 165

turnOnHazard()addGass(amount)

MaxSpeed = 145

turnOnHazard()addGass(amount)

MaxSpeedMaxSpeed=155NumCars = 3turnOnHazard()addGass(amount)

Page 31: 1 Chapter 14 Object-Oriented Software Development.

31

Methods

• It is also possible that you want information from an object; in this case, you would define a method that sends (returns) a message back to the requester containing that information.

• We need to know how much gas is in our cars, so we will create a new method that returns the value of Gas-Level variable for our car.

Page 32: 1 Chapter 14 Object-Oriented Software Development.

32

Messages and Methods

Audi 6 BMW Z3 Corvette

Car Car Car

Car

MaxSpeed = 155GasLevel = 4

turnOnHazard()addGass(amount)getGasLevel():GasLevel

MaxSpeed = 165GasLevel = 10

MaxSpeed = 145GasLevel = 6

turnOnHazard()addGass(amount)getGasLevel():GasLevel

MaxSpeedGasLevelMaxSpeed=155NumCars = 3

addGass(amount) getGasLevel():GasLevel

turnOnHazard()

addGass(amount) getGasLevel():GasLevel

turnOnHazard()

Page 33: 1 Chapter 14 Object-Oriented Software Development.

33

Class methods

• Class methods are used to get or manipulate information about all objects created from the class.

• Typically, class methods are changing class variables. For example:• Each time we move the car in or out of the

garage, we need to add/subtract one to the number of cars: carIn( ) & carOut( )

• Also, we may want to know how many cars are actually in the garage: getNumCars( )

Page 34: 1 Chapter 14 Object-Oriented Software Development.

34

Messages and Methods

Audi 6 BMW Z3 Corvette

Car Car Car

Car

MaxSpeed = 155GasLevel = 4

turnOnHazard()addGass(amount)getGasLevel():GasLevel

MaxSpeed = 165GasLevel = 10

turnOnHazard()addGass(amount)getGasLevel():GasLevel

MaxSpeed = 145GasLevel = 6

turnOnHazard()addGass(amount)getGasLevel():GasLevel

MaxSpeedGasLevelMaxSpeed=155NumCars = 3

addGass(amount) getGasLevel():GasLevel

turnOnHazard()

carIn()

carOut()

getNumCars():NumCars

Page 35: 1 Chapter 14 Object-Oriented Software Development.

35

Object Oriented Programming

• When writing object-oriented programs, first one must define the classes (like Car).

• Then, while the program is running, the instances of the classes (objects) (such as Audi, BMW, Corvette in our example) are created.

Page 36: 1 Chapter 14 Object-Oriented Software Development.

36

Object Oriented Programming - Benefits

• An object can be written and maintained separately from the rest of the program, modularity.

• An object has a “public face” that it uses to communicate with other objects, but other objects can not directly access its instance variables, information hiding.

Page 37: 1 Chapter 14 Object-Oriented Software Development.

37

Information Hiding

The interface to a class is the list of public data members and methods.

The interface defines the behavior of the class to the outside world (to other classes and functions that may access variables of your class type).

The implementation of your class doesn't matter outside the class – only the interface.

Page 38: 1 Chapter 14 Object-Oriented Software Development.

38

Information Hiding (cont.)

You can change the implementation and nobody cares! (as long as the interface is the same).

You can use other peoples classes without fear!

Page 39: 1 Chapter 14 Object-Oriented Software Development.

39

Polymorphism

The ability of different objects to respond to the same message in different ways.

Tell an int to print itself: cout << i; Now tell a double: cout << x;

Now tell the Poly: cout << poly;

Page 40: 1 Chapter 14 Object-Oriented Software Development.

40

Inheritance

You can create a new class that inherits from an existing class.

You can add new members and methods. You can replace methods. The new class is a specialization of the

existing class.

Page 41: 1 Chapter 14 Object-Oriented Software Development.

41

Inheritance

• All classes in C++ are organized into a class hierarchy.

• The highest level classes are very general and the lower level classes are more specific.

• The lower level classes are based upon the higher level classes and inherit instance variables and methods from those higher level class. They also may contain their own (new) instance variables and methods beyond the higher level class definition.

Page 42: 1 Chapter 14 Object-Oriented Software Development.

42

Inheritance

• A higher level class is called a superclass; a lower level class is called a subclass.

• A subclass may also be a superclass

• Inheritance allows you to define certain behaviors once and then to reuse those behaviors over and over again in the subclasses. This is called reusability.

Page 43: 1 Chapter 14 Object-Oriented Software Development.

43

Inheritance Example

Base class is shape, represents the abstract notion of a shape.

Derived classes: rectangle circle triangle.

An object that is a circle is also a shape!

Page 44: 1 Chapter 14 Object-Oriented Software Development.

44

Inheritance Example

• Our Car class is very general.

• Let's define a new class called BMW that contains the parameters: model, color, engine size.

Page 45: 1 Chapter 14 Object-Oriented Software Development.

45

Inheritance

CarMaxSpeedGasLevelMaxSpeed=155

turnOnHazard()addGass(amount)getGasLevel():GasLevel

BMWModelColorEngineSize

MaxSpeedGasLevel

turnOnHazard()addGass(amount)getGasLevel():GasLevel

Page 46: 1 Chapter 14 Object-Oriented Software Development.

46

Inheritance

• Now let's define two new classes. One for the Z3 and another for the 3 Series Sedan.

• What might be some of the differences between the two classes?

• Number of doors (3, 5)• Roof (soft or hardtop)• Therefore, we add variables NumDoors

and Roof

Page 47: 1 Chapter 14 Object-Oriented Software Development.

47

Inheritance

CarMaxSpeedGasLevelMaxSpeed=155

turnOnHazard()addGass(amount)getGasLevel():GasLevel

BMWModelColorEngineSize

MaxSpeedGasLevel

turnOnHazard()addGass(amount)getGasLevel():GasLevel

Z3ModelColorEngineSizeRoof

MaxSpeedGasLevel

turnOnHazard()addGass(amount)getGasLevel():GasLevel

3 seriesModelColorEngineSizeNumDoors

MaxSpeedGasLevel

turnOnHazard()addGass(amount)getGasLevel():GasLevel

Page 48: 1 Chapter 14 Object-Oriented Software Development.

48

Views of the class

• A class can be viewed as a sort of contract that specifies what instances of the class can, and cannot do

• It is possible to distinguish between the outside and inside view of a class

• The interface of a class provides its outside view and emphasizes the abstraction

• The implementation of a class is its inside view

Page 49: 1 Chapter 14 Object-Oriented Software Development.

49

Access

• Most classes provide three levels of access to their members (state and behavior):• Public

• The part of the class that is visible to all clients of the class

• Protected• The part of the class that is only visible to

subclasses of the class

• Private• A part of the class that is not visible to any other

classes

Page 50: 1 Chapter 14 Object-Oriented Software Development.

50

Private vs. Public

Public data members and methods can be accessed outside the class directly.

The public stuff is the interface.

Private members and methods are for internal use only.

Page 51: 1 Chapter 14 Object-Oriented Software Development.

51

Protected Class members/methods

We've already seen private and public.

Protected means derived classes have access to data members and methods, but otherwise the members/methods are private.

Page 52: 1 Chapter 14 Object-Oriented Software Development.

52

Special Member Functions

Constructors: called when a new object is created (instantiated). can be many constructors, each can take

different arguments.

Destructor: called when an object is eliminated only one, has no arguments.

Page 53: 1 Chapter 14 Object-Oriented Software Development.

53

Accessing Data Members

Data members are available within each method (as if they were local variables).

Public data members can be accessed by other functions using the member access operator "." (just like struct).

Page 54: 1 Chapter 14 Object-Oriented Software Development.

54

Accessing class methods

Within other class methods, a method can be called just like a function.

Outside the class, public methods can be called only when referencing an object of the class.

Page 55: 1 Chapter 14 Object-Oriented Software Development.

55

What happens here?class foo {

int i; // # elements in the array

int a[10]; // array 10 at most

// sum the elements

int sum(void) {

int i, x=0;

for (i=0;i<i;i++)

x+=a[i];

return(x);

}

...

which i is it ?

Page 56: 1 Chapter 14 Object-Oriented Software Development.

56

Class Scope Operator ::

You can solve the previous problem using the "::" operator classname::membername.

for (i=0;i<foo::i;i++)

x+=a[i];

Page 57: 1 Chapter 14 Object-Oriented Software Development.

57

Method names and ::

Sometimes we put just a prototype for a member function within the class definition.

The actual definition of the method is outside the class.

You have to use :: to do this.

Page 58: 1 Chapter 14 Object-Oriented Software Development.

58

Example

class foo { ...int sum(void);

};

int foo::sum(void) {int sum=0;

for (int i=0;i<foo::i;i++) {sum += a[i];

} return(sum);}

Page 59: 1 Chapter 14 Object-Oriented Software Development.

59

Classes and Files The relationship between C++ class

definitions and files depends on the compiler.

In general you can put class definitions anywhere! Visual C++ wants one class per file.

Most people do this: class definition is in classname.h any methods defined outside of the class

definition are in classname.cpp

Page 60: 1 Chapter 14 Object-Oriented Software Development.

60

static methods

A static method is a class method that can be called without having an object.

Must use the :: operator to identify the method.

Method can't access non-static data members! (they don't exist unless we have an object).

Page 61: 1 Chapter 14 Object-Oriented Software Development.

61

Static Data Members

It is possible to have a single variable that is shared by all instances of a class (all the objects). declare the variable as static.

Data members that are static must be declared and initialize outside of the class. at global or file scope.

Page 62: 1 Chapter 14 Object-Oriented Software Development.

62

Static data member example

class foo {private:static int cnt;

public: foo() {

foocount++;cout << "there are now " <<

cnt << " foo objects << endl;

}...

Page 63: 1 Chapter 14 Object-Oriented Software Development.

63

Friends

A Class can declare other classes as "friend classes".

A Class can declare external functions as "friends".

friends can access private members and methods.

Page 64: 1 Chapter 14 Object-Oriented Software Development.

64

Friend Declaration

class foo {

private:

int i,j;

friend class fee;

friend int printfoo( foo &f1);

};

Page 65: 1 Chapter 14 Object-Oriented Software Development.

65

Two Programming Paradigms

Structural (Procedural) Object-Oriented PROGRAM PROGRAM

FUNCTION

FUNCTION

FUNCTION

OBJECT

Operations

Data

OBJECT

Operations

Data

OBJECT

Operations

Data

Page 66: 1 Chapter 14 Object-Oriented Software Development.

66

Object-Oriented Programming Language Features

1. Data abstraction

2. Inheritance of properties

3. Dynamic binding of operations to objects

Page 67: 1 Chapter 14 Object-Oriented Software Development.

67

OOP Terms C++ Equivalents

Object Class object or class instance

Instance variable Private data member

Method Public member function

Message passing Function call ( to a public member function )

Page 68: 1 Chapter 14 Object-Oriented Software Development.

68

What is an object?

OBJECT

Operations

Data

set of methods(public member functions)

internal state(values of private data members)

Page 69: 1 Chapter 14 Object-Oriented Software Development.

69

Inheritance Hierarchy Among Vehicles

vehicle

wheeled vehicle boat

bicyclecar

four-door two-door

Every car is a wheeled vehicle.

Page 70: 1 Chapter 14 Object-Oriented Software Development.

70

Inheritance

is a mechanism by which one class acquires (inherits) the properties (both data and operations) of another class

the class being inherited from is the Base Class (Superclass)

the class that inherits is the Derived Class (Subclass)

the derived class is then specialized by adding properties specific to it

Page 71: 1 Chapter 14 Object-Oriented Software Development.

71

class Time Specification

// SPECIFICATION FILE ( time.h )

class Time{

public :

void Set ( int hours , int minutes , int seconds ) ;void Increment ( ) ;void Write ( ) const ;Time ( int initHrs, int initMins, int initSecs ) ; // constructor Time ( ) ; // default constructor

private :

int hrs ; int mins ; int secs ;

} ;71

Page 72: 1 Chapter 14 Object-Oriented Software Development.

72

Class Interface Diagram

Private data:

hrs

mins

secs

Set

Increment

Write

Time

Time

Time class

Page 73: 1 Chapter 14 Object-Oriented Software Development.

73

Using Inheritance to Add Features

// 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{public :

void Set ( int hours, int minutes, int seconds , ZoneType timeZone ) ;

void Write ( ) const ; ExtTime ( int initHrs , int initMins , int initSecs ,

ZoneType initZone ) ; // constructor ExtTime ( ) ; // default constructor

private :ZoneType zone ; // added data member

} ;73

Page 74: 1 Chapter 14 Object-Oriented Software Development.

74

class ExtTime: public Time

says class Time is a public base class of the derived class ExtTime

as a result, all public members of Time (except constructors) are also public members of ExtTime

in this example, new constructors are provided, new data member zone is added, and member functions Set and Write are overridden

Page 75: 1 Chapter 14 Object-Oriented Software Development.

75

Class Interface Diagram

Private data:

hrs

mins

secs

ExtTime class

Set

Increment

Write

Time

Time

Set

Increment

Write

ExtTime

ExtTime

Private data:zone

Page 76: 1 Chapter 14 Object-Oriented Software Development.

76

Client Code Using ExtTime

#include “exttime.h” . . .

ExtTime thisTime ( 8, 35, 0, PST ) ; ExtTime thatTime ; // default constructor called

thatTime.Write( ) ; // outputs 00:00:00 EST cout << endl ;

thatTime.Set (16, 49, 23, CDT) ; thatTime.Write( ) ; // outputs 16:49:23 CDT

cout << endl ;

thisTime.Increment ( ) ; thisTime.Increment ( ) ; thisTime.Write ( ) ; // outputs 08:35:02 PST cout << endl ; 76

Page 77: 1 Chapter 14 Object-Oriented Software Development.

77

Constructor Rules for Derived Classes

at run time, the base class constructor is implicitly called first, before the body of the derived class’s constructor executes

if the base class constructor requires parameters, they must be passed by the derived class’s constructor

Page 78: 1 Chapter 14 Object-Oriented Software Development.

78

Implementation of ExtTime Default Constructor

ExtTime :: ExtTime ( )

// Default Constructor

// Postcondition:

// hrs == 0 && mins == 0 && secs == 0

// (via an implicit call to base class default constructor )

// && zone == EST

{

zone = EST ;

}

Page 79: 1 Chapter 14 Object-Oriented Software Development.

79

Implementation of Another ExtTime Class Constructor

ExtTime :: ExtTime ( /* in */ int initHrs, /* in */ int initMins, /* in */ int initSecs,

/* in */ ZoneType initZone )

: Time (initHrs, initMins, initSecs) // constructor initializer

// Precondition: 0 <= initHrs <= 23 && 0 <= initMins <= 59// 0 <= initSecs <= 59 && initZone is assigned// Postcondition:// zone == initZone && Time set by base class constructor{ zone = initZone ;}

79

Page 80: 1 Chapter 14 Object-Oriented Software Development.

80

Implementation of ExtTime::Set function

void ExtTime :: Set ( /* in */ int hours,

/* in */ int minutes,

/* in */ int seconds,

/* in */ ZoneType time Zone )

// Precondition: 0 <= hours <= 23 && 0 <= minutes <= 59

// 0 <= seconds <= 59 && timeZone is assigned

// Postcondition:

// zone == timeZone && Time set by base class function

{

Time :: Set (hours, minutes, seconds);

zone = timeZone ;

}80

Page 81: 1 Chapter 14 Object-Oriented Software Development.

81

Implementation of ExtTime::Write Function

void ExtTime :: Write ( ) const

// Postcondition:// Time has been output in form HH:MM:SS ZZZ// where ZZZ is the time zone abbreviation{ static string zoneString[8] = { “EST”, CST”, MST”, “PST”, “EDT”, “CDT”, “MDT”, “PDT” } ; Time :: Write ( ) ; cout << ‘ ‘ << zoneString [zone] ;}

81

Page 82: 1 Chapter 14 Object-Oriented Software Development.

82

Composition (or Containment)

is a mechanism by which the internal data (the state) of one class includes an object of another class

Page 83: 1 Chapter 14 Object-Oriented Software Development.

83

A TimeCard object has a Time object

#include “time.h”

class TimeCard { public: void Punch ( /* in */ int hours,

/* in */ int minutes, /* in */ int seconds ) ; void Print ( ) const ; TimeCard ( /* in */ long idNum,

/* in */ int initHrs, /* in */ int initMins,

/* in */ int initSecs ) ; TimeCard ( ) ; private: long id ; Time timeStamp ; } ;

Page 84: 1 Chapter 14 Object-Oriented Software Development.

84

TimeCard ClassTimeCard has a Time object

Private data:

hrs

mins

secs

Punch

Private data:

id

timeStamp

Increment

SetPrint . . .

TimeCard

TimeCard

Write . . .

Page 85: 1 Chapter 14 Object-Oriented Software Development.

85

Implementation of TimeCard Class Constructor

TimeCard :: TimeCard ( /* in */ long idNum, /* in */ int initHrs, /* in */ int initMins,

/* in */ int initSecs )

: timeStamp (initHrs, initMins, initSecs) // constructor initializer

// Precondition: 0 <= initHrs <= 23 && 0 <= initMins <= 59// 0 <= initSecs <= 59 && initNum is assigned// Postcondition:// id == idNum && timeStamp set by its constructor{ id = idNum ;}

85

Page 86: 1 Chapter 14 Object-Oriented Software Development.

86

Order in Which Constructors are Executed

Given a class X,

if X is a derived class its base class constructor is executed first

next, constructors for member objects (if any) are executed (using their own default constructors if none is specified)

finally, the body of X’s constructor is executed

Page 87: 1 Chapter 14 Object-Oriented Software Development.

87

In C++ . . .

When the type of a formal parameter is a

parent class, the argument used can be:

the same type as the formal parameter,

or,

any descendant class type.

Page 88: 1 Chapter 14 Object-Oriented Software Development.

88

Static Binding

is the compile-time determination of which function to call for a particular object based on the type of the formal parameter

when pass-by-value is used, static binding occurs

Page 89: 1 Chapter 14 Object-Oriented Software Development.

89

Static Binding Is Based on Formal Parameter Type

void Print ( /* in */ Time someTime ){

cout << “Time is “ ;someTime.Write ( ) ;cout << endl ;

}

CLIENT CODE OUTPUT

Time startTime ( 8, 30, 0 ) ; Time is 08:30:00ExtTime endTime (10, 45, 0, CST) ; Time is 10:45:00

Print ( startTime ) ;Print ( endTime ) ;

Page 90: 1 Chapter 14 Object-Oriented Software Development.

90

Virtual Functions

A virtual function is a method in a base class that can be overridden by a derived class method.

In the time example, we would like each time object to "know" which write() method to use.

Declare the base class write method virtual, and this happens!

Page 91: 1 Chapter 14 Object-Oriented Software Development.

91

Dynamic Binding

is the run-time determination of which function to call for a particular object of a descendant 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

Page 92: 1 Chapter 14 Object-Oriented Software Development.

92

Virtual Member Function

// SPECIFICATION FILE ( time.h )

class TimeType{

public :

. . .

virtual void Write ( ) const ; // for dynamic binding

. . .

private :

int hrs ; int mins ; int secs ;

} ;

Page 93: 1 Chapter 14 Object-Oriented Software Development.

93

Dynamic binding requires pass-by-reference

void Print ( /* in */ Time & someTime ){

cout << “Time is “ ;someTime.Write ( ) ;cout << endl ;

}

CLIENT CODE OUTPUT

Time startTime ( 8, 30, 0 ) ; Time is 08:30:00ExtTime endTime (10, 45, 0, CST) ; Time is 10:45:00 CST

Print ( startTime ) ;Print ( endTime ) ;

Page 94: 1 Chapter 14 Object-Oriented Software Development.

94

Using virtual functions in C++

dynamic binding requires pass-by-reference when passing a class object to a function

in the declaration for a virtual function, 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

a derived class is not required to re-implement a virtual function. If it does not, the base class version is used

Page 95: 1 Chapter 14 Object-Oriented Software Development.

95

End of Lecture