Object Oriented Programming With C++ (Fifth Edition) PDF
Document Details
2011
E Balagurusamy
Tags
Related
Summary
Object Oriented Programming With C++ (Fifth Edition) is a textbook on object-oriented programming with C++. It covers fundamental concepts, C++ programming, and applications.
Full Transcript
OBJECT ORIENTED PROGRAMMING WITH C+ + Fifth Edition About 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,...
OBJECT ORIENTED PROGRAMMING WITH C+ + Fifth Edition About 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 PhD in Systems Engineering from the Indian Institute of Technology, Roorkee. His areas of interest include Object-Oriented Software Engineering, E-Governance, Technology Management, Business Process Re-engineering, and Total Quality Management. A prolific writer, he 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, 5e Programming in Java, 4e Programming in BASIC, 3e Programming in C#, 3e Numerical Methods Reliability Engineering A recipient of numerous honors and awards, E 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 WITH C++ Fifth Edition E Balagurusamy Chairman EBG Foundation Coimbatore Tata McGraw-Hill Published by Tata McGraw Hill Education Private Limited, 7 West Patel Nagar, New Delhi 110 008 Object Oriented Programming with C++, 5e Copyright © 2011, 2008, 2006, 2001, 1994, by Tata McGraw Hill Education Private Limited. No part of this publication may be reproduced or distributed in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise or stored in a database or retrieval system without the prior written permission of the publishers. The program listings (if any) may be entered, stored and executed in a computer system, but they may not be reproduced for publication. This edition can be exported from India only by the publishers, Tata McGraw Hill Education Private Limited. ISBN (13 digits): 978-0-07-107283-0 ISBN (10 digits): 0-07-107283-7 Vice President and Managing Director —McGraw-Hill Education, Asia Pacific Region: Ajay Shukla Head—Higher Education Publishing and Marketing: Vibha Mahajan Manager: Sponsoring—SEM & Tech Ed.: Shalini Jha Assoc. Sponsoring Editor: Suman Sen Development Editor: Surbhi Suman Copy Editor: Preyoshi Kundu Sr Production Manager: Satinder S Baveja Production Executive: Anuj Kr Shriwastava Dy Marketing Manager—SEM & Tech Ed.: Biju Ganesan Sr Product Specialist—SEM & Tech Ed.: John Mathews General Manager—Production: Rajender P Ghansela Asst General Manager—Production: B L Dogra Information contained in this work has been obtained by Tata McGraw-Hill, from sources believed to be reliable. However, neither Tata McGraw-Hill nor its authors guarantee the accuracy or completeness of any information published herein, and neither Tata McGraw-Hill nor its authors shall be responsible for any errors, omissions, or damages arising out of use of this information. This work is published with the understanding that Tata McGraw-Hill and its authors are supplying information but are not attempting to render engineering or other professional services. If such services are required, the assistance of an appropriate professional should be sought. Typeset at BeSpoke Integrated Solutions, Puducherry, India 605 008 and printed at Gopsons, A - 2 & 3, Sector - 64, Noida, U.P. - 201 301 Cover: Gopsons DALYYRZCRALLR Contents Preface 1. Principles of Object-Oriented Programming 1.1 Software Crisis 1.2 Software Evolution 1.3 A Look at Procedure-Oriented Programming 1.4 Object-Oriented Programming Paradigm 1.5 Basic Concepts of Object-Oriented Programming 1.6 Benefits of OOP 1.7 Object-Oriented Languages 1.8 Applications of OOP Summary Key Terms Review Questions 2. Beginning with C++ 2.1 What is C++? 2.2 Applications of C++ 2.3 A Simple C++ Program 2.4 More C++ Statements 2.5 An Example with Class 2.6 Structure of C++ Program 2.7 Creating the Source File 2.8 Compiling and Linking Summary Key Terms Review Questions Debugging Exercises Programming Exercises 3. Tokens, Expressions and Control Structures 3.1 Introduction 3.2 Tokens 3.3 Keywords 3.4 Identifiers and Constants 3.5 Basic Data Types 3.6 User-Defined Data Types 3.7 Storage Classes 3.8 Derived Data Types 3.9 Symbolic Constants 3.10 Type Compatibility 3.11 Declaration of Variables 3.12 Dynamic Initialization of Variables 3.13 Reference Variables 3.14 Operators in C++ 3.15 Scope Resolution Operator 3.16 Member Dereferencing Operators 3.17 Memory Management Operators 3.18 Manipulators 3.19 Type Cast Operator 3.20 Expressions and Their Types 3.21 Special Assignment Expressions 3.22 Implicit Conversions 3.23 Operator Overloading 3.24 Operator Precedence 3.25 Control Structures Summary Key Terms Review Questions Debugging Exercises Programming Exercises 4. Functions in C++ 4.1 Introduction 4.2 The Main Function 4.3 Function Prototyping 4.4 Call by Reference 4.5 Return by Reference 4.6 Inline Functions 4.7 Default Arguments 4.8 const Arguments 4.9 Recursion 4.10 Function Overloading 4.11 Friend and Virtual Functions 4.12 Math Library Functions Summary Key Terms Review Questions Debugging Exercises Programming Exercises 5. Classes and Objects 5.1 Introduction 5.2 C Structures Revisited 5.3 Specifying a Class 92 5.4 Defining Member Functions 5.5 A C++ Program with Class 5.6 Making an Outside Function Inline 5.7 Nesting of Member Functions 5.8 Private Member Functions 5.9 Arrays within a Class 5.10 Memory Allocation for Objects 5.11 Static Data Members 5.12 Static Member Functions 5.13 Arrays of Objects 5.14 Objects as Function Arguments 5.15 Friendly Functions 5.16 Returning Objects 5.17 const Member Functions 5.18 Pointers to Members 5.19 Local Classes Summary Key Terms Review Questions Debugging Exercises Programming Exercises 6. Constructors and Destructors 6.1 Introduction 6.2 Constructors 6.3 Parameterized Constructors 6.4 Multiple Constructors in a Class 6.5 Constructors with Default Arguments 6.6 Dynamic Initialization of Objects 6.7 Copy Constructor 6.8 Dynamic Constructors 6.9 Constructing Two-Dimensional Arrays 6.10 const Objects 6.11 Destructors Summary Key Terms Review Questions Debugging Exercises Programming Exercises 7. Operator Overloading and Type Conversions 7.1 Introduction 7.2 Defining Operator Overloading 7.3 Overloading Unary Operators 7.4 Overloading Binary Operators 7.5 Overloading Binary Operators Using Friends 7.6 Manipulation of Strings Using Operators 7.7 Some Other Operator Overloading Examples 7.8 Rules for Overloading Operators 7.9 Type Conversions Summary Key Terms Review Questions Debugging Exercises Programming Exercises 8. Inheritance: Extending Classes 8.1 Introduction 8.2 Defining Derived Classes 8.3 Single Inheritance 8.4 Making a Private Member Inheritable 8.5 Multilevel Inheritance 8.6 Multiple Inheritance 8.7 Hierarchical Inheritance 8.8 Hybrid Inheritance 8.9 Virtual Base Classes 8.10 Abstract Classes 8.11 Constructors in Derived Classes 8.12 Member Classes: Nesting of Classes Summary Key Terms Review Questions Debugging Exercises Programming Exercises 9. Pointers, Virtual Functions and Polymorphism 9.1 Introduction 9.2 Pointers 9.3 Pointers to Objects 9.4 this Pointer 9.5 Pointers to Derived Classes 9.6 Virtual Functions 9.7 Pure Virtual Functions 9.8 Virtual Constructors and Destructors Summary Key Terms Review Questions Debugging Exercises Programming Exercises 10. Managing Console I/O Operations 10.1 Introduction 10.2 C++ Streams 10.3 C++ Stream Classes 10.4 Unformatted I/O Operations 10.5 Formatted Console I/O Operations 10.6 Managing Output with Manipulators Summary Key Terms Review Questions Debugging Exercises Programming Exercises 11. Working with Files 11.1 Introduction 11.2 Classes for File Stream Operations 11.3 Opening and Closing a File 11.4 Detecting end-of-file 11.5 More about Open(): File Modes 11.6 File Pointers and their Manipulations 11.7 Sequential Input and Output Operations 11.8 Updating a File: Random Acess 11.9 Error Handling During File Operations 11.10 Command-line Arguments Summary Key Terms Review Questions Debugging Exercises Programming Exercises 12. Templates 12.1 Introduction 12.2 Class Templates 12.3 Class Templates with Multiple Parameters 12 4 Function Templates 12.5 Function Templates with Multiple Parameters 12.6 Overloading of Template Functions 12.7 Member Function Templates 12.8 Nontype Template Arguments Summary Key Terms Review Questions Debugging Exercises Programming Exercises 13. Exception Handling 13.1 Introduction 13.2 Basics of Exception Handling 13.3 Exception Handling Mechanism 13.4 Throwing Mechanism 13.5 Catching Mechanism 13.6 Rethrowing an Exception 13.7 Specifying Exceptions 13.8 Exceptions in Constructors and Destructors 13.9 Exceptions in Operator Overloaded Functions Summary Key Terms Review Questions Debugging Exercises Programming Exercises 14. Introduction to the Standard Template Library 14.1 Introduction 14.2 Components of STL 14.3 Containers 14.4 Algorithms 14.5 Iterators 14.6 Application of Container Classes 14.7 Function Objects Summary Key Terms Review Questions Debugging Exercises Programming Exercises 15. Manipulating Strings 15.1 Introduction 15.2 Creating (string) Objects 15.3 Manipulating String Objects 15.4 Relational Operations 15.5 String Characteristics 15.6 Accessing Characters in Strings 15.7 Comparing and Swapping Summary Key Terms Review Questions Debugging Exercises Programming Exercises 16. New Features of ANSI C++ Standard 16.1 Introduction 16.2 New Data Types 16.3 New Operators 16.4 Class Implementation 16.5 Namespace Scope 16.6 Operator Keywords 16.7 New Keywords 16.8 New Headers Summary Key Terms Review Questions Debugging Exercises Programming Exercises 17. Object-Oriented Systems Development 17.1 Introduction 17.2 Procedure-Oriented Paradigms 17.3 Procedure-Oriented Development Tools 17.4 Object-Oriented Paradigm 17.5 Object-Oriented Notations and Graphs 17.6 Steps in Object-Oriented Analysis 11.7 Steps in Object-Oriented Design 11.8 Implementation 17.9 Prototyping Paradigm 17.10 Wrapping Up Summary Key Terms Review Questions 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 Bibliography Index 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 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. Besides this, topical inclusions and strengthening of the existing topics along with pedagogical enhancement have been carried out in this edition, based on readers’ suggestions. Corrections to topographical errors and certain inaccuracies in the text have also been incorporated. This book is for the programmers who wish to know all about 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 reader is 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 briefly the important elements of object- oriented analysis and design of systems. New to the Edition Topical inclusions—Recursion, Preprocessor, Virtual Constructors and Destructors, Exceptions in Constructors and Destructors, Exceptions in Operator Overloaded Functions Topical elaborations—Dynamic Memory Management, Overloading, Structure and Union, Storage Classes, Abstract classes, Type casting and RTTI Addition of two new projects— Telephone Billing System (Major) and Typing Tutor (Minor) to provide hands-on approach Includes answers for debugging exercises Provides an updated and refreshed C++ Proficiency Test along with answers based on technical interview question pattern Revived and enriched pedagogy includes 115 Programs 218 Review Questions 67 Debugging Exercises 90 Programming Exercises Key Features of the Book Chapter Organization The book is organized into 17 chapters and 9 appendices. Chapters 1 and 2 provide a strong foundation and a perspective on Object- Oriented Programming and C++. Chapter 3 deals with the various data types and control structures. This chapter now includes differences between Structure and Union, explained with appropriate programs and introduction of Storage Classes and its various types. Chapter 4 elucidates the various functions of C++. A separate section discussing the Recursion function has been added in this chapter. Chapter 5 covers Classes and Objects, while Chapter 6 gives a detailed study on Constructors and Destructors, the various kinds of Constructors, including topics like Parameterized Constructors, Constructor Overloading and the various exceptional cases to be noted when working with Destructors. The chapter also deals with the Dynamic Initialization of Objects. Chapter 7 covers in detail the concept of Operator overloading and Type conversions, apart from discussing Overloading rules and String manipulations. The topic on Exceptions in Operator Overloading Operations has been added and explained with sufficient programs to support the theory. The various types of Inheritance like single, multiple, and hybrid inheritance and its other topics like Derived and Abstract classes can be studied in Chapter 8. Chapter 9 begins by explaining the vital feature of OOP, i.e., Polymorphism, and elucidating on Pointers and Virtual Functions, while the Input and Output Operations have been dealt with in Chapter 10. An in-depth study of the various File Stream Operations and File Pointers has been elucidated in Chapter 11. Templates and Exception handling, like Exceptions in Constructors and Destructors and Exceptions in Operator Overloading Functions can be studied in Chapters 12 and 13, respectively. Chapter 14 introduces the students to the standard template, its components and functions. Chapter 15 covers the study of Strings and its related fields while Chapter 16 deals with the new features of ANSI C++ standards. The concluding chapter, Chapter 17, helps students in understanding the object-oriented systems. Each chapter ends with a set of summary, key terms, review questions, debugging exercises and programming problems. For further assistance, students can also refer to the website for solutions to questions containing the icon. In addition, two new projects - Telephone Billing System (Major) and Typing Tutor (Minor) have been included in the present edition. Executing Turbo C++, Executing C++ under Windows, Glossary of ANSI C++ Keywords, C++ Operator Precedence, Points to Remember, Glossary of Important C++ and OOP Terms, and C++ Proficiency Test have been provided in the appendices, helping students understand and implement the concepts in a better way and prove to be valuable source and tool in their study. Web Supplement The book is accompanied with an enhanced and exhaustive web supplement which includes the following additional information for both instructors and students at http://www.mhhe.com/balagurusamy/oop5 Solutions for selected Programming Exercises from the book Solutions to the Debugging Exercises Complete code with step-by-step description and user manual for the Payroll management and Hospital management systems projects along with projects from the 4th edition and newly added projects in executable format (Telephone Billing System and Typing Tutor) Differences between C and C++ Implementation of Data Structures concepts using C++ Codes for deleted programs of the 4th edition Practice tests including questions from C++ proficiency tests in 4th edition Acknowledgements Since the release of the first edition of this book a decade ago, lakhs of teachers and students and professional programmers have been using this book. Their overwhelming support encouraged me to bring out the Fourth Edition in 2008 and now the Fifth Edition. The author would like to thank the following reviewers for their valuable suggestions and comments: Amit Jain Bharat Institute of Technology, Meerut, Uttar Pradesh Nitin Gupta National Institute of Technology, Hamirpur, Himachal Pradesh Preetvanti Singh Dayalbagh Educational Institute, Agra, Uttar Pradesh Prabhat Verma Harcourt Butler Technological Institute, Kanpur, Uttar Pradesh Manish Varshney Sri Siddhi Vinayak Institute of Technology, Bareilly, Uttar Pradesh Harmeet Institute of Information Technology and Malhotra Management, New Delhi S R Biradar Mody Institute of Technology and Science, Rajasthan Barnali Goswami Narula Institute of Technology, Kolkata, West Bengal Kishore Kumar Birla Institute of Technology, Mesra, Ranchi, Senapati Jharkhand Samaresh Kalinga Institute of Industrial Technology, Mishra Bhubaneshwar, Orissa Poornachandra ABCOM Information Systems Pvt Ltd, Mumbai, Sarang Maharashtra Manisha J Indira Institute of Management, Pune, Somavanshi Maharashtra V B Gadekar Vishwakarma Institute of Technology, Pune, Maharashtra Kavita Mahesh K J Somaiya College of Engineering, Mumbai, Kelkar Maharashtra N Shanthi K S Rengasamy College of Technology, Tiruchengode, Tamil Nadu Balamurugan Vellore Institute of Technology, Vellore, Tamil Balusamy Nadu Leena Thomas Mar Athanasius College of Engineering, Kothamangalam, Kerala A Sakthivel Aditya Institute of Technology, Coimbatore, Tamil Nadu A C Kaladevi Sona College of Technology, Salem, Tamil Nadu S Suresh Babu Thiruvalluvar Government Arts College, Rasipuram, Tamil Nadu CH V K N S N DRK Institute of Science and Technology, Moorthy Hyderabad, Andhra Pradesh S Murali PES College of Engineering, Mandya, Karnataka K Chandra National Institute of Technology, Surathkal, Sekaran Karnataka Annapurna P MSR Institute of Technology, Bengaluru, Patil Karnataka My sincere thanks are due to the editorial and publishing professionals of Tata McGraw-Hill for their keen interest and support in bringing out this edition in its present form. E Balagurusamy Feedback 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. Principles of Object- Oriented Programming 1 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 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. 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 Fig. 1.1 The state of US defence projects (according to the US government) 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. 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 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. 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-to- maintain, 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 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. 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. Fig. 1.5 Relationship of data and functions in procedural programming 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. 1.4Object-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. Fig. 1.6 Organization of data and functions in OOP 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 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. 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). 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. 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 behaviours in different instances. The behaviour 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 behaviours in different instances is known as operator overloading. 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. 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 behaviour, 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. 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: 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 imple-mentable 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. 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 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 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. Summary Software technology has evolved through a series of phases during the last five decades. The most popular phase till recently was procedure-oriented programming (POP). POP employs top-down programming approach where a problem is viewed as a sequence of tasks to be performed. A number of functions are written to implement these tasks. POP has two major drawbacks, viz. (1) data move freely around the program and are therefore vulnerable to changes caused by any function in the program, and (2) it does not model very well the real-world problems. Object-oriented programming (OOP) was invented to overcome the drawbacks of the POP. It employs the bottom- up programming approach. It 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 in a data structure called class. This feature is called data encapsulation. In OOP, a problem is considered as a collection of a number of entities called objects. Objects are instances of classes. Insulation of data from direct access by the program is called data hiding. Data abstraction refers to putting together essential features without including background details. Inheritance is the process by which objects of one class acquire properties of objects of another class. Polymorphism means one name, multiple forms. It allows us to have more than one function with the same name in a program. It also allows overloading of operators so that an operation can exhibit different behaviours in different instances. Dynamic binding means that the code associated with a given procedure is not known until the time of the call at run-time. Message passing involves specifying the name of the object, the name of the function (message) and the information to be sent. Object-oriented technology offers several benefits over the conventional programming methods—the most important one being the reusability. Applications of OOP technology has gained importance in almost all areas of computing including real-time business systems. There are a number of languages that support object-oriented programming paradigm. Popular among them are C++, Smalltalk and Java. C++ has become an industry standard language today. Key Terms Ada | assembly language | bottom-up programming | C++ | classes | concurrency | data abstraction | data encapsulation | data hiding | data members | dynamic binding | early binding | Eiffel | flowcharts | function overloading | functions | garbage collection | global data | hierarchical classification | inheritance | Java | late binding | local data | machine language | member functions | message passing | methods | modular programming | multiple inheritance | object libraries | Object Pascal | object-based programming | Objective C | object-oriented languages | object-oriented programming | objects | operator overloading | persistence | polymorphism | procedure-oriented programming | reusability | Simula | Smalltalk | structured programming | top-down programming | Turbo Pascal Review Questions 1.1 What do you think are the major issues facing the software industry today? 1.2 Briefly discuss the software evolution during the period 1950 - 1990. 1.3 What is procedure-oriented programming? What are its main characteristics? 1.4 Discuss an approach to the development of procedure-oriented programs. 1.5 Describe how data are shared by functions in a procedure- oriented program. 1.6 What is object-oriented programming? How is it different from the procedure-oriented programming? 1.7 How are data and functions organized in an object-oriented program? 1.8 What are the unique advantages of an object-oriented programming paradigm? 1.9 Distinguish between the following terms: (a) Objects and classes (b) Data abstraction and data encapsulation (c) Inheritance and polymorphism (d) Dynamic binding and message passing 1.10 What 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 is it useful in OOP? 1.13 How does object-oriented approach differ from object-based approach? 1.14 List a few areas of application of OOP technology. 1.15 State whether the following statements are TRUE or FALSE. (a) In procedure-oriented programming, all data are shared by all functions. (b) The main emphasis of procedure-oriented programming is on algorithms rather than on data. (c) One of the striking features of object-oriented programming is the division of programs into objects that represent real-world entities. (d) Wrapping up of data of different types into a single unit is known as encapsulation. (e) One problem with OOP is that once a class is created it can never be changed. (f) Inheritance means the ability to reuse the data values of one object by another object. (g) Polymorphism is extensively used in implementing inheritance. (h) Object-oriented programs are executed much faster than conventional programs. (i) Object-oriented systems can scale up better from small to large. (j) Object-oriented approach cannot be used to create databases. Beginning with C++ 2 Key Concepts 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 2.1 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. 2.2 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. 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. 2.3 A Simple C++ Program Let us begin with a simple example of a C++ program that prints a string on the screen. Program 2.1 Printing A String #include // include header file using namespace std; int main() { cout operator: Program 7.6 Overloading of Pointer-to-member Operator #include #include using namespace std; class test { public: int num; test(int j) { num=j; } test* operator ->(void) { return this; } }; int main() { test T(5); test *Ptr = &T; cout