Object Oriented Programming Through C++ As per the latest syllabus of JNTU (Kakinada)—Regulation 2014
 9789339212247, 933921224X

Table of contents :
Title
Contents
Unit 1
1 Introduction
2 Input and Output in C++
Unit 2
3 Operators and Control Structures
4 Functions in C++
Unit 3
5 Classes and Objects
Unit 4
6 Constructors and Destructors
7 Operator Overloading and Type Conversions
Unit 5
8 Inheritance: Extending Classes
9 Binding, Virtual Functions and Polymorphism
Unit 6
10 Applications with Files
11 Generic Programming with Templates
12 Exception Handling
Unit 7
13 Manipulating Strings
14 New Features of ANSI C++ Standard
15 Object-Oriented System Development
Appendix A Projects
Appendix B Answers to Debugging Exercises
Appendix C Executing Turbo C++
Appendix D Executing C++ Under Windows
Appendix E Glossary of ANSI C++ Keywords
Appendix F C++ Operator Precedence
Appendix G Points to Remember
Appendix H Glossary of Important C++ and OOP Terms
Appendix I C++ Proficiency Test with Answers

Citation preview

OBJECT ORIENTED PROGRAMMING THROUGH

C++ As per the latest syllabus of JNTU (Kakinada)—Regulation 2014

MEET THE AUTHOR E Balagurusamy, former Vice Chancellor, Anna University, Chennai and Member, Union Public Service Commission, New Delhi, is currently the Chairman of EBG Foundation, Coimbatore. He is a teacher, trainer, and consultant in the fields of Information Technology and Management. He holds an ME (Hons) in Electrical Engineering and a PhD in Systems Engineering from the Indian Institute of Technology, Roorkee. His areas of interest include ObjectOriented Software Engineering, E-Governance, Technology Management, Business Process Re-engineering, and Total Quality Management. A prolific writer, Dr Balagurusamy has authored a large number of research papers and several books. His best-selling books, among others include • Fundamentals of Computers • Computing Fundamentals and C Programming • Programming in ANSI C, 6e • Programming in Java, 4e • Programming in BASIC, 3e • Programming in C# , 3e • Numerical Methods • Reliability Engineering A recipient of numerous honors and awards, Dr Balagurusamy has been listed in the Directory of Who’s Who of Intellectuals and in the Directory of Distinguished Leaders in Education.

OBJECT ORIENTED PROGRAMMING THROUGH

C++ As per the latest syllabus of JNTU (Kakinada)—Regulation 2014

E Balagurusamy Chairman EBG Foundation Coimbatore

McGraw Hill Education (India) Private Limited NEW DELHI

McGraw Hill Education Offices New Delhi New York St Louis San Francisco Auckland Bogotá Caracas Kuala Lumpur Lisbon London Madrid Mexico City Milan Montreal San Juan Santiago Singapore Sydney Tokyo Toronto

McGraw Hill Education (India)!Qsjwbuf!Mjnjufe Qvcmjtife!cz!NdHsbx!Ijmm!Fevdbujpo!)Joejb*!Qsjwbuf!Mjnjufe Q.35-!Hsffo!Qbsl!Fyufotjpo-!Ofx!Efmij!221!127 Pckfdu!Psjfoufe!Qsphsbnnjoh!uispvhi!D,, Dpqzsjhiu!©!3126!cz!NdHsbx!Ijmm!Fevdbujpo!)Joejb*!Qsjwbuf!Mjnjufe/ Op! qbsu! pg! uijt! qvcmjdbujpo! nbz! cf! sfqspevdfe! ps! ejtusjcvufe! jo! boz! gpsn! ps! cz! boz! nfbot-! fmfduspojd-! nfdibojdbm-!qipupdpqzjoh-!sfdpsejoh-!ps!puifsxjtf!ps!tupsfe!jo!b!ebubcbtf!ps!sfusjfwbm!tztufn!xjuipvu!uif!qsjps! xsjuufo!qfsnjttjpo!pg!uif!qvcmjtifst/!Uif!qsphsbn!mjtujoht!)jg!boz*!nbz!cf!foufsfe-!tupsfe!boe!fyfdvufe!jo!b! dpnqvufs!tztufn-!cvu!uifz!nbz!opu!cf!sfqspevdfe!gps!qvcmjdbujpo/ Uijt!fejujpo!dbo!cf!fyqpsufe!gspn!Joejb!pomz!cz!uif!qvcmjtifstNdHsbx!Ijmm!Fevdbujpo!)Joejb*!Qsjwbuf!Mjnjufe/ ISBN (13 digit): 978-93-3921-224-7 ISBN (10 digit): 93-3921-224-X Managing Director: Kaushik Bellani HeadūHigher Education (Publishing and Marketing): Vibha Mahajan Sr. Publishing ManagerūSEM & Tech Ed.: Shalini Jha Editorial ExecutiveūAcq.: S. Vamsi Deepak NbobhfsÐQspevdujpo!Tztufnt;!Tbujoefs!T!Cbwfkb Bttjtubou!NbobhfsÐFejupsjbm!Tfswjdft;!Tpijoj!Nvlifskff Ts/!Qspevdujpo!Nbobhfs;!Q!M!Qboejub Bttu/!Hfofsbm!NbobhfsÐIjhifs!Fevdbujpo!)Nbslfujoh*;!Wjkbz!Tbsbuij Bttu/!Qspevdu!Nbobhfs;!Ujob!Kbkpsjzb Ts/!Hsbqijd!Eftjhofs!)Dpwfs*;!Nffov!Sbhibw Hfofsbm!NbobhfsÐQspevdujpo;!Sbkfoefs!Q!Hibotfmb Qspevdujpo!Nbobhfs;!Sfkj!Lvnbs Jogpsnbujpo!dpoubjofe!jo!uijt!xpsl!ibt!cffo!pcubjofe!cz!NdHsbx!Ijmm!Fevdbujpo!)Joejb*-!gspn!tpvsdft!cfmjfwfe! up!cf!sfmjbcmf/!Ipxfwfs-!ofjuifs!NdHsbx!Ijmm!Fevdbujpo!)Joejb*!ops!jut!bvuipst!hvbsbouff!uif!bddvsbdz!ps! dpnqmfufoftt!pg!boz!jogpsnbujpo!qvcmjtife!ifsfjo-!boe!ofjuifs!NdHsbx!Ijmm!Fevdbujpo!)Joejb*!ops!jut!bvuipst! tibmm!cf!sftqpotjcmf!gps!boz!fsspst-!pnjttjpot-!ps!ebnbhft!bsjtjoh!pvu!pg!vtf!pg!uijt!jogpsnbujpo/!Uijt!xpsl!jt! qvcmjtife!xjui!uif!voefstuboejoh!uibu!NdHsbx!Ijmm!Fevdbujpo!)Joejb*!boe!jut!bvuipst!bsf!tvqqmzjoh!jogpsnbujpo! cvu!bsf!opu!buufnqujoh!up!sfoefs!fohjoffsjoh!ps!puifs!qspgfttjpobm!tfswjdft/!Jg!tvdi!tfswjdft!bsf!sfrvjsfe-!uif! bttjtubodf!pg!bo!bqqspqsjbuf!qspgfttjpobm!tipvme!cf!tpvhiu/ Uzqftfu!bu!Ufk!Dpnqptfst-!X[!4:2-!Nbejqvs-!Ofx!Efmij!221!174!boe!qsjoufe!bu

CONTENTS Preface

xiii

VOJU!Ï!2 1.

Introduction

3

1.1 Software Crisis 4 1.2 Software Evolution 5 1.3 A Look at Procedure-Oriented Programming 6 1.4 Object-Oriented Programming Paradigm 8 1.5 Basic Concepts of Object-Oriented Programming 9 1.6 Benefits of OOP 13 1.7 Object-Oriented Languages 14 1.8 Applications of OOP 15 1.9 What is C++? 16 1.10 Applications of C++ 16 1.11 A Simple C++ Program 17 1.12 More C++ Statements 21 1.13 An Example with Class 23 1.14 Structure of C++ Program 24 1.15 Creating the Source File 25 1.16 Compiling and Linking 25 Summary 26 Review Questions 28 Debugging Exercises 29 Programming Exercises 30

2.

Input and Output in C++ 2.1 2.2 2.3 2.4 2.5 2.6

Introduction 32 C++ Streams 32 C++ Stream Classes 33 Unformatted I/O Operations 34 Formatted Console I/O Operations 41 Managing Output with Manipulators 52 Summary 56 Review Questions 57

31

vi

Contents

Debugging Exercises 59 Programming Exercises 60

VOJU!Ï!3 3.

Operators and Control Structures 3.1 Introduction 64 3.2 Tokens 64 3.3 Keywords 64 3.4 Identifiers and Constants 65 3.5 Basic Data Types 66 3.6 User-Defined Data Types 68 3.7 Storage Classes 71 3.8 Derived Data Types 72 3.9 Symbolic Constants 73 3.10 Type Compatibility 74 3.11 Declaration of Variables 75 3.12 Dynamic Initialization of Variables 3.13 Reference Variables 76 3.14 Operators in C++ 78 3.15 Scope Resolution Operator 78 3.16 Member Dereferencing Operators 3.17 Memory Management Operators 3.18 Manipulators 85 3.19 Type Cast Operator 87 3.20 Expressions and Their Types 88 3.21 Special Assignment Expressions 3.22 Implicit Conversions 91 3.23 Operator Overloading 92 3.24 Operator Precedence 93 3.25 Control Structures 93 Summary 98 Review Questions 99 Debugging Exercises 100 Programming Exercises 102

4.

Functions in C++ 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8

Introduction 105 The Main Function 105 Function Prototyping 106 Call by Reference 108 Return by Reference 109 Inline Functions 109 Default Arguments 111 const Arguments 113

63

75

80 81

90

104

Contents

4.9 4.10 4.11 4.12

vii

Recursion 113 Function Overloading 115 Friend and Virtual Functions 117 Math Library Functions 118 Summary 119 Review Questions 120 Debugging Exercises 121 Programming Exercises 123

VOJU!Ï!4 5.

Classes and Objects 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 5.10 5.11 5.12 5.13 5.14 5.15 5.16 5.17 5.18 5.19

127

Introduction 128 C Structures Revisited 128 Specifying a Class 130 Defining Member Functions 133 A C++ Program with Class 135 Making an Outside Function Inline 137 Nesting of Member Functions 137 Private Member Functions 139 Arrays within a Class 139 Memory Allocation for Objects 144 Static Data Members 144 Static Member Functions 147 Arrays of Objects 148 Objects as Function Arguments 151 Friendly Functions 153 Returning Objects 158 const Member Functions 160 Pointers to Members 160 Local Classes 162 Summary 163 Review Questions 164 Debugging Exercises 164 Programming Exercises 168

VOJU!Ï!5 6.

Constructors and Destructors 6.1 6.2 6.3 6.4 6.5

Introduction 172 Constructors 173 Parameterized Constructors 174 Multiple Constructors in a Class 176 Constructors with Default Arguments 179

171

viii

Contents

6.6 6.7 6.8 6.9 6.10 6.11

7.

Dynamic Initialization of Objects 179 Copy Constructor 182 Dynamic Constructors 183 Constructing Two-Dimensional Arrays 185 const Objects 187 Destructors 187 Summary 190 Review Questions 191 Debugging Exercises 191 Programming Exercises 194

Operator Overloading and Type Conversions

195

7.1 Introduction 196 7.2 Defining Operator Overloading 196 7.3 Overloading Unary Operators 198 7.4 Overloading Binary Operators 199 7.5 Overloading Binary Operators Using Friends 202 7.6 Manipulation of Strings Using Operators 205 7.7 Some Other Operator Overloading Examples 208 7.8 Rules for Overloading Operators 210 7.9 Type Conversions 211 Summary 218 Review Questions 219 Debugging Exercises 219 Programming Exercises 221

VOJU!Ï!6 8.

Inheritance: Extending Classes 8.1 8.2 8.3 8.4 8.5 8.6 8.7 8.8 8.9 8.10 8.11 8.12

Introduction 226 Defining Derived Classes 227 Single Inheritance 228 Making a Private Member Inheritable 234 Multilevel Inheritance 237 Multiple Inheritance 241 Hierarchical Inheritance 245 Hybrid Inheritance 247 Virtual Base Classes 249 Abstract Classes 253 Constructors in Derived Classes 254 Member Classes: Nesting of Classes 260 Summary 261 Review Questions 262 Debugging Exercises 263 Programming Exercises 267

225

Contents

9.

Binding, Virtual Functions and Polymorphism 9.1 9.2 9.3 9.4 9.5 9.6 9.7 9.8

ix

270

Introduction 271 Pointers 272 Pointers to Objects 282 this Pointer 286 Pointers to Derived Classes 288 Virtual Functions 291 Pure Virtual Functions 295 Virtual Constructors and Destructors 297 Summary 298 Review Questions 299 Debugging Exercises 300 Programming Exercises 304

VOJU!Ï!7 10.

Applications with Files 10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8 10.9 10.10

11.

Generic Programming with Templates 11.1 11.2 11.3 11.4 11.5 11.6 11.7 11.8 11.9 11.10 11.11 11.12

307

Introduction 308 Classes for File Stream Operations 309 Opening and Closing a File 310 Detecting end-of-file 317 More about Open(): File Modes 318 File Pointers and their Manipulations 319 Sequential Input and Output Operations 321 Updating a File: Random Access 327 Error Handling During File Operations 331 Command-line Arguments 333 Summary 335 Review Questions 337 Debugging Exercises 338 Programming Exercises 340

Introduction to Templates 342 Class Templates 342 Class Templates with Multiple Parameters 347 Function Templates 349 Function Templates with Multiple Parameters 354 Overloading of Template Functions 355 Member Function Templates 356 Non-type Template Arguments 357 Introduction to Standard Template Library 358 Components of STL 358 Containers 359 Algorithms 362

341

x

Contents

11.13 11.14 11.15

12.

Iterators 365 Application of Container Classes 366 Function Objects 375 Summary 377 Review Questions 378 Debugging Exercises 380 Programming Exercises 384

Exception Handling 12.1 12.2 12.3 12.4 12.5 12.6 12.7 12.8 12.9

386

Introduction 387 Basics of Exception Handling 387 Exception Handling Mechanism 388 Throwing Mechanism 392 Catching Mechanism 392 Rethrowing an Exception 397 Specifying Exceptions 399 Exceptions in Constructors and Destructors 400 Exceptions in Operator Overloaded Functions 402 Summary 403 Review Questions 403 Debugging Exercises 404 Programming Exercises 408

VOJU!Ï!8 13.

Manipulating Strings 13.1 13.2 13.3 13.4 13.5 13.6 13.7

14.

Introduction 412 Creating (string) Objects 414 Manipulating String Objects 415 Relational Operations 416 String Characteristics 417 Accessing Characters in Strings 419 Comparing and Swapping 420 Summary 422 Review Questions 423 Debugging Exercises 424 Programming Exercises 426

New Features of ANSI C++ Standard 14.1 14.2 14.3 14.4 14.5 14.6

411

Introduction 428 New Data Types 428 New Operators 430 Class Implementation 433 Namespace Scope 435 Operator Keywords 440

427

Contents

14.7 14.8

15.

New Keywords 441 New Headers 442 Summary 442 Review Questions 443 Debugging Exercises 444 Programming Exercises 446

Object-Oriented Systems Development 15.1 15.2 15.3 15.4 15.5 15.6 15.7 15.8 15.9 15.10

xi

447

Introduction 448 Procedure-Oriented Paradigms 449 Procedure-Oriented Development Tools 451 Object-Oriented Paradigm 452 Object-Oriented Notations and Graphs 454 Steps in Object-Oriented Analysis 458 Steps in Object-Oriented Design 461 Implementation 467 Prototyping Paradigm 467 Wrapping Up 469 Summary 469 Review Questions 471

Appendix A: Projects

473

Appendix B: Answers to Debugging Exercises

491

Appendix C: Executing Turbo C++

503

Appendix D: Executing C++ Under Windows

515

Appendix E: Glossary of ANSI C++ Keywords

526

Appendix F: C++ Operator Precedence

531

Appendix G: Points to Remember

534

Appendix H: Glossary of Important C++ and OOP Terms

546

Appendix I: C++ Proficiency Test with Answers

557

PREFACE Object-Oriented Programming (OOP) has become the preferred programming approach by the software industries, as it offers a powerful way to cope with the complexity of real-world problems. Among the OOP languages today, C++ is by far the most widely used language. Since its creation by Bjarne Stroustrup in the early 1980s, C++ has undergone many changes and improvements. The language was standardized in 1998 by the American National Standards Institute (ANSI) and the International Standards Organization (ISO) by incorporating not only the new features but also the changes suggested by the user groups. The present edition completely follows the specifications of ANSI/ISO Standards. Object Oriented Programming with C++ is for programmers who wish to know all about the C++ language and object-oriented programming. It explains in a simple and easy-to-understand style the what, why and how of object-oriented programming with C++. The book assumes that the readers are already familiar with C language, although she or he need not be an expert programmer. The book provides numerous examples, illustrations and complete programs. The sample programs are meant to be both simple and educational. Wherever necessary, pictorial descriptions of concepts have been included to improve clarity and facilitate better understanding. The book also presents the concept of object-oriented approach and discusses important elements of objectoriented analysis and design of systems.

SALIENT FEATURES •

Completely in tune with JNTU Kakinada syllabus regulation – 2013



Solution to previous year’s exam papers and model question papers given



PowerPoint slides as web supplements for instructors

• Simple and easy-to-understand language • Extended coverage to topics like Overloading, Abstract Classes, Typecasting, Dynamic Memory Allocation, Structures and Unions, and RTTI • Projects to enhance programming skills • Refreshed C++ proficiency test covering latest technical interview questions along with answers • Refreshed and enhanced pedagogy which includes over 500 pedagogical aids like programs, review questions, debugging exercise with answers, programming exercises, and special boxes with notes wherever relevant • Exhaustive Pedagogy b Solved Programs – 168 b Review Questions – 130

xiv

Preface

CHAPTER ORGANIZATION The book has 6 units, Unit 1 deals with basics of object oriented programming and I/O in C++. Unit 2 deals with basic concepts of C++ programming. Unit 3 deals with classes, objects and member functions. Unit 4 deals with constructors, destructors, operator overloading and type conversion. Unit 5 deals with inheritance, polymorphism and virtual functions. Unit 6 deals with file operations, generic programming and exception handling. Unit 7 and Appendices provide additional information on C++.

ACKNOWLEDGEMENTS I would like to thank Mr. Deepak Manoj from University of Florida for his review feedback. My sincere thanks are due to the editorial and publishing professionals of McGraw Hill Education (India) for their keen interest and support in bringing out this edition in its present form.

E Balagurusamy

PUBLISHER'S NOTE Remember to write to us. We look forward to receiving your feedback, comments and ideas to enhance the quality of this book. You can reach us at [email protected]. Please mention the title and the author’s name as the subject. In case you spot piracy of this book, in any form, please do let us know.

Object-oriented programming

xv

OBJECT-ORIENTED PROGRAMMING THROUGH C++ Objectives: Expertise in object oriented principles and their implementation in C++

UNIT I Objectives: Exposure to basics of object oriented mode, C++ programming and I/O in C++ Introduction: Differences Between C and C++, The Object Oriented Technology, Disadvantage of Conventional Programming, Concepts of Object Oriented Programming, Advantages of OOP. Structure of a C++ Program, Header Files and Libraries. Input and Output in C++: Introduction, Streams In C++ and Stream Classes, Pre-Defined Streams, Stream Classes, Formatted and Unformatted Data, Unformatted Console I/O Operations, Member Functions of Istream Class, Formatted Console I/O Operations, Bit Fields, Flags Without Bit Field, Manipulators, User-Defined Manipulators.

UNIT II Objectives: Focus on Basic concept in C++ Programming, Operators, control structures, functions, overloading, recursion Tokens in C++, Variable Declaration and Initialization, Data Types, Operators in C and C++, Scope Access Operator, Namespace, Memory Management Operators, Comma Operator, Revision of Decision Statements, Control Loop Statements. Functions in C++: Introduction, Structure of Function, Passing Arguments, Lvalues and Rvalues, Return by Reference, Returning More Values by Reference, Default Arguments, Const Arguments, Inputting Default Arguments, Inline Functions, Function Overloading Principles of Function Overloading, Recursion.

UNIT III Objectives: Acquaintance with classes, objects and member functions Classes and Objects: Introduction, Classes In C++, Declaring Objects, Access Specifiers and Their Scope, Member Functions, Outside Member Function as Inline, Data Hiding or

xvi

Object-Oriented Programming through C++

Encapsulation, Classes, Objects and Memory, Static Member Variables, Static Member Functions, Static Object, Array of Objects, Objects as Function Arguments, Friend Functions, The Const Member Function, The Volatile Member Function, Recursive Member Function, Local Classes, Empty, Static and Const Classes, Member Function and Non-Member Function, Overloading Member Functions, Nested Class.

UNIT IV Objectives: Focus on constructors, destructors, variants in them, operator overloading, type conversions Constructors and Destructors: Introduction, Characteristic of Constructors and Destructors, Applications With Constructors, Parameterized Constructor, Overloading Constructors (Multiple Constructors), Array of Objects Using Constructors, Constructors With Default Arguments, Copy Constructors, The Const Objects, Destructors, Calling Constructors, and Destructors, Qualifier and Nested Classes, Anonymous Objects, Private Constructors and Destructors, Dynamic Initialization Using Constructors, Dynamic Operators and Constructors, Recursive Constructor, Constructor and Destructor with Static Members, Local vs. Global Object. Operator Overloading and Type Conversion: Introduction, Overloading Unary Operators, Constraint on Increment and Decrement Operators, Overloading Binary Operators, Overloading with Friend Function, Overloading Assignment Operator (=), Type Conversion, Rules for Overloading Operators, One Argument Constructor and Operator Function, Overloading Stream Operators.

UNIT V Objective: Concentration on inheritance, types of inheritance, polymorphism, virtual functions Inheritance: Introduction, Reusability, Access Specifiers and Simple Inheritance, Protected Data With Private Inheritance, Types of Inheritances (Single Inheritance, Multilevel Inheritance, Multiple Inheritance, Hierarchical Inheritance, Hybrid Inheritance, Multipath Inheritance), Virtual Base Classes, Constructors, Destructors, and Inheritance, Object as a Class Member, Abstract Classes, Qualifier Classes and Inheritance, Constructor in Derived Class, Pointers and Inheritance, Overloading Member Function, Advantages of Inheritance, Disadvantages of Inheritance. Binding Polymorphism and Virtual Functions: Introduction, Binding In C++, Static (Early) Binding, Dynamic (Late) Binding, Pointer to Base and Derived Class Objects, Virtual Functions, Rules for Virtual Functions, Array of Pointers, Pure Virtual Functions, Abstract Classes, Working of Virtual Functions, Virtual Functions in Derived Classes, Object Slicing, Constructors and Virtual Functions, Virtual Destructors, Destructor and Virtual Functions.

Object-Oriented Programming through C++

xvii

UNIT VI Objectives: Focus on Files, File operations, generic programming, templates, function templates, Exception handling Applications with Files: Introduction, File Stream Classes, File Opening Modes, File Pointers, and Manipulators, Manipulators With Arguments, Sequential Access Files, Binary and ASCII Files Random Access Operation. Generic Programming with Templates: Introduction, Need of Template, Definition of Class Template, Normal Function Template, Working of Function Templates, Class Template with More Parameters, Functions Templates with More Arguments, Overloading of Template Functions, Member Function Template, Recursion with Template Function, Class Template with Overloaded Operators, Class Template Revisited, Class Templates and Inheritance, Container Classes, Types of Containers, Container Adaptors, Iterators. Exception Handling: Introduction, Principles of Exception Handling, The Keywords Try, Throw and Catch, Exception Handling Mechanism, Multiple Catch Statements, Catching Multiple Exceptions, Re-Throwing Exception, Specifying Exception, Exceptions, In Constructor and Destructors, Controlling Uncaught Exceptions, Class Template with Exception Handling.

70+6!c � Chapter 1: Introduction � Chapter 2: Input and Output in C++

c +0641&7%6+10 .'#40+0)!1$,'%6+8'5 � � � � �

Software Crisis Software Evolution A Look at Procedure-Oriented Programming Object-Oriented Programming Paradigm Basic Concepts of Object-Oriented Programming � � � � � � �

� � � � � �

Objects Classes Data Abstraction and Encapsulation Inheritance Polymorphism Dynamic Binding Message Passing

Benefits of OOP Object-Oriented Languages Applications of OOP What is C++? Applications of C++ A Simple C++ Program � � � � � �

Program Features Comments Output Operator The iostream File Namespace Return Type of main( )

� More C++ Statements � Variables � Input Operator � Cascading of I/O Operators

� � � �

An Example with Class Structure of C++ Program Creating the Source File Compiling and Linking � Unix AT&T C++ � Turbo C++ and Borland C++ � Visual C++

4

Object Oriented Programming through C++

Key Concepts Software evolution | Procedure-oriented programming | Object-oriented programming | Objects | Classes | Data abstraction | Encapsulation | Inheritance | Polymorphism | Dynamic binding | Message passing | Object-oriented languages | Object-based languages | C with classes | C++ features | Main function | C++ comments | Output operator | Input operator | Header file | Return statement | Namespace | Variables | Cascading of operators | C++ program structure | Client-server model | Source file creation | Compilation | Linking

1.1 SOFTWARE CRISIS Developments in software technology continue to be dynamic. New tools and techniques are announced in quick succession. This has forced the software engineers and industry to continuously look for new approaches to software design and development, and they are becoming more and more critical in view of the increasing complexity of software systems as well as the highly competitive nature of the industry. These rapid advances appear to have created a situation of crisis within the industry. The following issues need to be addressed to face this crisis: • • • • • • • •

How to represent real-life entities of problems in system design? How to design systems with open interfaces? How to ensure reusability and extensibility of modules? How to develop modules that are tolerant to any changes in future? How to improve software productivity and decrease software cost? How to improve the quality of software? How to manage time schedules? How to industrialize the software development process?

Many software products are either not finished, or not used, or else are delivered with major errors. Figure 1.1 shows the fate of the US defence software projects undertaken in the 1970s. 3.5

Paid for but not received

Project value $m

3 Delivered but not used

2.5 2

Abandoned or reworked

1.5 1

Used after change

0.5

Used as delivered

0 1

2

3

4

5

Projects

Fig. 1.1 The state of US defence projects (according to the US government)

Introduction

5

Around 50% of the software products were never delivered, and one-third of those which were delivered were never used. It is interesting to note that only 2% were used as delivered, without being subjected to any changes. This illustrates that the software industry has a remarkably bad record in delivering products. Changes in user requirements have always been a major problem. Another study (Fig. 1.2) shows that more than 50% of the systems required modifications due to changes in user requirements and data formats. It only illustrates that, in a changing world with a dynamic business environment, requests for change are unavoidable and therefore systems must be adaptable and tolerant to changes. Hardware changes

Documentation Other 3.4% 6.2%

Routine debugging

Efficiency improvement 4.0%

5.5%

Changes in user requirements 41.9%

9.0%

Emergency fixes

12.4% 17.5% Changes in data formats

Fig. 1.2 Breakdown of maintenance costs These studies and other reports on software implementation suggest that software products should be evaluated carefully for their quality before they are delivered and implemented. Some of the quality issues that must be considered for critical evaluation are 1. Correctness 2. Maintainability 3. Reusability 4. Openness and interoperability 5. Portability 6. Security 7. Integrity 8. User friendliness Selection and use of proper software tools would help resolving some of these issues.

1.2 SOFTWARE EVOLUTION Ernest Tello, a well-known writer in the field of artificial intelligence, compared the evolution of software technology to the growth of a tree. Like a tree, the software evolution has had distinct phases or “layers” of growth. These layers were built up one by one over the last five decades as shown in Fig. 1.3, with each layer representing an improvement over the previous one. However, the

6

Object Oriented Programming through C++

analogy fails if we consider the life of these layers. In software systems, each of the layers continues to be functional, whereas in the case of trees, only the uppermost layer is functional.

1, 0

Machine language Assembly language Procedure-oriented Object-oriented programming

Fig. 1.3 Layers of computer software

Alan Kay, one of the promoters of the object-oriented paradigm and the principal designer of Smalltalk, has said: “As complexity increases, architecture dominates the basic material ”. To build today’s complex software, it is just not enough to put together a sequence of programming statements and sets of procedures and modules; we need to incorporate sound construction techniques and program structures that are easy to comprehend, implement and modify. Since the invention of the computer, many programming approaches have been tried. These include techniques such as modular programming, top-down programming, bottom-up programming and structured programming. The primary motivation in each has been the concern to handle the increasing complexity of programs that are reliable and maintainable. These techniques have become popular among programmers over the last two decades. With the advent of languages such as C, structured programming became very popular and was the main technique of the 1980s. Structured programming was a powerful tool that enabled programmers to write moderately complex programs fairly easily. However, as the programs grew larger, even the structured approach failed to show the desired results in terms of bug-free, easy-tomaintain, and reusable programs. Object-Oriented Programming (OOP) is an approach to program organization and development that attempts to eliminate some of the pitfalls of conventional programming methods by incorporating the best of structured programming features with several powerful new concepts. It is a new way of organizing and developing programs and has nothing to do with any particular language. However, not all languages are suitable to implement the OOP concepts easily.

1.3 A LOOK AT PROCEDURE-ORIENTED PROGRAMMING Conventional programming, using high level languages such as COBOL, FORTRAN and C, is commonly known as procedure-oriented programming (POP). In the procedure-oriented approach, the problem is

Introduction

7

viewed as a sequence of things to be done such as reading, calculating and printing. A number of functions are written to accomplish these tasks. The primary focus is on functions. A typical program structure for procedural programming is shown in Fig. 1.4. The technique of hierarchical decomposition has been used to specify the tasks to be completed for solving a problem. Main Program

Function - 1

Function - 5

Function - 4

Function - 6

Function - 3

Function - 2

Function - 7

Function - 8

Fig. 1.4 Typical structure of procedure-oriented programs Procedure-oriented programming basically consists of writing a list of instructions (or actions) for the computer to follow, and organizing these instructions into groups known as functions. We normally use a flowchart to organize these actions and represent the flow of control from one action to another. While we concentrate on the development of functions, very little attention is given to the data that are being used by various functions. What happens to the data? How are they affected by the functions that work on them? In a multi-function program, many important data items are placed as global so that they may be accessed by all the functions. Each function may have its own local data. Figure 1.5 shows the relationship of data and functions in a procedure-oriented program. Global data are more vulnerable to an inadvertent change by a function. In a large program it is very difficult to identify what data is used by which function. In case we need to revise an external data structure, we also need to revise all functions that access the data. This provides an opportunity for bugs to creep in. Another serious drawback with the procedural approach is that it does not model real world problems very well. This is because functions are action-oriented and do not really correspond to the elements of the problem. Some characteristics exhibited by procedure-oriented programming are • Emphasis is on doing things (algorithms). • Large programs are divided into smaller programs known as functions. • Most of the functions share global data. • Data move openly around the system from function to function. • Functions transform data from one form to another. • Employs top-down approach in program design.

8

Object Oriented Programming through C++ Global data

Global data

Function -1

Function -2

Function -3

Local data

Local data

Local data

Fig. 1.5 Relationship of data and functions in procedural programming

1.4 OBJECT-ORIENTED PROGRAMMING PARADIGM The major motivating factor in the invention of object-oriented approach is to remove some of the flaws encountered in the procedural approach. OOP treats data as a critical element in the program development and does not allow it to flow freely around the system. It ties data more closely to the functions that operate on it, and protects it from accidental modification from outside functions. OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects. The organization of data and functions in object-oriented programs is shown in Fig. 1.6. The data of an object can be accessed only by the functions associated with that object. However, functions of one object can access the functions of other objects. Object A

Object B

Data

Data

Functions

Communication

Functions

Object C Functions

Data

Fig. 1.6 Organization of data and functions in OOP

Introduction

9

Some of the striking features of object-oriented programming are: • Emphasis is on data rather than procedure. • Programs are divided into what are known as objects. • Data structures are designed such that they characterize the objects. • Functions that operate on the data of an object are tied together in the data structure. • Data is hidden and cannot be accessed by external functions. • Objects may communicate with each other through functions. • New data and functions can be easily added whenever necessary. • Follows bottom-up approach in program design. Object-oriented programming is the most recent concept among programming paradigms and still means different things to different people. It is therefore important to have a working definition of object-oriented programming before we proceed further. We define “object-oriented programming as an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand.” Thus, an object is considered to be a partitioned area of computer memory that stores data and set of operations that can access that data. Since the memory partitions are independent, the objects can be used in a variety of different programs without modifications.

1.5 BASIC CONCEPTS OF OBJECT-ORIENTED PROGRAMMING It is necessary to understand some of the concepts used extensively in object-oriented programming. These include • Objects • Classes • Data abstraction and encapsulation • Inheritance • Polymorphism • Dynamic binding • Message passing We shall discuss these concepts in some detail in this section.

Objects Objects are the basic run-time entities in an object-oriented system. They may represent a person, a place, a bank account, a table of data or any item that the program has to handle. They may also represent user-defined data such as vectors, time and lists. Programming problem is analyzed in terms of objects and the nature of communication between them. Program objects should be chosen such that they match closely with the real-world objects. Objects take up space in the memory and have an associated address like a record in Pascal, or a structure in C. When a program is executed, the objects interact by sending messages to one another. For example, if “customer” and “account” are two objects in a program, then the customer object may send a message to the account object requesting for the bank balance. Each object contains data, and code

10

Object Oriented Programming through C++

to manipulate the data. Objects can interact without having to know details of each other’s data or code. It is sufficient to know the type of message accepted, and the type of response returned by the objects. Although different authors represent them differently, Fig. 1.7 shows two notations that are popularly used in object-oriented analysis and design. STUDENT

Object: STUDENT DATA Name Date-of-birth Marks ...... FUNCTIONS Tota l Average Display ......

Total

Average

Display

Fig. 1.7 Two ways of representing an object

Classes We just mentioned that objects contain data, and code to manipulate that data. The entire set of data and code of an object can be made a user-defined data type with the help of a class. In fact, objects are variables of the type class. Once a class has been defined, we can create any number of objects belonging to that class. Each object is associated with the data of type class with which they are created. A class is thus a collection of objects of similar type. For example, mango, apple and orange are members of the class fruit. Classes are user-defined data types and behave like the built-in types of a programming language. The syntax used to create an object is no different than the syntax used to create an integer object in C. If fruit has been defined as a class, then the statement fruit mango; will create an object mango belonging to the class fruit.

Data Abstraction and Encapsulation The wrapping up of data and functions into a single unit (called class) is known as encapsulation. Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world, and only those functions which are wrapped in the class can access it. These functions provide the interface between the object’s data and the program. This insulation of the data from direct access by the program is called data hiding or information hiding. Abstraction refers to the act of representing essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, weight and cost, and functions to operate on these attributes. They encapsulate all the essential properties of the objects that are to be created. The attributes are sometimes called data members because they hold information. The functions that operate on these data are sometimes called methods or member functions. Since the classes use the concept of data abstraction, they are known as Abstract Data Types (ADT).

Introduction

11

Inheritance Inheritance is the process by which objects of one class acquire the properties of objects of another class. It supports the concept of hierarchical classification. For example, the bird ‘robin’ is a part of the class ‘flying bird’ which is again a part of the class ‘bird’. The principle behind this sort of division is that each derived class shares common characteristics with the class from which it is derived as illustrated in Fig. 1.8. Bird

Attributes Feathers Lay eggs

Flying Bird

Nonflying Bird

Attributes ................. ................. .................

Attributes ................. ................. .................

Robin

Swallow

Penguin

Kiwi

Attributes ................. ................. .................

Attributes ................. ................. .................

Attributes ................. ................. .................

Attributes ................. ................. .................

Fig. 1.8 Property inheritance In OOP, the concept of inheritance provides the idea of reusability. This means that we can add additional features to an existing class without modifying it. This is possible by deriving a new class from the existing one. The new class will have the combined features of both the classes. The real appeal and power of the inheritance mechanism is that it allows the programmer to reuse a class that is almost, but not exactly, what he wants, and to tailor the class in such a way that it does not introduce any undesirable side-effects into the rest of the classes. Note that each sub-class defines only those features that are unique to it. Without the use of classification, each class would have to explicitly include all of its features.

Polymorphism Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the ability to take more than one form. An operation may exhibit different behaviors in different instances. The behavior depends upon the types of data used in the operation. For example, consider the operation of addition. For two numbers, the operation will generate a sum. If the operands are strings, then the operation would produce a third string by concatenation. The process of making an operator to exhibit different behaviors in different instances is known as operator overloading.

12

Object Oriented Programming through C++

Figure 1.9 illustrates that a single function name can be used to handle different number and different types of arguments. This is something similar to a particular word having several different meanings depending on the context. Using a single function name to perform different types of tasks is known as function overloading. Polymorphism plays an important role in allowing objects having different internal structures to share the same external interface. This means that a general class of operations may be accessed in the same manner even though specific actions associated with each operation may differ. Polymorphism is extensively used in implementing inheritance. Shape Draw ()

Circle object

Box object

Triangle object

Draw (circle)

Draw (box)

Draw (triangle)

Fig. 1.9 Polymorphism

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. Its 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 process of programming in an object-oriented language, therefore, involves the following basic steps: 1. Creating classes that define objects and their behavior, 2. Creating objects from class definitions, and 3. Establishing communication among objects. Objects communicate with one another by sending and 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.

Introduction

13

A message for an object is 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) and the information to be sent. Example: employee.salary (name);

object

information message

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 OOP OOP offers several benefits to both the 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: • Through inheritance, we can eliminate redundant code and extend the use of existing 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 saving 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 co-exist without any interference. • It is possible to map objects in the problem domain to those in the program. • It is easy to partition the work in a project based on objects. • The data-centered design approach enables us to capture more details of a model in implementable 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 these features in an object-oriented system, their importance depends on the type of the project and the preference of the programmer. There are a number of issues that need to be tackled to reap some of the benefits stated above. For instance, object libraries must be available for reuse. The technology is still developing and current products may be superseded quickly. Strict controls and protocols need to be developed if reuse is not to be compromised. Developing a software that is easy to use makes it hard to build. It is hoped that the object-oriented programming tools would help manage this problem.

14

Object Oriented Programming through C++

1.7 OBJECT-ORIENTED LANGUAGES Object-oriented programming is 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 is specially designed to support the OOP concepts makes it easier to implement them. The languages should support several of the OOP concepts to claim that they are object-oriented. Depending upon the features they support, they can be classified into the following two categories: 1. Object-based programming languages, and 2. Object-oriented programming languages. Object-based programming is the style of programming that primarily supports encapsulation and object identity. Major features that are required for object-based programming are: • • • •

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

Languages that support programming with objects are said to be object-based programming languages. They do not support inheritance and dynamic binding. Ada is a typical object-based 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-based features + inheritance + dynamic binding Languages that support these features include C++, Smalltalk, Object Pascal and Java. There are a large number of object-based and object-oriented programming languages. Table 1.1 lists some popular general purpose OOP languages and their characteristics. Table 1.1

Characteristics of some OOP languages Simula Smalltalk Objective C++

Ada

Characteristics

Eiffel *

Java *

*

*

C

Both

Late

Both

Both

Early

Late

Early

Early

Both

(early or late)



















Polymorphism



















Data hiding



















Concurrency



Poor

Poor

No

No

Promised



Inheritance









No









Multiple Inheritance

No







No

---

---



No

Binding

**

Object Turbo Pascal Pascal

Poor Difficult

(Contd.)

Introduction

15

Table 1.1 (Contd.) Simula Smalltalk Objective C++

Ada

Characteristics **

Object Turbo Pascal Pascal

Eiffel *

Java *

*

*

C

Garbage Collection









No









Persistence

No

Promised

No

No

like 3GL

No

No

Some Support



Genericity

No

No

No





No

No



No

Object Libraries









Not much









* Pure object-oriented languages ** Object-based languages Others are extended conventional languages As seen from Table 1.1, all languages provide for polymorphism and data hiding. However, many of them do not provide facilities for concurrency, persistence and genericity. Eiffel, Ada and C++ provide generic facility which is an important construct for supporting reuse. However, persistence (a process of storing objects) is not fully supported by any of them. In Smalltalk, though the entire current execution state can be saved to disk, yet the individual objects cannot be saved to an external file. Simula is one of the oldest object oriented programming languages, though it has spent most of its life in a research environment. Commercially, C++ and Java are the most prominent object oriented programming languages that have found extensive usage in application development. Use of a particular language depends on characteristics and requirements of an application, organizational impact of the choice, and reuse of the existing programs. C++ has now become the most successful, practical, general-purpose OOP language, and is widely used in industry today.

1.8 APPLICATIONS OF OOP OOP has become one of the programming buzzwords today. There appears to be a great deal of excitement and interest among software engineers in using OOP. Applications of OOP are beginning to gain importance in many areas. The most popular application of object-oriented programming, up to now, has been in the area of user interface design such as windows. Hundreds of windowing systems have been developed, using the OOP techniques. Real-business systems are often much more complex and contain many more objects with complicated attributes and methods. OOP is useful in these types of applications because it can simplify a complex problem. The promising areas for application of OOP include: • Real-time systems • Simulation and modeling • Object-oriented databases • Hypertext, hypermedia and expertext • AI and expert systems • Neural networks and parallel programming

16

Object Oriented Programming through C++

• Decision support and office automation systems • CIM/CAM/CAD systems The richness of OOP environment has enabled the software industry to improve not only the quality of software systems but also its productivity. Object-oriented technology is certainly changing the way the software engineers think, analyze, design and implement systems.

1.9 WHAT IS C++? C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories in Murray Hill, New Jersey, USA, in the early 1980’s. Stroustrup, an admirer of Simula67 and a strong supporter of C, wanted to combine the best of both the languages 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 was a major addition to the original C language, Stroustrup initially called the new language ‘C with classes’. However, later in 1983, 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. During the early 1990’s the language underwent a number of improvements and changes. In November 1997, the ANSI/ISO standards committee standardised these changes and added several new features 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++ programs. However, there are a few minor differences that will prevent a C program to 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 classes, inheritance, function overloading, and operator overloading. These features enable creation 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 C++ allow programmers to build large programs with clarity, extensibility and ease 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.

1.10 APPLICATIONS OF C++ C++ is a versatile language for handling very large programs. It is suitable for virtually any programming task including development of editors, compilers, databases, communication systems and any complex real-life application systems. • Since C++ allows us to create hierarchy-related objects, we can build special object-oriented 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 to the machine-level details.

Introduction

17

• C++ programs are easily maintainable and expandable. When a new feature needs to be implemented, it is very easy to add to the existing structure of an object. • It is expected that C++ will replace C as a general-purpose language in the near future.

1.11 A SIMPLE C++ PROGRAM Let us begin with a simple example of a C++ program that prints a string on the screen.

Program 1.1

Printing a String

#include

// include header file

using namespace std; int main() { cout code; while(code >= circle && code code; } cout x; sum = sum +x; } float average; // declaration average = sum/(i-1); cout