Object Oriented Programming With C++ [Fourth Edition]
 0070669074, 9780070669079

Citation preview

FOURTH EDITION

OBJECT

PROGRAMMING WITH

E BALACURUSAMY

2

Now a

unique opportunity to access the

Look

lor ih&

Genuineness CenilKale

Web

Resources!

inside the

book

Scralch the srker ink an the Genuineness Certificate 1d find your Unique

A&caa* Number'

I Access

ttie

website

I CiCk on

Ilia

Flrsi

Time U«ra

Link

in

the

OLC menu

on your laH

I A[ the

bongm el

the- (ert

appearing on your right-hand side, took and click an itia Student hnk

for

Register

How

I buynv click art the link thai says:

When asked

to

I

have a registration code that came wFth

Shier yOur

«de,

1ype

in

my

book.

ywr Unique A0c*4g Number

r Create your Personalized Account by selecting your usernama and password

Click

gn

the-

Student Edition Link

Login u&no, your personaltzed

*

This number

is

meant

lor

one

fimfl

use and

is $elt

m

|he

QLC menu

on your

left

usemame and password

faslrvctibie

Copyrighted material

|R&V>

OBJECT

KA' mhemtei E5& PROGRAMMING £3fl fj&Z

WITH

^flj

Thla On*

c6KZ-DGX-5tOK ltcC material j

About the Author E Balagurusamy, former Vice Chancellor, Anna University, Cbennai, is currently Member, Union Public Service Commission, New Delhi. He is a teacher trainer, and consultant in f

the fields of Information Techno kqiy wirt M: m jgenient. He holds an ME (Hans) in Electrical Engineering and a Ph. D. in Systems Engineering from the Indian Institute of Technology, Roorkee, His areas of interest include Object-Oriented Software Engineering, Electronic Business, Technology Management, Business Process Re-engineering and Total Quality .

Management.

A

he has authored a large number of research papers and several books. His best selling books among others include: prolific writer,

,

* * » * * * A

Programming in C#, 2fs Programming in Java, 3fe Programming in ANSI C, 4/e Programming in BASlC 3/e Numerical Metbodn, and h

Itnlijahility

Engineering

numerous honours and awards, he has been lifted in the Directory of Who's Who of Intellectuals and in the Directory uf Distinguished Leaders in Education. recipient of

Copyrighted material



OBJECT ORIENTED

PROGRAMMING WITH

FOURTH EDITION £ Bala guru samy Member Union Public Service Commission

New

Delhi

Tata McGraw-Hill Publishing Company Limited NEW DELHI Mt Gmw-Hllt Offices

New

Delhi

New

York

Kuala Lumpur San Juan

Lisbon

5t Louis

London

Santiago

Sucj Jtudclscci

Madrid

Singapore

Auckland

Mexico City Sydney Tokyo

Bogota Milan

Caracas

Montreal

Toronto

Copyrighted material

35 Tata McGraw-Hill r

i

Published by Taia McGraw-Hill Publishing

New

7 West Patel Nagar,

Copyright

So

© 2008,

Company

Limited,

Delhi KOtlflR

2006, 200

pari of this publication

1994, by Tutu McGraw-Hill Publishing

H

may

he reproduced or distributed

mechanical, photocopying, recording, or otherwise or stored written permission of the publishers.

computer system, but they may

rial

The program

in a

listings (if

in

Lin

^

Company Limited form or by any means, electronic,

database or retrieval system without the prim

any)

may

be entered, stored and executed

in a

be reproduced for publication.

Fourth reprint 200g

DQLt KEiRMt A/VB This edition can be exported from India only by the publisher*, Tita McGraw-Htll Publishing

ISBN

1.

13 digits!:

Company

Limited.

97B-0-07-066907-9

ISBN (10

digits):

Managing

Director: Ajay Shukla

Q-Q7-0M907-4

Clcnerat Manager;

Publishing—SEM

ATech

Ed: VSbha Maftq/an

Sponsoring Rditor: SbrtiiM Jfta Spnnumriji

Jr.

Senior

Copy

F.dilor: fv'danjan Chiskrii\urt\

Kditor: Dipika

Senior Produciion Manager:

Dey P L Pundim

General Manager: Marketing— Higher Education I

'r

;

n ulT. I

Manager;

Controller

SEM &

£ School: Mithatl

Craq

Tech Ed; Riju Gctncsan

—Ptoduirtion: Rajender f Gftamelu — Production: B Dagra

Asst General Manager

I.

Information contained in [his work has been obtained reliable,

/.

However, neither Tata McOraw-Hill nor

its

t>y

Tata McGraw-Hill, from sources believed lo be

authors guarantee the accuracy or completeness of any

information published herein, and neither Tata McGraw-Hill nor

its

authors shall be responsible for any

em>ji. omissions, or damages arising out of use of this information. This work

understanding that Tata McGraw-Hill and

its.

is

published with the

authors, are supplying Jnformatioit but ore not attempting to

render engineering or other professional services, if such services are required, the assistance of an appropriate professional should be sought.

IjpoL-i

jI

Sen pi Makers

Gopsonv A-2

&. i.

M>.

A

I

l«.

Sector 64, bfoida

I.JJ.JA -

Mum-

I.

Kim. him Vi| wr

.

Neu Ik

i

i

I

in

ft?..

,ind

prnied

iti

201 301

Cover: Gopson*

Tht McGrawHffl Companies

Copyrighted materia

Contents Preface

1,

Principles of Object-Oriented

Li

Programming

\.'2

Software Crisis I Software Evolution

L3

A Look at PfriHjedurft-Qrienteii

1.4

Object Oriented Programming Paradigm fi Basic Concf?pta of Ohjflct-Orientfld Pro-am iliiirLi;;

1.5

3 Proprammiflff

4

RmftfibnfnOP

L7 1A

1 2.

Objoct-Oriciitcd

Languages

13

Applicationgof OOF 14 Summary 15 Rtuit'ii Questions 17

Beginning with C + +

19

2_L 2.2

Applications of C++

2.3

A Simplb- Q+

2L4 2.5 2.6 2.7 2.8

20

Program

gfl

Mora T-H- StatementH a5 An Example with Class 28 Stfuctmx L?f'C-t l j'uflTji[]j 29 Creatine! the? Source FUe. Mi Compiling gnd Linking JO ]

1

Debugging Exercises 33 Prfiffm mmi ng Exercises 34

^3^^jkt|ns^^p^es5^jns and Control Smictures^ Introduction

12 3.3

3,5 3.6 3.7

35.

Tokens 3iZ K^yworda 36 IdentifierH and Honatant.q Basic Data Types 38 User- Dimmed. Data Typufi Derived Data Types ¥2

_4fi

40

35

vi

#

Contents

3.8

Symbolic Constants

43

3.9

Typt* Compatibility

{5

3JJJ

Declaratinn

3.11

D>raamic Initialization of Variableg

t?

ft

3.13 3.14

3.15 3.16 3.17 \i. I

H

3.2(J

3.21

3.22 3.23 3Jil

Ri'Tr-n-rii-i-

cif

Variables

Viirmhli-ri

4A

=12

Operators in C++ 4fl Hcu pL* Kl-suJu Li in] Operator 50 Member Derefereiidtijj Operators 52 Memory Management Operators 52 Manipulators 55 'I'y i h-

f

"

;

u

j

L

O] >i- r: iltir

>

7

Expressions and their Types 5# S pec] a] A>s it Kx -ss uh s Implicit Conversions fiJ Operator Overloading 63 Operator Precedence 63 Crmtrnl Structure

m

1

\>.i l

i

1

1

i

Review Quvalion x 71 Debugging Exercises

Programming

i

75

77

4.1

IriLradnCLuMt

4Ji

The Main Function

ZZ

4,5

2£ Function Prototyping ?9 Call by Reference £J Return by Reference 82



Inline Furii'tiims

4.

Default

44

4.8 4.9 4.1 0

4,11

82.

Arguments 84 const Arguments 87 Function Overloading 87 Friend and Virtiia] Function:* Math Library Fmi[:lL[)itH BO Summary 90 Review Questions} 92 Debugging Exercises 93

Programming

5*

67/

?'A

Exercises

Functions in C + +

4,3

46

fCxerrjaeif

95

C lasses and Objects £2

H Structure

5,3

Specifying a Class

SR.

9glG}

Dynamic Binding Binding refers to the linking of a procedure call to the code to be executed in response to the call, Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance, A function call associated with a polymorphic reference depends on the dynamic type of that reference. Consider the procedure '"draw" in Fig. 1.9. By inheritance, every object will have this procedure. ItH algorithm is, however, unique to each object and so the draw procedure will be redefined in each class that defines the object. At run-time, the code matching the object under current reference will be called.

Message Passing An

object-oriented program consists of a set of objects that

communicate with each

other.

The proceed of programming in an object-oriented language, therefore, involves the following run sic

steps:

2.

Creating dashes that define objects and their behaviour, Creating objects from class definitions,, and

3.

Establishing communication

1.

among

objects.

Objects communicate with one another by sending end receiving information much the same way as people pass messages to one another. The concept of message passing makes it easier to talk about building systems that directly model or simulate their real-world counterparts-

Copyrighted material

12 #-

A

Object-Oriented Programming with

O-

a request for execution of a procedure,, and therefore will invoke a function (procedure) in the receiving object that generates the desired result. Message passing involves specifying the name of the object, the name of the function (message) arid the information no be sent. Example:

message

for

an object

is

am ploygo. salary

^namej:

infonnalion

object

Objects have a life cycle, They can be created and destroyed. Communication with an object is feasible as long as it is alive.

1.6

Benefits of

I

OOP offers

OOP

program designer and the "user. Object-orientation contributes to the solution of many problems associated with the development and quality of software products. The new technology promises greater programmer productivity, better quality of software and lesser maintenance cost. The principal advantages are: several benefits to both the

# Through inheritance, we can

eliminate redundant code

and extend the use of exist-

ing classes.

• We can build • •

programs from the standard working modules that communicate with one another, rather than having to start writing the code from scratch. This leads to aaving of development time and higher productivity. The principle of data hiding helps the programmer to build secure programs that cannot be invaded by code in other parts of the program, It is possible to have multiple instances of an object to m-exisi without, any interference.

* # *

*



Tt is possible to

map

objects, in

the problem domain to those in the program.

easy to partition the work in a project based on objects. Jala-centered design approach enables us to capture more details of a model in The It is

impiementable form. Object-oriented systems can be easily upgraded from small to large systems. Message passing techniques for communication between objects makes, the interface descriptions with external systems much simpler. Software complexity can be easily managed.

While it is possible to incorporate all the.He features in an object-oriented system, their importance depends on the type of the project and the prflferen-rp of the- programmer. There are a number of issues that need to be tackled to reap some of the benefits stated above. For

C opy rig hted m ateri al

m

PrincysJes of Object - On ented Progr&MfnirtQ

13

Tbe technology in still developing and current products maybe superseded quickly. Strict controls and protocols need to be developed instance, object libraries

if reuse is

must be available

for reuse,

not to be compromised.

easy to use makes it hard to build. object-oriented programming tools would help manage* this problem.

Developing a software tbat

1

1.7

is

It ia

hoped that the

Object-Oriented Languages

not the right of Any particular language. Like structured programming, OOP concepts can be implemented using languages such as C and Pascal. However,, programming becomes clumsy and may generate confusion when the programs grow large. A language that m specially designed to support the OOP concepts makes it Object-oriented

programming

is

easier to implement them.

The languages should support several of the OOP concepts to claim that they are objectoriented. Depending upon the features they support, they can be classified into the following two categories: 1.

2.

Object-based programming languages, and Object-oriented programming languages.

Ohjfwt-hnfted

programming

in

the

style-

of

programming that primarily supports

encapsulation and object identity. Major features that are required for object-baaed

programming

* *

* *

ape-

Data encapsulation Data hiding and sccrhs mechanisms Automatic initialization and clear-up of objects Operator overloading

Languages that support programming with objects are said fcc be object-based programming languages. They do not support inheritance and dynamic binding. Ada is a typical objectbased programming language. Object-oriented programming incorporates all of object-based programming features along with two additional features, namely, inheritance and dynamic binding. Object-oriented

programming can therefore be characterized by the following statement Object-ba&ed features + Inheritance + dynamic binding

Languages that

Th«™ Table

support, these features include

C++> Smalltalk, Object Pascal and Java,

number of object-based and object-oriented programming languagHR. some popular general purpose OOP languages and their characteristics-

are a large 1.1 lists

Copy righted

material

14 •

Characteristics of some

Table 1,1

C++

Smalltulk

C'hartirtrrihtim 9.

*

Birth

Late

/

f

'

BiodLdg (early or late!

Polymorphism [la Lb.

Programming with

Object Oriented

hiding

•-•

.-iDfLl

C

"".

Both

Both

Early

Object

Eiffel

Fcueul

*

1

..I.

Early

Rnrly

Bnth

/

*

V

•i

v

S

ConcnTTTurv

OOP fonrjuugtui

V

s

l'..i:.r

No

Pciac"

Mb

Promised.

-

J

i : ..;

'i

!

.unic

v

„.

..

No

*

No

t

V

No

No

In tit) fit;* tint;

Garbage



*

Collect km

Same

hi,.

No

\,

Persist* new

No Object

Nu

N

No



No

No

No

Np

Support

Nd

Ncrt

..-

Litn-fLfLte

SGL

much *

Pure

object-oriented languages

** Object- boxed tan/ruaees

Others are extended conventional language*

As seen from Table

1. 1

,

all lanfiuap*cs

provide for polymorphism and data hiding. However,

many of them do not provide facilities for concurrency, persistence and Ada and C++ provide generic facility which is an important ei instruct for

genericrty, Eiffel,

supporting reuse. However, persistence (a process of storing objects is not fully supported by eny uf them. In Smalltalk, though the entire current execution state con "be saved to disk, yet the individual objects cannot be saved to an external file. )

Commercially, C+-+- is only 10 years uld, Smalltalk and Objective C 13 years old. and Java only 5 years old. Although Simula has existed lor mors than tv- u

assembly language

>

C++

>

classes

>

concurrency

> >

data abstraction

>

data hiding

> >

data members

>

early binding

>

Eiffel

hottom-up programming

data encapsulation

dynamic binding

> > > > > > > > > > > > >

flowcharts function overloading

functions jjurbagp LyJIettign glcmal data

hierarchical classification

inheritance

Java late binding krcal

data

machine language

member

functions

message passing

(Contd)

Copyrighted material

Principles of Object-Oriented

• 17

Programming

rm* Hilda

>

iifKTr

>

modular programming

>

iKTiiistence

>

r>)uitiplf^ iilklLTi LSiijCi:

>

IKjlymorphiam

>

object libraries

>

procedure-oriented programming

Object Pascal

> > >

object'based

>

object-oriented

Objective

overloading

reusability

> >

programming

C

Simula Smalltalk

object-oriented languages

structured

programming

objects

programming

>

tup-down programming

>

Turbo Pascal

Review Questions 1.1

What do you think

1.2

Briefly discusa the software evolution

1.3

What

1.4

Discuss an approach

1.5

Describe

how data

What

object-oriented

1.6

is

is

oriented

are the major issues facing the software industry today!

during the period 1960 — 1990-

procedure-oriented programming? What are to

are.

shared by functumx

in

programming? How

1.8

What are

1.9

Distinguish between the following terms:

a procedure -oriented program. is it different

ore data the

and functions organized

from the procedure-

program? unioue advantages of an object-oriented programming paradigm?

and

in

an

(a)

Objects

(a)

Data abstraction and data encapsulation

object-oriented

classes

and polymorphism fd) Dynamic binding and message passing 1.10 Whul kinds of things can become objects in OOP? 1.11 Describe inheritance- as applied to OOP, 1. 12 What do you mean by dynamic binding? How in it

How

characteristics?

programming?

How

1.13

main

the development of procedure-oriented programs,

1.7

(c>

its

Inheritance

useful in

OOP?

does object-oriented approach differ from object-based approach f

OOP technology. statement* are TRUE or FALSE.

1.14 List a few areas of application of

1.15 State whether the following (a.

In procedure-oriented programming, all data are shared by all functions.

(bl

The main emphasis of procedure-oriented programming

i

is

on algorithms

rather than on data.

C opy rig hted m ateri al

Object -Oriented Pyogmmtruf\ef uath 0>

(c)

One of th e striking features of object -oriented pmgra fuming programs

(d)

is

the

d i v r« inn

of

knawn

an

into objects that represent real-world entities.

Wrapping up of data of

different types into a Kindle unit

is

encapsulation. (e) (f)

(g)

(h)

One problem with OOP is that once a

ciaxa

is

created

it

van never he changed.

means the ability to reuse the data values of one object by Polymorphism is extensively used in implementing inheritance. Object-oriented programs are executed muck fanfcr than conventional Inheritance

programs. (i.)

Object-oriented systems can scale up better from small to large.

(j)

Object-oriented approach cannot be used to create databases.

Copyrighted material

2 Beginning with C++

Key Concepts

|2.1

What

is

C++?

is, an object-oriented programming language. It was developed by Bjarne Strougtrup at AT&T Bell Laboratories in

C++

Murray Hill New Jersey, USA, ,

V

C wilh

> V ^

C++ features Main function C++ ctjmtnetitH

V

Output operator

* y

Input operator

>

RH urn Statetnunt

>

Namespace

^

Variables

y

Cascading of operators

P y y y >

C++ program

cla.mws

Header

File

structure

Client-server model

Source

file

creation

Ccimpilation

Linking

in

the early

an admirer of Simula67 and a strong supporter of C wanted to combine the best of both the tanguatfeK and create a more powerful language that could support object-oriented programming features and still retain the power and elegance of C. The result was C++. Therefore, C++ is an extension of C with a major addition of the class construct feature of Simula67, Since the class wag a major addition to the original C language, Stroustrup initially called the new language C with classes'. However, later in 1963, the name was changed to C++, The idea of C++ comes from the C increment operator ++, thereby suggesting that C++ is an augmented (incremented) version of C. 1980's. Stroustrup,

t

During the early the language underwent a number of improvements and

Copyrighted material



20

Object Oriented Progrumn\inxj with

changes. In

November

1997, the

and added several new features

0

+

ANSI/ISO standards committee standardised these changes to the

language specifications.

C++ is a superset of C. Most of what we already know about C applies to C++ also. Therefore, almost all C programs are also C++ program^. However, there are a few minor diffe.ranraii that will prevent a C program in run under C++ compiler, We shall see these differences later as

and when they

are encountered.

The most important facilities that C++ adds on to C are clashes, inheritance, function overloading, and operator overloading. These features enable creating of abstract data types, inherit properties from existing data types and support polymorphism, thereby making C++ a truly object-oriented language, The

object-oriented features in

and ease

clarity, extensibility

C++

allow programmers to build large programs with

of maintenance, incorporating the spirit

and

efficiency of C,

The addition of new features has transformed C from a language that currently

facilitates

top-down, structured design, to one that provides bottom-up, object-oriented design.

[2,2

C++ in

C+ +

Applicat ions of

a versatile language for handling very large programs.

any compilers, databases, communication 1

1

1

-

.-ui

table for virtually

programming task including development of editors, systems and any complex real-lite application systems.

* • • *

1

2.3

Since C++ allows us to create hierarchy-related objects., we can buildspccial objectoriented libraries which can be used later by many programmers. While C++ is able to map the real-world problem properly, the C part of C++ gives the language the ability to get close te the machine- level details. C++ programs are easily maintainable and expandable. When a new feature needs t» ht> implemented, it is very «asy Lo add to the exiting utructurft of an objectIt is expected that C++ will replace C as ajsenerul-uurpose Language in the near future.

C++

A Simple

Program

Let us begin with a simple example of a

PUNTING

*

include

C + + program

that prints a string on the screen.

STRING «=1

ast

rearr.>

// include header file

usi^g namespace 5td; (Ctmtd)

Copyrighted material

*

Beginning with C**

21

int mainf) cokft

«

"C++ is better thin C.\n";

return 0; ^

1

^

ffiypj^y

^

// C++ Jttfteitwfll

;

c^ example

if'(^0^^^

fRWWW

This simple program demonstrates several

C++

£.1

features.

Program Features Like C, the C++ program

is

a collection of functions.

The above example contains only one

mainO. As usual, execution begins at mainO- Every C++ program must have a mainO. C++ is a free- form language. With a few exceptions, the compiler ignores carriage returns and white spaces, Like C the C++ statements terminate with semicolons. function,

Comments C++

new comment symbol // double slash). Comments start with a double symbol and terminate at the end of the line, A comment may start anywhere in the slash line, and whatever fallows till the end of the line is ignored. Note that there is no dosing introduces a

i

Symbot-

The double slash written as follows: // // //

comment is

basically a single line

comment. Multiline comments can be

This is art example of C++ program to illustrate Some Qf its feotvres

The C comment symbols i x " / are still valid and are more suitable for multiline comments. The following comment is allowed: ,

/*

This

is.

an example of

C++ program to illustrate same of its features

7 We can use either or both styles in our programs. Since this is a boot on C++ we will use only the C+ + style. However, remember that we can not insert a # style comment within the text offl program line. For example, thtf double slash comment cannot be used in the* manner as shown below: ,

forfj-0; j^n;

/* loops n times */ j+*J

C opy rig hted m ateri al

22 •

Object-Oriented Programming with C+ +

Output Operator The only statement cout

«

in

Program

2,1 is

"C++ is better than C.

causes the string

in quotation

an output statement. The statement H ;

marks

to

be

«

displayed

on

the screen. This statement 1

Thy

introduces two new C++ features, 4-imt and identifier cout (pronounced as 'C out ) is a predefined ithjetrt that represents the standard output Htretim in C++- Here,, the standard redi reel the output to other output Output stream rep resents the screen. Ft is also possihk I

devices.

We shall later discuss sLreums in

The operator

Contains classes and functions used by the standard library to allocate memory to the standard library containers. Contains classes

for

manipulating data in the standard library

containers

Contains functions

for

manipulating data

in the

standard Library

containers. c exceptions

cstdexcept*

These header

files

contain classes that arc used for exception

handling.

Contains the definition of class string from the standard Library. Discussed in Chapter 15

Contains function prototypes for functions that perform input from strings in memory and output to strings in memory.