PROGRAMMING WITH ANSI C++ SECOND EDITION BHUSHAN TRIVEDI Directoz MCA Ptqyamme GLS Institute of Computer Technolom, Ahnzedabad OXFORD UNIVERSITY PRESS 3 Oxford University Press is a department of the University of Oxford. It furthers the University’s objective of excellence in research, scholarship, and education by publishing worldwide. Oxford is a registered trade mark of Oxford University Press in the UK and in certain other countries. Published in India by Oxford University Press YMCA Library Building, 1 Jai Singh Road, New Delhi 110001, India © Oxford University Press 2007, 2012 The moral rights of the author/s have been asserted. First Edition published in 2007 Second Edition published in 2012 All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, without the prior permission in writing of Oxford University Press, or as expressly permitted by law, by licence, or under terms agreed with the appropriate reprographics rights organization. Enquiries concerning reproduction outside the scope of the above should be sent to the Rights Department, Oxford University Press, at the address above. You must not circulate this work in any other form and you must impose this same condition on any acquirer. ISBN-13: 978-0-19-808396-2 ISBN-10: 0-19-808396-3 Typeset in Times New Roman by Cameo Corporate Services Limited, Chennai Printed in India by Sanat Printers, Kundli, Haryana Dedicated to my Teachers who enabled me to learn and write PPrreeffaaccee ttoo tthhee FFiirrsstt EEddiittiioonn C++ is a popular, versatile, and widely used programming language, which supports all features of C language and also provides a number of additional features that make it object-oriented. It includes concepts and features such as classes, objects, dynamic memory management, operator overloading, and many more. Besides learning the syntax, understanding the philosophical background helps the students appreciate the choices made by the creator of the language very easily. It is diffi cult to answer certain questions such as the following without really knowing the idea behind creating the language: Why is there no standard library for graphics in C++? Why is the base class embedded in the derived class rather than having a pointer to it? Why is there a need for virtual functions? Such questions can only be answered, if one understands the domain of application of C++ and Stroustrup’s idea behind creating the language. ABOUT THE BOOK Programming with ANSI C++ is designed as a textbook for students of engineering (BE/ BTech) and computer applications (BCA/MCA). It discusses the philosophical issues related to the language in order to make the concepts clearer to the users. The book assumes basic knowledge of the fundamental concepts of C and the art of programming. Those who have already studied C would fi nd this book to be an excellent starter. Wherever possible, comparison with C as well as Java is provided. The book demonstrates and highlights the difference of working in C++, problems with programming in C or Java, and better ways to do the same in C++. ANSI C and ANSI C++ have been used as the default language throughout the book. The worked examples and codes presented have been specifi cally designed to demonstrate the concept and syntax as also use in real-life applications. By no means is it claimed that the way to program shown here is the best or most effi cient. The variable naming convention is Java-like and care has been taken to use meaningful, though at times very long, variable names. To make the textbook ideal for classroom learning, several examples and program codes have been included. All of them have been test run with Visual C++.Net (VC++ 7.0) and most of them have also been tested on Linux. 8.0 (gnu C++ 3.2). Numerous review questions, exercises, and project ideas that require knowledge of advanced topics have also been included in every chapter. ACKNOWLEDGEMENTS Asheesh Asthana, one of my students sent me a book on C++ in 2002. My real journey of learning C++ actually began then. I have to thank Asheesh for his invaluable gift. While I was writing this book, I kept imagining the kind of queries my readers would pose. Fortunately my students whom I was teaching gave me excellent feedback and suggestions. Preface to the First Edition ix I am thankful to all of them. Hardik, Rahul, Hemal, Nimesh, and Shiv are a few names that I can remember at this moment. My wife Arpita, son Jay, and daughter Sonu all helped me in a way to complete this book. Without their support it would have been impossible. My colleagues, Harshal, Viral, and Hardik, supported me in every way they could. The editorial team at Oxford University Press has done a great job. The book took a far better shape in the fi nal version than it started with, and I would like to express my sincere thanks to the members of OUP for their interest and support, wealth of good ideas and suggestions, forceful requests and sweet reminders, without which this book would not have happened. Bhushan Trivedi PPrreeffaaccee ttoo tthhee SSeeccoonndd EEddiittiioonn Even in this age of advanced languages such as Java and DotNet, the age-old C++ is still revered for its versatility. These advanced languages as well as environments such as Windows and Linux would not be around without C++, because they are all written in C++! In fact, the TCP/IP code that a network card runs, the shell that an operating system such as Linux runs, and the graphics library that some of us use are all developed and maintained in C++. It continues to play a major role in coding various embedded systems. It is a vital cog in designing several reliable and high-performan ce components in various software products. The latest standard of ANSI C++ was released in August 2011; compilers conforming to this standard are expected to be released within a year. This is an important indication that the language is still going strong and in fact evolving, nearly four decades after its release! But why do we need programming languages in the fi rst place? You have probably read about it in the previous semesters—programming languages help us interact with computers. Effi cient as they are, computers can simplify tedious tasks and make them look ridiculously easy. They perform computations at a stunning pace and solve complex problems by applying equally complex algorithms. However, we cannot use the word intelligent to describe a computer, since every operation requires someone to instruct the computer, in concrete terms, about what it is supposed to do. How does one instruct a computer whose native language (machine codes) is so different from anything we speak? This is where the programs that we create break the language barrier, by providing sets of instructions that the computer can understand. The next question—why do we have so many languages then? This is because, in our attempt to provide instructions in an unambiguous manner and communicate better with the computer, we have gradually developed a range of programming languages. Where does C++ stand among the group of programming languages? In simple terms, C++ is an object-oriented as well as an object-based language that allows reusability of existing objects. It expresses every programming component as an object in a professionally written program, but it can work without objects as well. To conclude, C++ is still a professional programmers’ favourite when it comes to coding reliable tools. This brings us to the next question—what makes it so versatile? The following are a few reasons from what is almost an endless list: • C++ codes are compiled directly to a machine’s native code. In optimized conditions, it can produce executable codes at a breathtaking speed. • C++ is an open language and, therefore, it has a range of compilers suitable for different platforms. Its portability allows cross-platform independence. Codes written in one platform can be easily transported to other platforms. • C++ is reverse compatible with C; in fact, it is almost a superset. It can use existing C libraries with very few or no modifi cations. It is compatible with C to such an extent that a valid C program (barring very few special cases) is also a valid C++ program. • C++ lends superior control to the user, unlike most other high-level languages; but it expects the user to know what he/she is typing on the console. Fine control requires more disciplined programming and C++ is no exception. It is a strongly typed language. vi Programming with ANSI C++ NEW TO THE SECOND EDITION Continuing with the question–answer series, the moot question follows now—why a new edition? In this edition, the attempt has been to make suitable changes based on the useful feedback and comments received from users. Preserving all the basic ingredients that established the fi rst edition, the book now includes the following new features: • Each chapter contains pedagogical elements such as notes, sidebars, and exhibits spread across the chapters to highlight important statements and concepts. • Every program is followed by a complete analysis section, ‘How the Program Works’. These sections describe the logic behind the programs and the new concepts introduced therein. • End-chapter exercises now include multiple choice questions in addition to conceptual and practical exercises. • The book is now accompanied by a CD that contains the codes of all the programs as well as the case study. KEY FEATURES • Contains numerous application-oriented programs, complete with their source codes and test cases • Includes programs simulating real-life scenarios, to equip the readers to become entry- level professionals • Discusses advanced topics such as run-time type information (RTTI), casting operators, memberwise initialization list (MIL), reference variables, and templates in detail • Provides a balance between theory and practice, and covers both elementary as well as advanced topics EXTENDED CHAPTER MATERIAL • Chapter 1 now features the various concepts of object-oriented programming, besides providing an introduction to C++. • Chapter 4 provides extended coverage of temporary object creation and destruction. Small code segments have been added to strengthen the discussions on friend functions and how to return a reference. • Chapter 5 includes sections on memory leaks and the correct method to copy. Besides, the second edition covers destructors in more detail. • Chapter 9 provides a more in-depth analysis of abstract classes. • Chapter 10 includes an introduction to virtual destructors and object slicing. • In Chapter 11, the section on polymorphic objects has been strengthened with the help of a code segment and additional descriptions. • Chapter 13 contains updated information on operating systems and device drivers. The second edition throws light on fi le handles and fi le pointers. A table indicating the differences between binary and ASCII strings has been added. • Chapter 14 covers namespaces and dynamism in more depth. • Chapter 16 now provides a brief history of Standard Template Library (STL) before moving on to its application areas. The sections on functional and direct addressing models have been signifi cantly improved in the second edition. Additions in this chapter also include a table illustrating different types of iterators. Preface to the Second Edition vii • The case study sports a new look in the second edition. It describes the essential components of the program in an explicit manner. The output is appealing, with direct screenshots taken at the time of execution. It has a new section ‘Possible Extensions’, which describes how the same program can be extended further. CONTENT AND STRUCTURE Chapter 1 provides an introduction to C++ and explains the philosophical and technical differences between C and C++. Chapters 2 and 3 present an overview of core C++ and introduce data types, operators, classes, objects, structs, unions, arrays, pointers, and their extensive role in C++. Chapter 4 discusses the various kinds of functions and their usage. Chapter 5 deals with constructors and destructors, explaining their need, usage, and execution. Chapter 6 describes operator overloading along with user-defi ned conversions. It also discusses the use of either friends or member functions to overload operators, thereby emphasizing the difference between the approaches. Chapters 7 and 8 discuss the templates and exception handling mechanism in C++ in great detail. Chapter 9 covers inheritance in detail with all its forms. Chapter 10 explains the use of virtual functions to implement run-time polymorphism. Chapter 11 provides an introduction to RTTI, polymorphic objects, different casting operators, limitations of virtual functions, and how RTTI is used to overcome them. Chapter 12 discusses streams and formatted input/output (I/O), their need and advantages, as also differences between ios functions and manipulators for I/O formatting. Chapter 13 throws light on text and binary streams, usage of text and binary fi les, the various operations, as well as error handling in fi les. Chapter 14 introduces namespaces, illustrates their need, and explains concepts such as using directive and using declaration, extending namespaces, and namespace aliases. Chapter 15 discusses ANSI string objects and issues related to normal as well as substring operations. Chapter 16 provides an introduction to the Standard Template Library in C++. A comprehensive case study, included at the end of the book as an appendix, demonstrates the application of C++ in maintaining mark sheets of students and displaying them in the requisite format whenever required. ACKNOWLEDGEMENTS I gratefully acknowledge the feedback and suggestions given by various faculty members for the improvement of the book. I am obliged to the editorial team at Oxford University Press, India for bringing out the second edition in quick time and in a very elegant format. Any suggestions for improving the presentation and contents are welcome. Please send them to the publishers through their website www.oup.com or to the author at [email protected]. Bhushan Trivedi BBrriieeff CCoonntteennttss Preface to the Second Edition v Preface to the First Edition viii Features of the Book x 1. Object-oriented Programming and C++ 1 2. Overview of the C++ Language 39 3. Classes and Objects 69 4. Functions 109 5. Constructors and Destructors 175 6. Operator Overloading and User-defi ned Conversions 227 7. Templates 279 8. Exception Handling 328 9. Inheritance 362 10. Run-time Polymorphism by Virtual Functions 403 11. Run-time Type Information and Casting Operators 438 12. Streams and Formatted Input/Output 470 13. Using Files for Input /Output 497 14. Namespaces 525 15. String Objects 545 16. Standard Template Library 555 Appendix: Case Study 593 Index 617