100% found this document useful (2 votes)
19 views

Programming in C 2nd Edition Safari instant download

The document provides links to various programming eBooks, including titles on C, C++, and Java, available for instant download in multiple formats. It includes detailed contents and chapters for the book 'Programming in C++ Second Edition' by Ashok Namdev Kamthane, covering fundamental concepts and advanced topics in C++. The document also contains copyright information and publisher details.

Uploaded by

chipskoffab3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
19 views

Programming in C 2nd Edition Safari instant download

The document provides links to various programming eBooks, including titles on C, C++, and Java, available for instant download in multiple formats. It includes detailed contents and chapters for the book 'Programming in C++ Second Edition' by Ashok Namdev Kamthane, covering fundamental concepts and advanced topics in C++. The document also contains copyright information and publisher details.

Uploaded by

chipskoffab3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Programming in C 2nd Edition Safari download

https://ebookgate.com/product/programming-in-c-2nd-edition-
safari/

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats

Programming with ANSI C 2nd ed Edition Trivedi

https://ebookgate.com/product/programming-with-ansi-c-2nd-ed-
edition-trivedi/

C for business programming 2nd ed Edition Molluzzo

https://ebookgate.com/product/c-for-business-programming-2nd-ed-
edition-molluzzo/

Programming Principles and Practices using C 2nd


Edition Bjarne Stroustrup

https://ebookgate.com/product/programming-principles-and-
practices-using-c-2nd-edition-bjarne-stroustrup/

Programming in Objective C 4th Edition Stephen Kochan

https://ebookgate.com/product/programming-in-objective-c-4th-
edition-stephen-kochan/
Programming in ANSI C 6th Edition E. Balagurusamy

https://ebookgate.com/product/programming-in-ansi-c-6th-edition-
e-balagurusamy/

Programming in Scala 2nd 2nd Edition Martin Odersky

https://ebookgate.com/product/programming-in-scala-2nd-2nd-
edition-martin-odersky/

Mobile Computing 1st edition Edition Safari

https://ebookgate.com/product/mobile-computing-1st-edition-
edition-safari/

Separation Process Engineering Second Edition Safari

https://ebookgate.com/product/separation-process-engineering-
second-edition-safari/

Programming in Java 2nd edition Edition Choudhary

https://ebookgate.com/product/programming-in-java-2nd-edition-
edition-choudhary/
Programming in C++

Second Edition

Ashok Namdev Kamthane


Associate Professor
Department of Electronics and Telecommunication Engineering
Shri Guru Gobind Singhji
Institute of Engineering and Technology
Nanded, Maharashtra
Copyright © 2013 Dorling Kindersley (India) Pvt. Ltd.
Licensees of Pearson Education in South Asia

No part of this eBook may be used or reproduced in any manner whatsoever without the publisher’s
prior written consent.

This eBook may or may not include all assets that were part of the print version. The publisher
reserves the right to remove any material in this eBook at any time.

ISBN 9788131791448
eISBN 9789332520288

Head Office: A-8(A), Sector 62, Knowledge Boulevard, 7th Floor, NOIDA 201 309, India
Registered Office: 11 Local Shopping Centre, Panchsheel Park, New Delhi 110 017, India
Brief Contents

PrEfAcE xv
About thE Author xvii

1. iNtroductioN to c++ 1

2. bASicS of c++ 21

3. iNPut ANd outPut iN c++ 33

4. c++ dEclArAtioNS 99

5. dEciSioN StAtEmENtS 161

6. coNtrol looP StructurES 187

7. fuNctioNS iN c++ 203

8. clASSES ANd objEctS 257

9. coNStructorS ANd dEStructorS 345

10. oPErAtor ovErloAdiNg ANd tyPE coNvErSioN 395

11. iNhEritANcE 441

12. ArrAyS 511


iv Brief Contents

13. PoiNtErS 531

14. c++ ANd mEmory modElS 577

15. biNdiNg, PolymorPhiSmS, ANd virtuAl fuNctioNS 603

16. APPlicAtioNS with filES 639

17. gENEric ProgrAmmiNg with tEmPlAtES 697

18. worKiNg with StriNgS 731

19. ExcEPtioN hANdliNg 759

20. ovErviEw of StANdArd tEmPlAtE librAry 785

21. AdditioNAl iNformAtioN About ANSi ANd turbo-c++ 817

22. c++ grAPhicS 843

APPENdicES 869

iNdEx 879
Contents

Preface xv
About the Author xvii

1. iNtroductioN to c++ 1
1.1 Differences between C and C++ 1
1.2 Evolution of C++ 2
1.3 The ANSI Standard 2
1.4 The Object Oriented Technology 2
1.5 Disadvantage of Conventional Programming 4
1.6 Programming Paradigms 5
1.7 Preface to Object Oriented Programming 6
1.8 Key Concepts of Object Oriented Programming 7
1.9 Advantages of OOP 15
1.10 Object Oriented Languages 16
1.11 Usage of OOP 17
1.12 Usage of C++ 18
Summary 18
Exercises 19

2. bASicS of c++ 21
2.1 Introduction 21
2.2 Steps to Create and Execute a C++ Program 21
2.3 Flowchart for Creating a Source File, Compiling, Linking
and Executing in C++ 22
2.4 C++ Environments 23
2.5 Typical C++ Environment (Borland C++) 24
2.6 Structure of a C++ Program 27
2.7 Illustrative Simple Program in C++ without Class 28
2.8 Header Files and Libraries 29
Summary 30
Exercises 31
vi Contents

3. iNPut ANd outPut iN c++ 33


3.1 Introduction 33
3.2 Streams in C++ and Stream Classes 34
3.3 Pre-defined Streams 34
3.4 Buffering 35
3.5 Stream Classes 36
3.6 Formatted and Unformatted Data 37
3.7 Unformatted Console I/O Operations 38
3.8 Type Casting with the cout Statement 44
3.9 Member Functions of the istream Class 56
3.10 Formatted Console I/O Operations 59
3.11 Bit Fields 67
3.12 Flags without Bit Fields 70
3.13 Manipulators 71
3.14 User-defined Manipulators 74
3.15 Manipulator with One Parameter 76
3.16 Manipulators with Multiple Parameters 77
3.17 More Programs 79
Summary 87
Exercises 88

4. c++ dEclArAtioNS 99
4.1 Introduction 99
4.2 Tokens 100
4.3 Variable Declaration and Initialization 108
4.4 Data Types in C++ 115
4.5 Operators in C and C++ 129
4.6 Scope Access Operator 133
4.7 Namespace 133
4.8 Memory Management Operators 137
4.9 Comments 141
4.10 Comma Operator 142
4.11 Comma in Place of Curly Braces 143
4.12 More Programs 145
Summary 155
Exercises 156

5. dEciSioN StAtEmENtS 161


5.1 Introduction 161
5.2 The if Statement 162
5.3 Multiple ifs 165
5.4 The if-else Statement 167
5.5 Nested if-else Statements 169
5.6 The else-if Ladder 171
5.7 Unconditional Control Transfer Statements 175
Contents vii

5.8 The switch Statement 177


5.9 Nested switch case 182
Summary 183
Exercises 184

6. coNtrol looP StructurES 187


6.1 Introduction 187
6.2 What Is a Loop? 187
6.3 The for Loop 188
6.4 Nested for Loops 191
6.5 The while Loop 192
6.6 The do-while Loop 195
6.7 The do-while Statement with while Loop 196
6.8 More Programs 197
Summary 199
Exercises 199

7. fuNctioNS iN c++ 203


7.1 Introduction 203
7.2 Parts of a Function 205
7.3 Passing Arguments 209
7.4 Lvalues and Rvalues 215
7.5 Return by Reference 216
7.6 Returning More Values by Reference 217
7.7 Default Arguments 218
7.8 const Arguments 222
7.9 Inputting Default Arguments 224
7.10 Inline Functions 225
7.11 Function Overloading 228
7.12 Principles of Function Overloading 230
7.13 Precautions with Function Overloading 234
7.14 Recursion 235
7.15 Library Functions 237
7.16 More Programs 241
Summary 252
Exercises 252

8. clASSES ANd objEctS 257


8.1 Introduction 258
8.2 Structure in C 259
8.3 Structure in C++ 261
8.4 Classes in C++ 262
8.5 Declaring Objects 263
8.6 The public Keyword 264
viii Contents

8.7 The private Keyword 265


8.8 The protected Keyword 266
8.9 Access Specifiers and Their Scope 267
8.10 Defining Member Functions 268
8.11 Characteristics of Member Functions 272
8.12 Outside Member Function as Inline 272
8.13 Rules for Inline Functions 274
8.14 Data Hiding or Encapsulation 274
8.15 Classes, Objects, and Memory 277
8.16 static Member Variables 280
8.17 static Member Functions 286
8.18 static Object 289
8.19 Array of Objects 290
8.20 Objects as Function Arguments 292
8.21 friend Functions 295
8.22 The const Member Functions 304
8.23 The Volatile Member Function 305
8.24 Recursive Member Function 306
8.25 Local Classes 307
8.26 empty, static, and const Classes 310
8.27 Member Function and Non-member Function 310
8.28 The main() Function as a Member Function 311
8.29 Overloading Member Functions 312
8.30 Overloading main() Functions 313
8.31 The main(), Member Function, and Indirect Recursion 314
8.32 Bit Fields and Classes 317
8.33 Nested Class 319
8.34 More Programs 320
Summary 339
Exercises 340

9. coNStructorS ANd dEStructorS 345


9.1 Introduction 346
9.2 Constructors and Destructors 348
9.3 Characteristics of Constructors and Destructors 349
9.4 Applications with Constructors 350
9.5 Constructors with Arguments (Parameterized Constructor) 353
9.6 Overloading Constructors (Multiple Constructors) 355
9.7 Array of Objects Using Constructors 359
9.8 Constructors with Default Arguments 360
9.9 Copy Constructors 361
9.10 The const Objects 363
9.11 Destructors 364
9.12 Calling Constructors and Destructors 367
9.13 Qualifier and Nested Classes 370
Contents ix

9.14 Anonymous Objects 372


9.15 Private Constructors and Destructors 374
9.16 Dynamic Initialization Using Constructors 375
9.17 Dynamic Operators and Constructors 377
9.18 main() as a Constructor and Destructor 379
9.19 Recursive Constructors 380
9.20 Program Execution Before main() 381
9.21 Constructor and Destructor with Static Members 383
9.22 Local Versus Global Object 384
9.23 More Programs 385
Summary 392
Exercises 392

10. oPErAtor ovErloAdiNg ANd tyPE coNvErSioN 395


10.1 Introduction 395
10.2 The Keyword Operator 398
10.3 Overloading Unary Operators 400
10.4 Operator Return Type 403
10.5 Constraint on Increment and Decrement Operators 404
10.6 Overloading Binary Operators 405
10.7 Overloading with friend Function 409
10.8 Overloading Assignment Operator (=) 412
10.9 Type Conversion 414
10.10 Rules for Overloading Operators 422
10.11 One-Argument Constructor and Operator Function 424
10.12 Overloading Stream Operators 425
10.13 More Programs 427
Summary 438
Exercises 439

11. iNhEritANcE 441


11.1 Introduction 442
11.2 Reusability 442
11.3 Access Specifiers and Simple Inheritance 442
11.4 Protected Data with Private Inheritance 449
11.5 Types of Inheritance 454
11.6 Single Inheritance 456
11.7 Multilevel Inheritance 457
11.8 Multiple Inheritance 459
11.9 Hierarchical Inheritance 460
11.10 Hybrid Inheritance 462
11.11 Multipath Inheritance 465
11.12 Virtual Base Classes 466
11.13 Constructors, Destructors, and Inheritance 468
11.14 Object as a Class Member 483
11.15 Abstract Classes 489
x Contents

11.16 Qualifier Classes and Inheritance 489


11.17 Constructors in Derived Class 490
11.18 Pointers and Inheritance 491
11.19 Overloading Member Function 492
11.20 Advantages of Inheritance 494
11.21 Disadvantages of Inheritance 494
11.22 More Programs 494
Summary 505
Exercises 506

12. ArrAyS 511


12.1 Introduction 511
12.2 One-dimensional Array Declaration and Initialization 511
12.3 Characteristics of Arrays 512
12.4 Accessing Array Elements Through Pointers 515
12.5 Arrays of Pointers 516
12.6 Passing Array Elements to a Function 517
12.7 Passing Complete Array Elements to a Function 518
12.8 Initialization of Arrays Using Functions 519
12.9 Two-dimensional Arrays 520
12.10 Pointers and Two-dimensional Arrays 523
12.11 Three- or Multi-dimensional Arrays 524
12.12 Arrays of Classes 525
Summary 528
Exercises 529

13. PoiNtErS 531


13.1 Introduction 531
13.2 Features of Pointers 532
13.3 Pointer Declaration 533
13.4 Arithmetic Operations with Pointers 536
13.5 Pointer to Pointer 538
13.6 void Pointers 539
13.7 wild Pointers 540
13.8 Pointer to Class 542
13.9 Pointer to Object 544
13.10 The this Pointer 546
13.11 Pointer to Derived Classes and Base Class 550
13.12 Pointer to Members 554
13.13 Accessing Private Members with Pointers 561
13.14 Direct Access to Private Members 562
13.15 Addresses of Objects and void Pointers 564
13.16 More Programs 565
Summary 573
Exercises 573
Contents xi

14. c++ ANd mEmory modElS 577


14.1 Introduction 577
14.2 Memory Models 577
14.3 Dynamic Memory Allocation 581
14.4 The new and delete Operators 582
14.5 Heap Consumption 586
14.6 Overloading new and delete Operators 588
14.7 Overloading new and delete in Classes 592
14.8 Execution Sequence of Constructor and Destructor 595
14.9 Specifying Address of an Object 597
14.10 Dynamic Objects 598
14.11 Calling Convention 599
Summary 600
Exercises 601

15. biNdiNg, PolymorPhiSmS, ANd virtuAl fuNctioNS 603


15.1 Introduction 603
15.2 Binding in C++ 604
15.3 Pointer to Base and Derived Class Objects 609
15.4 Virtual Functions 612
15.5 Rules for Virtual Functions 613
15.6 Array of Pointers 615
15.7 Pure Virtual Functions 618
15.8 Abstract Classes 619
15.9 Working of Virtual Functions 621
15.10 Virtual Functions in Derived Classes 627
15.11 Object Slicing 629
15.12 Constructors and Virtual Functions 631
15.13 Virtual Destructors 632
15.14 Destructors and Virtual Functions 634
Summary 635
Exercises 635

16. APPlicAtioNS with filES 639


16.1 Introduction 639
16.2 File Stream Classes 641
16.3 Steps of File Operations 643
16.4 Checking for Errors 650
16.5 Finding End of a File 653
16.6 File Opening Modes 655
16.7 File Pointers and Manipulators 657
16.8 Manipulators with Arguments 661
16.9 Sequential Access Files 664
16.10 Binary and ASCII Files 666
xii Contents

16.11 Random Access Operation 670


16.12 Error Handling Functions 674
16.13 Command-Line Arguments 679
16.14 Strstreams 680
16.15 Sending Output to Devices 682
16.16 More Programs 684
Summary 691
Exercises 692

17. gENEric ProgrAmmiNg with tEmPlAtES 697


17.1 Introduction 698
17.2 Need for Templates 698
17.3 Definition of Class Templates 698
17.4 Normal Function Templates 701
17.5 Working of Function Templates 704
17.6 Class Templates with More Parameters 704
17.7 Function Templates with More Arguments 705
17.8 Overloading of Template Functions 708
17.9 Member Function Templates 709
17.10 Recursion with Template Functions 710
17.11 Class Templates with Overloaded Operators 711
17.12 Class Templates Revisited 713
17.13 Class Templates and Inheritance 715
17.14 Bubble Sort Using Function Templates 717
17.15 Guidelines for Templates 718
17.16 Differences Between Templates and Macros 719
17.17 Linked Lists with Templates 720
17.18 More Programs 722
Summary 727
Exercises 728

18. worKiNg with StriNgS 731


18.1 Introduction 731
18.2 Moving From C String to C++ String 734
18.3 Declaring and Initializing String Objects 735
18.4 Relational Operators 738
18.5 Handling String Objects 740
18.6 String Attributes 743
18.7 Accessing Elements of Strings 747
18.8 Comparing and Exchanging 750
18.9 Miscellaneous Functions 752
18.10 More Programs 754
Summary 757
Exercises 757
Contents xiii

19. ExcEPtioN hANdliNg 759


19.1 Introduction 759
19.2 Principles of Exception Handling 760
19.3 The Keywords try, throw, and catch 760
19.4 Guidelines for Exception Handling 761
19.5 Multiple catch Statements 765
19.6 Catching Multiple Exceptions 767
19.7 Re-throwing Exception 768
19.8 Specifying Exceptions 769
19.9 Exceptions in Constructors and Destructors 771
19.10 Controlling Uncaught Exceptions 773
19.11 Exceptions and Operator Overloading 774
19.12 Exceptions and Inheritance 776
19.13 Class Templates with Exception Handling 777
19.14 Guidelines for Exception Handling 778
19.15 More Programs 779
Summary 781
Exercises 782

20. ovErviEw of StANdArd tEmPlAtE librAry 785


20.1 Introduction to STL 785
20.2 STL Programing Model 786
20.3 Containers 786
20.4 Sequence Containers 787
20.5 Associative Containers 789
20.6 Algorithms 789
20.7 Iterators 794
20.8 Vectors 795
20.9 Lists 801
20.10 Maps 808
20.11 Function Objects 811
Summary 814
Exercises 815

21. AdditioNAl iNformAtioN About ANSi ANd turbo-c++ 817


21.1 Introduction 817
21.2 Innovative Data Types 818
21.3 New Type-casting Operators 821
21.4 The Keyword explicit 826
21.5 The Keyword mutable 827
21.6 Namespace Scope 828
21.7 Nested Namespaces 829
21.8 Anonymous Namespaces 830
21.9 The Keyword using 830
xiv Contents

21.10 Namespace Alias 835


21.11 The Standard Namespace std 835
21.12 ANSI and Turbo-C++ Keywords 836
21.13 ANSI and Turbo-C++ Header Files 839
21.14 C++ Operator Keywords 840
Summary 840
Exercises 841

22. c++ grAPhicS 843


22.1 Introduction 843
22.2 Computer Display Modes 844
22.3 Video Display and Display Adapters 844
22.4 Initilisation of Graphics 844
22.5 Few Additional Graphics Functions 846
22.6 Programs Using Library Functions 848
22.7 Working with Texts 856
22.8 Filling Patterns with Different Colors and Styles 858
22.9 Mouse Programming 862
22.10 Drawing Noncommon Figures 866
Summary 867
Exercises 867

Appendices 869

Index 879
Preface

Programming in C++ is meant for students pursuing various disciplines such as engineer-
ing, science, computer application, and diploma courses. Students who are learning object-
oriented programming (OOP) can also refer to this book. It covers the subject of C++ as per
the syllabi prescribed by various branches of Indian universities, state board of technical
educations, and the Department of Electronics and Accreditation of Computer Courses. Hence,
this book can be adopted in engineering, degree as well as other courses that deal with this sub-
ject. Written for beginners and for those who have some knowledge of C, the book will be espe-
cially useful for students who are learning object-oriented programming.
Designed to bridge the gap between theory and practice, the chapters have been presented
using a systematic and lucid approach. Each topic is explained in an easy-to-understand manner
with ample worked-out examples and programs. The book abounds with about 700 solved
programs and as many as 300 exercises for the student’s benefit. The programmer can run the
solved programs, see the output and appreciate the concepts of C++.
The programs have been fully tested and executed with Borland’s Turbo C++ compiler
version 3.00 and Visual C++ 6.0 compiler. The programs in Chapter 22 have been tested and
compiled with Java Compiler version 2.
This second edition has been thoroughly revised based on comments and responses received
for the previous edition. All programming examples have been tested, compiled and executed.
While utmost care has been taken at the time of writing this book, it is possible that errors and
omissions may have inadvertently crept in. Such incongruities, if any, may please be pointed
out. Suggestions and feedback are most welcome and may be directed to my e-mail address:
ankamthane@gmail.com.

AcKNowlEdgEmENtS
I express my gratitude to the Minister for Technical and Medical Education of Maharashtra State,
Honorable Shri D. P. Sawant, who complimented and felicitated me for writing technical books,
while he was invited to our institute recently in the month of May 2013. He also encouraged me
to write more books.
I am grateful to Prof. B. M. Naik, Former Principal of S.G.G.S. Institute of Engineering and
Technology, Nanded, who has always acted as a source of encouragement. His dynamism and
leadership led me to write this book and I will never forget his support and words of wisdom.
xvi Preface

Special thanks are due to the members of the board of governors of S.G.G.S. Institute of
Engineering and Technology, who motivated me to write this book. I thank eminent industrialist
Shri B. N. Kalyani, head of the Kalyani Group of Companies, for inspiring and complimenting
me for authoring technical books. I am also obliged to Dr L. M. Waghmare, Director of our
institute, for supporting and appreciating me while writing this book.
I am indebted to all my colleagues, friends and students who helped me at the time of
preparing the manuscript for this book. I acknowledge the support rendered by Dr S. V. Bonde,
Dr P. D. Jadhav, Dr P. Pramanik, Dr P. S. Charpe, Dr B. M. Dabde, Dr Y. V. Joshi, Dr U. V. Kulkarni,
Dr S. P. Kallurkar, Dr V. M. Nandedkar, Dr A. U. Digraskar, Dr R. S. Holambe, Dr B. M. Patre,
Prof. R. K. Chavan, Dr J. V. L. Venkatesh, Prof. P. S. Nalawade, S. S. Hatkar, Dr R. C. Thool,
Dr V. R. Thool, Dr D. D. Doye, Milind Bhalerao, Dr A. B. Gonde, Dr A. Chakraborthi,
Dr A. V. Nandedkar, Dr P. B. Londhe, Dr R. R. Manthalkar, Dr S. S. Gajre, Prof. N. G. Megde,
Dr A. S. Sontakke, Dr R. H. Chille, Dr L. M. Waikar and A. I. Tamboli of S.G.G.S. Institute of
Engineering and Technology.
I thank my friends Principal Prof. S. L. Kotgire and Prof. Balaji Bacchewar for their words
of encouragement. M. M. Jahagirdar, L. M. Buddhewar, K. M. Buddhewar, D. V. Deshpande,
S. R. Kokne, M. G. Damkondawar, Yeramwar, Pampatwar, D. R. Yerawar, S. R. Tumma, and
S. R. Mana also helped me to a great extent while writing this book.
I thank Pearson Education for publishing this book. In particular, I thank Ms V. Pavithra and
Ms Neha Goomer for their help in seeing this book through production. In addition, I also thank
Thomas Rajesh for his constant encouragement.
I appreciate the help and support provided by all the students, faculty, and non-teaching staff
of this institute as well as that of other friends who have directly or indirectly added value to this
book.
Thanks are also due to my wife, Surekha, who persistently supported me at all times. I am
indebted to my sons Amol and Amit, daughter Sangita, as also my daughter-in-law Swarupa, who
all played a key role in bringing this book to fruition. Swarupa was of immense help in drawing
the figures in several chapters. I thank all of them.

Ashok Namdev Kamthane


About the Author

Ashok Namdev Kamthane obtained his M.E. (Electronics) degree from S.G.G.S. Institute of
Engineering and Technology, Nanded. A meritorious student throughout his career, he has bagged
a number of prizes including cash and medals for his distinct work in the academics. For his
M. E. (Electronics) dissertation, he worked at the Bhabha Atomic Research Center, Mumbai.
Associated with the teaching profession for the past 30 years, Kamthane was instrumental
in the development of hardware and software using the 8051 (8-bit microcontroller) on Acoustic
Transceiver System required in submarines. He has also worked at Melton as an executive.
Currently Associate Professor at the Department of Electronics and Telecommunication
Engineering in S.G.G.S Institute of Engineering and Technology, he has guided a number of
undergraduate and postgraduate students in their projects and published a number of technical
papers at both national and international conferences.
This page is intentionally left blank.
Introduction to C++ 1
cHaPter

• 1.1 Differences between C and C++


• 1.2 Evolution of C++
• 1.3 The ANSI Standard
Chapter Outline

• 1.4 The Object Oriented Technology


• 1.5 Disadvantage of Conventional Programming
• 1.6 Programming Paradigms
• 1.7 Preface to Object Oriented Programming
• 1.8 Key Concept of Object Oriented Programming
• 1.9 Advantages of OOP
• 1.10 Object Oriented Languages
• 1.11 Usage of OOP
• 1.12 Usage of C++

1.1 Differences between c anD c++


Some differences between C and C++ are as follows:
(1) C is a procedure/function-oriented language and C++ language is driven by a procedure/
object.
(2) Data is not protected in C, whereas data is secured in C++. Data hiding concept is absent
in C.
(3) C uses a top down approach while C++ uses a bottom up approach. The program is
prepared step by step in C, and in C++ base elements are prepared first.
(4) In C, we cannot give the same name to two functions in a program, whereas due to the
function overloading feature, the above concept is possible in C++. One can initialize a
number of functions with the same name, but with different arguments. The polymorphism
feature is built in C++, which supports this concept.
2 Introduction to C++

(5) C uses printf() and scanf() functions to write and read the data respectively,
while C++ uses cout and cin objects for output and input operations, respectively.
Further, the cout uses << (insertion operator) and cin uses >> ( extraction operator).
(6) C uses stdio.h file for input and output functions, whereas C++ uses iostream.h
for these functions.
(7) Constructor and destructors are absent in C and the same are provided in C++.
(8) Inline functions are supported by C++, and the same are absent in C. Inline func-
tions can be used as micros. They are stated by a word ‘inline’.

1.2 evolution of c++

C SIMULA 67
C++ is an object oriented programming language and also con-
sidered as an extension of C. Bjarne Stroustrup at AT&T Bell
Laboratories in Murray Hill, New Jersey (USA) developed this
language in the early 1980s. Stroustrup, a master of Simula67
and C, wanted to combine the features of both the languages
and he developed a powerful language that supports object-ori-
ALGOL 68 C WITH CLASSES
ented programming with features of C. The outcome was C++
as per Fig. 1.1. Various features were derived from Simula67
and algol68. Stroustrup called the new language ‘C with
classes’. However, in 1983, the name was changed to C++.
The thought of C++ came from the C increment operator
C++ ++. Rick Mascitti coined the term C++ in 1983. Therefore,
C++ is an extension of C. C++ is a superset of C. All the
concepts of C are applicable to C++ also.
fig. 1.1 Evolution of C++
For developing complicated applications, object orient-
ed language such as C++ is the most convenient and easy.
Hence, a programmer must be aware of its features.

1.3 tHe ansi stanDarD


The ANSI stands for American National Standards Institute. This Institute was founded in 1918.
The main goal for establishing this Institute was to suggest, reform, recommend, and publish stan-
dards for data processing in the USA. This committee sets up the standard in the computer industry.
The recognized council working under the procedure of the American National Standards
Institute (ANSI) has made an international standard for C++. The C++ standard is also referred to
as ISO (International Standards Organization) standard. The process of standardization is gradual
and the first draft of the planned ANSI standard was made on 25 January 1994. This book will
continue to refer ANSI standard code, which is more commonly used. The ANSI standard is an
attempt to ensure that the C++ is portable.

1.4 tHe object orienteD tecHnology


Nature is composed of various objects. Living beings can be categorized into different objects.
Let us consider an example of a teaching institute which has two different working sections –
teaching and non-teaching. Further sub-grouping of teaching and non-teaching can be made for
The Object Oriented Technology 3

the coordination of management. The various departments of any organization can be thought of
as objects working for certain goals and objectives.
Usually an institute has faculty of different departments. The Director/Principal is a must for
the overall management of the institute. The Academic Dean is responsible for the academics of
the institute. The Dean for Planning should have the future plans of the institute and he/she must
see how the infrastructure is utilized effectively. The Dean R&D should see research activities
run in the institute forever.
Besides teaching staff there must be laboratory staff for assistance in conducting practical ses-
sions, and a site development section for beautification of the campus. The accounts department
is also required for handling monetary transactions and salaries of the employees. The Sports sec-
tion is entrusted the responsibility of sports activities. The Registrar for Administration and staff
for dealing with administrative matters of the institute are also required. Each department has an
in-charge who carries clear-cut given responsibilities. Every department has its own work as stat-
ed above. When an institute’s work is distributed into departments as shown in Fig. 1.1, it is com-
fortable to accomplish goals and objectives. The activities are carried on smoothly. The burden of
one particular department has to be shared among different departments with personnel. The staff
in the department is controlled properly and act according to the instructions laid down by the
management. The faculty performs activities related to teaching. If the higher authority needs to
know the details regarding the theory, practical, seminar and project loads of individuals of the de-
partment, then a person from the department furnishes the same to the higher authority. This way
some responsible person from the department accesses the data and provides the higher authority
with the requisite information. It is also good to think that no unconnected person from another
department reads the data or attempts to make any alteration that might corrupt the data.
As shown in Fig. 1.2, an institute is divided into different departments such as library,
classroom, computer laboratory, etc. Each department performs its own activities in association
with the other departments. Each department may be considered as a module and it contains
class and object in C++ language. This theory of class and object can be extended to every
walk of life and can be implemented with software. In general, objects are in terms of entities.

Computer Lab

Class Room

Library

fig. 1.2 Relationship between different sections


4 Introduction to C++

In a nutshell, in object oriented programming objects of a program interact by sending


messages to each other.

1.5 DisaDvantage of conventional Programming


Traditional programming languages such as COBOL, FORTRAN, C etc. are commonly known
as procedure oriented languages. The program written in these languages consists of a sequence
of instructions that tells the compiler or interpreter to perform a given task. Numerous functions
are initiated by the user to perform a task. When a program code is large, it becomes inconve-
nient to manage it. To overcome this problem, procedures or subroutines were adopted to make
a program more understandable to the programmers. A program is divided into many functions.

Main Function

Function-A Function-B Function-C

Function-D Function-E

Function-F Function-G Function-H

fig. 1.3 Flow of functions in non-OOP languages

Each function can call another function, as shown in Fig. 1.3. Each function has its own task. If
the program is too large the function also creates problems. In many programs, important data
variables are declared as global. In case of programs containing several functions, every function
can access the global data as per the simulation in Fig. 1.4. In huge programs it is difficult to know
what data is used by which function. Due to this the program may contain several logical errors.
Global Variables Global Variables Global variables

Function A Function B Function C Function D


Local Variable Local Variable Local Variable Local Variable

fig. 1.4 Sharing of data by functions in non-OOP languages

The following are the drawbacks observed in monolithic, procedure, and structured program-
ming languages:
Programming Paradigms 5

(1) Huge programs are divided into smaller programs known as functions. These functions
can call one another. Hence security is not provided.
(2) No importance is given to security of data and importance is laid on doing things.
(3) Data passes globally from function to function.
(4) Most function accesses global data.

1.6 Programming ParaDigms


(1) monolithic Programming:
(A) In these types of programming languages,
the program is written with a single function. GLOBAL DATA
A program is not divided into parts; hence it
is named as monolithic programming. It is 1 Statement
also called single thread execution. 2 Statement
(B) When the program size increases it leads 3 Statement
to difficulty.
goto 50
(C) In monolithic programming languages
such as basic and assembly language, the 50 Statement
data variables declared are global and the 51 Statement
52 Statement
statements are written in sequence.
(D) The program contains jump statements goto 1
such as goto that transfers control to any
99 Statement
statement as specified in it. Fig. 1.5 shows 100 Statement
a program of monolithic type. The global
data can be accessed from any portion of
the program. Due to this reason the data is fig. 1.5 Program in monolithic
not fully protected. programming
(E) The concept of sub-programs does not
exist, and hence is useful for small programs.

(2) Procedural/structured Programming


(A) Sometimes known as modular programming.
(B) Programs written are more efficient and easier to understand and modify.
(C) The procedural/structured programming languages are similar to solving a prob-
lem by human. In a nut shell, humans attempt a problem by adopting a sequence
of operations.
(D) It makes use of a top-down design model in which a program developer maps out
the overall program structure into separate subsections.
(E) Large size programs can be developed in structured programming such as Pascal
and C. Programs are divided in multiple sub-modules.
(F) Procedural/Structured programming languages such as FORTRAN, BASIC, AL-
GOL, COBOL, C, etc., are divided into a number of segments called as subpro-
grams. There is a main function and it invokes subprograms. Thus, it focuses on
functions apart from data. Figure 1.6 describes a program of procedural/structured
type. It shows different sub-programs accessing the same global data. Here also
the programmer can observe the lack of secrecy.
6 Introduction to C++

(G) The control of program can be transferred using unsafe goto statement.
(H) This type of programming language uses different control structures that are as
follows.
• Decision/selection control statements
• Iteration control statements
• Jump control statements
(I) Data are global and all the sub-programs share the same data, i.e. data are globally
accessible to all functions. Thus, any function operates on the global data and this
directs to loosing some vital information. We can conclude here that a module
represents a function.
(J) Procedural structured/programming languages permit data transfer through mes-
sages by means of functions.
(K) Least importance is given to the data in procedural/structured programming languages.
(L) These languages are used for developing medium-sized software applications.
(M) Complier and interpreter construction are easy and simple with this type of pro-
gramming language. Furthermore, these compilers and interpreters need low
memory to run on the computers.
(N) It is difficult to implement simultaneous processes/parallelization.

GLOBAL DATA

Local Data Local Data Local Data

Modules

fig. 1.6 Program in procedural/structured programming

1.7 Preface to object orienteD Programming


The prime factor in the design of object oriented programming approach is to rectify some of
the faults observed in the procedure oriented languages. OOP acts with data as a critical com-
ponent in program development. It does not allow the data to flow freely around the systems. It
ties data to the functions that operate on it and prevents it from accidental change due to external
functions. OOP permits us to analyze a problem into a number of items called objects and then
assembles data and functions around these items as per Fig. 1.7. Following are the impressive
characteristics of object-oriented programming:
Key Concepts of Object Oriented Programming 7

(1) OOP pays more importance to data rather than function.


(2) Programs are divided into classes and their member functions.
(3) OOP follows a bottom-up approach.
(4) New data items and functions can be comfortably added whenever essential.
(5) Data is private and prevented from accessing external functions.
(6) Objects communicate with each other through functions.

Object A Object B Object C

Data variables Data variables Data variables

Member function Member function Member function

Data variables Data variables Data variables

Member function Member function Member function

fig. 1.7 Relation between data and member function in OOP

1.8 Key concePts of object orienteD Programming

Object oriented programming language is a feature that allows a mode of modularizing programs by
forming ory area for data as well as functions that is used as object for making copies of modules as per
requirement.

There are several fundamental concepts in object oriented programming. They are shown in Fig. 1.8
and are discussed as follows.

Encapsulation

Data abstraction

Inheritance
C++
Polymorphism

Delegation

Genericity

fig. 1.8 Concepts/elements of object oriented paradigm


8 Introduction to C++

(1) objects

Objects are primary run-time entities in object oriented programming.

Objects are primary run-time entities in object-oriented programming. They may stand for a
thing that makes sense in a specific application. Some examples are a spot, a person, any data
item related to the program including user-defined data types. Programming issues are analyzed
in terms of object and the type of transmission between them. Program objects must be selected
like the items equivalent to actual world objects. Objects occupy space in memory. Every object
has its own properties or features that illustrate what the object can do. An object is a specimen
of a class. It can be singly recognized by its name. It declares the state that is shown by the data
values of its characteristic at a specific time. The state of the object varies according to the pro-
cedure used with it. It is called as the action of the object. The action of the object depends upon
the member function defined within its class.
Fig. 1.9 (a) shows some of the objects that we use in our daily life.


Object: City
Data:
Name_of_city
Population
Telephone Book Computer Watch Lock
Area


Functions:
Average age
Literacy_rate
Display
Home Trophy Television Bicycle Ambulance

fig. 1.9 (a) Commonly available objects fig. 1.9 (b) Representation of
an object

Objects communicate with each other by sending messages. An object can be represented by
Fig 1.9 (b).
The name of the above object is city. Its data members are name_of_city, population, and
area. The various functions associated with the city are average age, literacy_ rate, and display.

(2) classes

A class is grouping of objects that have the identical properties, common behavior, and shared relation-
ship. A class binds the data and its related functions together.

A class is the accomplishment of abstract data type. It defines the nature and methods that act
on the data structure and abstract data type, respectively. Specimens are also called as objects. In
other words, a class is a grouping of objects that have identical properties, common behavior, and
shared relationship. For example, Tata’s Swift, Maruti’s Alto etc. are the members of a class car.
The entire group of data and code of an object can be built as a user-defined data type us-
ing class. Objects are nothing but variables of type class. Once a class has been declared, the
programmer can create a number of objects associated with that class. The syntax used to create
Key Concepts of Object Oriented Programming 9

an object is similar to the syntax used to create an integer variable in C. A class is a model and
not a true specimen of the object. Every object has its own value for each of its member variables.
However, it shares the property names or operations with other instances of the class. Thus,
classes define the characteristic and action of objects.

Class: car
Properties: company, model, color, and capacity
Actions: Speed(), average() and break().

Class: computer
Properties: Brand, resolution, price and size
Action: processing(), display() and printing()

Class: floppy
Properties: company, size and capacity
Action: storing(), protection(), and retrieving()

fig. 1.10 Objects and their properties

In Fig. 1.10 commonly useful classes are described with their properties and action they per-
form. For example, a car has properties like company, model and color with which a car can be
identified among a number of cars of other properties, and the actions like speed() and aver-
age() describes its working.

Class home
{
Telephone

Book
Computer {
Watch

}
Lock 
Class vehicle

{} 
Class entertainment 
{} 
}
fig. 1.11 Classes and their members

Figure 1.11 describes the classes and related data that come under the different classes.
10 Introduction to C++

(3) method

An operation required for an object or entity when coded in a class is called a method.

An operation required for an object or entity when coded in a class is called a method. The opera-
tions that are required for an object are to be defined in the class. All objects in a class carry out
certain common actions or operations. Each action needs an object that becomes a function in the
class that defines it and is referred to as a method.
In Fig. 1.12 the class and its associated data members and functions are shown in different
styles. It is a frequent style of writing a class in the program.
The class A contains private data members and public methods or member functions.
Usually, the data members are declared private and methods or member functions are declared
as public and they are available outside the class. The data member of any class uses its member
functions or methods to perform operations.

class A
{
private
data member1;
data member2; Members
data member(n);
public
method1() { } Methods or
method2() { } Member functions
method_n() { }
};

(a)

Class A Class A

Data member 1 Data member 1


Data member 2
Data member 3 Method 1
:
Data member 2
:
Data member n Method 2

Method 1
Method 2
Method 3 Method n
:
:
Method n

(b)

fig. 1.12 (a) and (b) Representation of methods in different manners


Key Concepts of Object Oriented Programming 11

(4) Data abstraction

Abstraction refers to the procedure of representing essential features without including the background
details.

Abstraction refers to the procedure of representing essential features without including the back-
ground details. Classes use the theory of abstraction and are defined as a list of abstract properties
such as size, cost, height, and few functions to operate on these properties. Data abstraction is
the procedure of identifying properties and method related to a specific entity as applicable to
the application.
A powerful method to achieve abstraction is through the manipulation of hierarchical clas-
sifications. It permits us the breaking of semantics of multiple systems into layers by separating
them into multiple controllable parts. For example, a computer as shown in Fig. 1.13 is made of
various parts such as CPU, keyboard, and so on. We think it as a single unit, but the single unit
has several sub-units. They together do the single task. By assembling sub-parts we can build a
single system.
Hierarchical abstraction of complicated systems can also be used in computer software. The
data from conventional procedure oriented programs can be converted by abstraction mechanism
into its partial objects. A series of operation steps may develop a set of messages between these
objects. Each object shows its own attributes.
Data abstraction is used to define a data type available in the programming language, called
as abstract data type (ADT). It consists of a set of values and a set of operations.

 
(a) Computer as single unit (b) Different components of computer

fig 1.13 Computer and its parts

(5) encapsulation

The packing of data and functions into a single component is known as encapsulation.

C++ supports the features of encapsulation using classes. The packing of data and functions into
a single component is known as encapsulation. The data is not reachable by the outside functions.
Only those functions that are able to access the data are defined within the class. These functions
prepare the interface between the object’s data and the program. With encapsulation we can
accomplish data hiding. Data hiding is an important feature using which an object can be used
without the user knowing how it works internally.
In C++ the fundamental of encapsulation is class. A class defines the structure of data and
member functions. It is common to all its objects. Class is a logical structure whereas object is
12 Introduction to C++

a physical actuality. The goal of the class is to encapsulate complication. The class also has a
mechanism for hiding the data. Each member in the class may be private or public. Any non-
member function cannot access the data of the class. The public section of the class must be
mindfully coded not to expose the inner details of the class. Figure 1.14 explains sections of
encapsulation.
class C
Φ Φ Φ Φ Φ
κ Private Data
υυυ κκκκκ
Members
υ Private methods Φ υυυ κκκκκ Φ
υυυ κκκκκ
Φ Public methods Φ υυυ κκκκκ Φ
ι Public data Φ Φ Φ Φ Φ
members ιιιι

fig. 1.14 Encapsulation: Private and public sections

(6) inheritance

Inheritance is the method by which objects of one class get the properties of objects of another class.

Inheritance is the method by which objects of


Red Yellow Blue one class get the properties of objects of another
class. In object oriented programming inheritance
provides the thought of reusability. The programmer
can add new properties to the existing class without
changing it. This can be achieved by deriving a new
Orange Green Violet class from the existing one. The new class will pos-
sess features of both the classes. The actual power
of the inheritance is that it permits the programmer
to reuse a class that is nearly, but not precisely, what
Reddish Yellowish Bluish
he wants, and to tailor the class in such a manner
brown brown brown that it does not bring any unwanted incidental re-
sult into the rest of the class. Thus, inheritance is the
fig. 1.15 Inheritance feature that permits the reuse of an existing class to
make a new class. Figure 1.15 shows an example of
inheritance.
In Fig. 1.15, red, yellow and blue are the main colors. The orange is created from the combi-
nation of red and yellow, green is created from yellow and blue and violet is created from red and
blue. The orange color has attributes of both red and yellow, which produces a new effect. Thus,
many combinations are possible.

(7) Polymorphism

Polymorphism allows the same function to act in a different way in different classes.
Key Concepts of Object Oriented Programming 13

Polymorphism makes it possible for the same functions to act differently on different classes as
shown in Fig. 1.16. It is an important feature of OOP concept. It holds an ability to take more than
one form. Polymorphism accomplishes an important part in allowing objects of different classes
to share the same external interface. It is possible to code a non-specific (generi(c) interface to a
set of associated actions.

Line

Display()

Dotted Object Single Object Dash Object

Display(dotted) Display(single) Display(dash)

fig. 1.16 Polymorphism in OOP

(8) Dynamic binding

Binding means connecting one program to another program that is to be executed in reply to the call.

Binding means connecting one program to another program that is to be executed in reply to
the call. Dynamic binding is also known as late binding. The code present in the specified
program is unknown till it is executed. It is analogous polymorphism.
In Fig. 1.16 polymorphism allows the single object to invoke similar function from different
classes. The program action is different in all the classes. At execution time, the code analogous
to the object under the present reference will be executed. The reader is advised to refer polymor-
phism chapter for more details.

(9) message passing


An object oriented programming includes objects. The objects communicate with one another.
The programming with these objects should be followed with following steps.
(1) Declaring classes that define objects and their actions.
(2) Declaring objects from classes.
(3) Implementing relation between objects.
Data is transferred from one object to another object. A message for an object is the demand
for implementation of the process. Message passing consists of indicating the name of the object,
function, and required data elements (Fig. 1.17). Objects can be created, released, and interacted
with each other. An object is workable, as long as it is active. In object oriented programming
there is a panorama of independent objects that communicate with each other by swapping mes-
sages. Objects invoke member functions. They also negate if the calling object is not a member of
14 Introduction to C++

the same class. Thus a message is a solicitation to an object to call one of its member functions.
A message contains name of the member function and parameters of the function. Execution of
member function is just a response generated due to receipt of a message. It is possible when the
function and the object are of the same class.
Obj.Display (argument)

Object Data

Communication operator
Message

fig. 1.17 Message Passing

(10) reusability

Object oriented technology allows reusability of the classes by extending them to other classes using
inheritance.

Object oriented technology allows reusability of the classes by extending them to other class-
es using inheritance. Once a class is defined, the other programmer can also use it in their
programs. The programmer can also add new feature to the derived classes. The verified and
checked qualities of base classes need not to be redefined. Thus, the reusability saves the time.
In Fig. 1.18, class A is reused and class B is created. Again class B is reused and class
C is created.
CLASS A

CLASS B

CLASS C

fig. 1.18 Reusability

(11) Delegation
In OOP, two classes can be joined in two ways: (a) Inheritance, (b) Delegation. Both these ways
provide reusability of the class.
In Inheritance one class can be derived from the other class. The relationship between these
two classes is called as kind of relationship. For example if class Y is derived from class X, then
class Y is known as kind of X. Figure 1.19 (a) explains this point.
Advantages of OOP 15

CLASS A CLASS B
{ }; { };

Class X//Base class

CLASS C
{
A a; // Object of class A as data member
B b; // Object of class B as data member
Class Y//Derived class }

(a) (b)

fig. 1.19 Relationships between two classes: (a) Kind of relationship (Inheritance)
(b) has a relationship (Delegation)

The second type of relationship is has a relationship. When object of one class is used as
data member in the other class, such composition of objects is known as delegation. As shown in
Fig. 1.19 (b) class C has two data members. These two data members are objects of class A
and B, such relationship between the classes in known as has a relationship.

(12) genericity
The software components of a program have more than one version depending on the data
types of arguments. This feature allows declaration of variables without specifying exact
data type. The compiler identifies the data type at run time. The programmer can create a
function that can be used for any type of data. The template feature in C++ allows generic
programming.

1.9 aDvantages of ooP


Object oriented technology provides many advantages to the programmer and the user. This
technology solves many problems related to software development, provides improved quality
and low cost software.
(1) Object oriented programs can be comfortably upgraded.
(2) Using inheritance, we can eliminate redundant program code and continue the use of
previously defined classes.
(3) The technology of data hiding facilitates the programmer to design and develop safe
programs that do not disturb code in other parts of the program.
(4) The encapsulation feature provided by OOP languages allows programmer to define the
class with many functions and characteristics and only few functions are exposed to the
user.
(5) All object oriented programming languages allows creating extended and reusable parts
of programs.
(6) Object oriented programming changes the way of thinking of a programmer. This re-
sults in rapid development of new software in a short time.
(7) Objects communicate with each other and pass messages.
16 Introduction to C++

1.10 object orienteD languages


There are many languages which support object oriented programming. Tables 1.1 and 1.2 describe
the OOP languages and features supported by them.
table 1.1 Properties of pure OOP and object based languages

Pure object oriented languages object based


languages

Properties java simula smalltalk eiffel java ada


Encapsulation      
Inheritance      No

Multiple inheritance      No

Polymorphism      
Binding (Early and late) Both Both Late binding Early binding Both Early binding
Genericity      
Class libraries      Few

Garbage collection      
Persistence   Promised Less  Same as 3GL

Concurrency   Less Promised  Hard

table 1.2 Properties of extended traditional languages

extended traditional languages


Properties objective c c++ charm ++ objective Pascal turbo Pascal
Encapsulation     
Inheritance     
Multiple inheritance    --- ---
Polymorphism     
Binding (Early and late) Both Both Both Late Early
Genericity     
Class libraries     
Garbage collection     
Persistence     
Concurrency Poor Poor   
Usage of OOP 17

The following are the object-oriented languages, which are widely accepted by the pro-
grammer.
• C++
• Smalltalk
• Charm ++
• Java

smalltalK
Smalltalk is a pure object oriented language. C++ makes few compromises to ensure quick per-
formance and small code size. Smalltalk uses run-time binding. Smalltalk programs are con-
sidered to be faster than the C++. Smalltalk needs longer time to learn than C++. Smalltalk
programs are written using Smalltalk browser. Smalltalk uses dynamic objects and memory is
allocated from free store. It also provides automatic garbage collection and memory is released
when object is no longer in use.

cHarm++
Charm ++ is also an object oriented programming language. It is a portable. The language pro-
vides features such as inheritance, strict type checking, overloading, and reusability. It is de-
signed in order to work efficiently with different parallel systems together with shared memory
systems, and networking.

java
Java was developed by Patrick Naughton, James Gosling, Chris Warth, Mike Sheridan and Ed Frank
at Sun Microsystems. Java is an object oriented programming language and supports maximum
OOP characteristics exist. Its statement structure is like C and C++, but it easier than C++. Java
excludes few confusing and unsafe features of C and C++ like pointers.
Java allows client/server programming. Java is used for Internet programming. The Java
programs are downloaded by the client machines and executed on different types of hardware.
This portability is achieved by translation of Java program to machine code using compiler and
interpreter.
The Java compiler converts the source program to JVM (Java virtual machine). The JVM is
a dummy CPU. The compiler Java program is called as byte code. The Java interpreter translates
byte code into the object code. Compiler and interpreter do the conversion of Java program to
object code.

1.11 usage of ooP


Object oriented technology is changing the style of software engineers to think, analyze, plan,
and implement the software. The software developed using OOP technology is more efficient and
easy to update. OOP languages have standard class library. The users in their program can reuse
the standard class library. Thus, it saves lot of time and coding work.
The most popular application of object oriented programming is windows. There are sev-
18 Introduction to C++

eral windowing software based on OOP technology. Following are the areas for which OOP is
considered.
(1) Simulation
(2) Object oriented DBMS
(3) Office automation software
(4) Artificial Intelligence and expert systems
(5) CAD/CAM software
(6) Network programming & Internet applications
(7) System software

1.12 usage of c++


C++ is a flexible language. Lengthy programs can be easily controlled by the use of C++. It
permits us to create hierarchy -associated objects and libraries that can be useful to other pro-
grammers. C++ helps the programmer to write bug-free program, which are easy to maintain.

summary

(1) C++ is an object oriented programming (7) Larger programs are developed in structured
language invented by Bjarne Stroupstrup at programming such as Pascal and C. Pro-
AT&T Bell Laboratories. grams are divided in multiple sub modules
(2) The recognized council working under the and procedures.
procedure of the American National Standard (8) OOP acts with data as a critical component in
Institute (ANSI) has made an international the program development and does not let the
standard for C++. data to flow freely around the systems.
(3) The disadvantage in conventional program- (9) Object: Objects are primary run-time enti-
ming language is that the program written in ties in an object-oriented programming. They
these languages consists of a sequence of in- may stand for a thing that makes sense in a
structions that tells the compiler or interpreter specific application.
to perform a given task. When program code (10) Class: A class is grouping of objects that have
is large then it becomes inconvenient to man- the identical properties, common behavior,
age. and shared relationship. The entire group of
(4) The prime factor in the design of object ori- data and code of an object cab be built as a
ented programming approach is that to get user-defined data type using class.
back some of the faults found in the proce- (11) Method: An operation required of an object
dure oriented languages. or entity when coded in a class is called a
(5) In monolithic programming languages such method.
as basic and assembly language, the data (12) Data Abstraction: Abstraction directs to the
variables declared are global and the state- procedure of representing essential features
ments are written in sequence. without including the background details.
(6) In the procedural programming languages (13) Encapsulation: C++ supports the features of
such as FORTRAN and COBOL, programs encapsulation using classes. The packing of
are divided into number of segments called data and functions into a single component is
as subprograms. Thus it focuses on functions known as encapsulations.
apart from data. (14) Inheritance: Inheritance is the method by
Exercises 19

which objects of one class get the proper- (17) The languages C++, Smalltalk, Eiffel and
ties of objects of another class. In object ori- Java are widely used OOP languages.
ented programming inheritance provides the (18) Object oriented technology is changing the
thought of reusability. style of software engineers to think, analyze,
(15) Polymorphism: Polymorphism makes pos- plan and implements the software. The soft-
sible the same functions to act differently on ware developed using OOP technology is
different classes. It is an important feature of more efficient and easy to update.
OOP concept. (19) C++ is a flexible language. Lengthy programs
(16) Object oriented technology allows reusabil- can be easily controlled by the use of C++.
ity of the classes by extending them to other
classes using inheritance.

eXercises

(A) Answer the following questions.


(1) Compare C and C++. (15) Mention the types of relationships be-
(2) What is object oriented programming? tween two classes.
(3) Explain the key concepts of OOP. (16) What is structured oriented program-
(4) What is ANSI standard? ming? Discuss its pros and cons.
(5) What are the disadvantages of conven- (17) How is global data shared in procedural
tional programming languages? programming?
(6) Explain the characteristics of monolithic (18) Describe any two object oriented pro-
programming languages. gramming languages.
(7) Compare structured and procedural lan- (19) What are the differences between Java
guages. and C++?
(8) List the disadvantages of procedural pro- (20) Mention the advantages of OOP languages?
gramming languages. (21) What do you mean by message passing?
(9) Explain evolution of C++. (22) Distinguish between inheritance and
(10) List the names of popular OOP languages. delegation.
(11) List the unique features of an OOP paradigm. (23) Can we define member functions in
(12) What is an object and class? private section?
(13) How is data secured in OOP languages? (24) Can we declare data member in the public
(14) Compare and contrast OOP languages section?
with procedure oriented languages.

(B) Answer the following by selecting the appropriate option.


(1) Data hiding concept is supported by language (c) function names are same but differ­
(a) C ent number of arguments
(b) Basic (d) none of the above
(c) Fortran (3) C++ language was invented by
(d) C++ (a) Bjarne Stroupstrup
(2) Function overloading means (b) Dennis Ritche
(a) different functions with different (c) Ken Thompson
names (d) none of the above
(b) function names are same but same (4) The languages COBOL and BASIC are
number of arguments commonly known as
20 Introduction to C++

(a) procedure oriented languages (b) encapsulations


(b) object oriented languages (c) inheritance
(c) low level languages (d) none of the above
(d) none of the above (9) The existing class can be reused by
(5) A program with only one function is ob- (a) inheritance
served in (b) polymorphism
(a) monolithic programming langu­ (c) dynamic binding
ages. (d) abstraction
(b) object oriented languages (10) Composition of objects in a class is
(c) structured programming languages known as
(d) none of the above (a) delegation
(6) The packing of data and functions into a (b) inheritance
single component is known as (c) polymorphism
(a) encapsulation (d) none of the above
(b) polymorphism (11) A class
(c) abstraction (a) binds the data and its related func­
(d) none of the above tions together
(7) The method by which objects of one class (b) data and their addresses
get the properties of objects of another (c) contains only functions
class is known as (d) none of the above
(a) inheritance (12) The major drawback of procedural pro-
(b) encapsulations gramming languages is
(c) abstraction (a) frequently invoking functions from
(d) none of the above main()
(8) The mechanism that allows same func- (b) non security of data
tions to act differently on different classes (c) non security of methods
is known as (d) none of the above
(a) polymorphism
Basics of C++ 2
CHAPTER

• 2.1 Introduction
CHAPTER OuTlinE

• 2.2 Steps to Create and Execute a C++ Program


• 2.3 Flowchart for Creating a Source File, Compiling, Linking and Executing in C++
• 2.4 C++ Environments
• 2.5 Typical C++ Environment (Borland C++)
• 2.6 Structure of a C++ Program
• 2.7 Illustrative Simple C++ Program without Class
• 2.8 Header Files and Libraries

2.1 inTRODuCTiOn
A programmer must know rules and steps to develop programs with C++. Programs given in this
book are developed using Borland’s C++ IDE compiler version 3.0. Let us try to follow the steps
for creating, compiling and running programs under Borland’s C++ IDE compiler.

2.2 STEPS TO CREATE AnD EXECuTE A C++ PROGRAM


For creating and executing a C++ program, one must follow various phases. The C++ program
is created with an editor and saved with extension .cpp. Following this step, compilation and
execution operations are to be performed. The following phases are essential in ‘C++’ when a
program is to be executed in MS-DOS mode.
(1) Create
(2) Save
(3) Compile
(4) Execute.
22 Basics of C++

We would now see the steps in each phase.


(1) Steps for creation of a C++ program
(a) Open the Turbo C++ editor. In this book, the path selected for opening the C++ edi-
tor is C:\TURBOC3\TC\BIN. Executable file TC is to be clicked in BIN file to open
the window of C++.
(b) In the Edit menu section with alt+f, select the New option. A new file is selected
with this procedure.
(c) The program should be written in ‘C++’ editor.
(2) Saving a C++ program
(a) Save the program using the Save option in the file menu with extension .cpp.
The reader may create his/her own folder where programs are to be stored. The
file name does not necessarily include extension “.cpp.” The default extension
is “.cpp.” The user can also specify his/her own extension. The C++ program
includes preprocessor directives.
(3) Compilation of a C++ program
(a) The source program contains statements that are to be translated into object codes.
These object codes are used for execution by the computer. So, compile the source
code with alt+c keys.
(b) If the program contains errors, the programmer should correct it using C++ editor.
(c) If there is no error in the program, compilation proceeds and the translated program
is stored in another file with the same file name and with extension “.obj.” This
object file is stored on a secondary storage device such as the disk.
(4) Linking and running/execution of a C++ program
(a) The linking is also an essential process. It puts together all the program files and
functions that are required by the program. For example, if the programmer is us-
ing pow() function, then the object code of this function should be brought from
math.h library of the system and linked to the main() program. After linking, the
program code is stored on the disk. The program code generated is called the execut-
able code.
(b) Run the executable code file with alt+r, in case of no errors. In case there are errors,
correct the program, and follow steps (1), (2), (3), and (4).

2.3 FlOWCHART FOR CREATinG A SOuRCE FilE, COMPilinG, linKinG


AnD EXECuTinG in C++
The following steps are necessary for execution of a program in C++.
• Write the code for a program and save it
• Compile the program with a compiler
• Link the program with library functions
• Run the program.
A flowchart for implementing the aforesaid steps is given in Figure 2.1
C++ Environments 23

Open any text editor

Write the code for the program

Save the file with .cpp as an


extension

Correct the code Compile the program

Yes Syntax
Error / s?

No
Link with library

Run the program

Figure 2.1 Flowchart for creating a C++ program, compiling and linking

The process of compiling, linking and running a program in C++ is elaborated in the following
section.

2.4 C++ EnViROnMEnTS


C++ programs can be implemented on different operating systems such as UNIX, Linux, Win-
dows, and DOS, etc. C++ programs executed under DOS environment can also run successfully
under Windows, because we have to follow the same programming rules on both platforms. Only
the C++ execution environments are different.
Various types of C++ compilers are described below.
(1) GNU C++: The GNU C++ is a compiler and it is available in the source code form. It is
available in different versions.
(2) NDP C++: NDP C++ is also a C++ compiler, i.e. compatible with AT&T C++ 2.0 for
DOS,UNIX , Sun OS, etc.
(3) Oregon C++: Oregon C++ is a C++ compiler compatible with AT&T C++ 2.0 for a
variety of UNIX systems.
(4) Zortech C++ Version 2.1: This compiler has been developed for MS-DOS, OS/2, and
UNIX.
(5) Borland C++: Borland C++ compiler is a combination of two compilers. They are ANSI
standard C compiler and C++ compiler. It runs on MS-DOS. Borland C++ includes Tur-
bo Assembler, Turbo Debugger, and Turbo Profiler.
In the following section, brief information for creating, compiling, and executing C++ programs
are described using Borland C++ compiler.
24 Basics of C++

2.5 TYPiCAl C++ EnViROnMEnT (BORlAnD C++)


In this section, brief information is given about the different platforms for C++ implementation,
and execution of C++ programs using Borland C++ compiler under the Windows platform is
described.

STEP 1: OPEn AnY TEXT EDiTOR


Unix/Linux platform:
Use text editors such as Gedit, Kwrite, Medit, ed, VI, etc.
Windows platform:
Use text editors such as Notepad, Wordpad, etc.
Alternately, one can use integrated Borland C++ compiler, which supports its own text editor.
Once Turbo C++ is installed, it automatically creates a directory turboc3 and subdirectory
bin. Follow the path c:\turboc3 and click the executable file tc. One can use desktop
shortcut for turboc3. Turbo C++ screen appears, which is blank initially and has a menu bar at
the top, which is shown as follows.

STEP 2: WRiTE THE CODE FOR THE PROGRAM


Write the code to fulfill the requirements of the program, if possible using the proper syntax and
indentation using an editor.
Typical C++ Environment (Borland C++) 25

Alternatively, create a source program using integrated Turbo C++ editor. Go to the File menu
and select New. The file name NONAME00.CPP appears on the screen at the centre of the window.
Check whether your source program is typed correctly. If mistakes are found, correct them.

STEP 3: SAVE THE FilE WiTH .CPP AS An EXTEnSiOn


26 Basics of C++

Now press F 2 to save your program or use Save option with .cpp extension. You can change
the file name and save it using the Save option in File menu. In the following window the file
is saved with ABC.CPP.

STEP 4: COMPilE THE PROGRAM


Unix/Linux platform:
Open the terminal window; change the working directory to the directory where the program file
is stored.
Compile the program using the command: g++ filename.cpp
It will display the errors and warnings. If there are any errors and warnings, correct them and
save the corrected file again.
After successful compilation, file a.out will be created in the same directory.
Windows platform:
Use IDE such as Turbo C++.
From the File menu, open the program file and compile it using ‘Compile’ option in Com-
pile menu or use Alt+F 9.
It will display the errors and warnings. If there are any errors or warnings, correct them and
save the corrected file again, compile again. If program is correct, then the window shows:
• Warnings: 0
• Errors: 0
After successful compilation, a file filename.obj will be created in the same directory. The fol-
lowing window shows the compilation of a program named ABC.CPP.
Discovering Diverse Content Through
Random Scribd Documents
Of an election-time approaching near;
And who can tell the upshot? Will the rout
Whom I enfranchised not so long ago
Shake off the yoke of Tory Government,
And bring the Liberals in instead? Who knows?

Fain would I get me to the gorgeous East!


I wonder how my constitution stands
The rigours of this chilly English clime,
This so-called summer, wretched, cold, and wet.
I shiver by the fireside, while the steam
Floats from the damp fields round my country seat,
And racks my agèd bones with rheumatism.
Place me upon some Asiatic throne,
Give me an empire in the realms of morn,
Thither I'd hasten from this bourgeois court
On a triumphal car with silver wheels.

V. A. C. A.

The World, July 30, 1879.

WHAT LOCKSLEY HALL SAID BEFORE HE


PASSED HIS OXFORD RESPONSIONS,
(Vulgo SMALLS).
OH the misery of "Smalls!" the cark, the turmoil, and the grind!
Oh the cruel, cruel fetters which are wreathing round my mind!
There is grammar, there is Euclid, and far worse than all of these,
Arithmetical refinements, with their stocks, and rules of threes,
With their discount and their practice, and their very vulgar fractions,
Smashing up the one ideal into many paltry factions.
Square root makes the head to ache, the decimals the tear to start,
For they're ever circulating round the fibres of my heart—
Learning grammar is like putting water in a leaky pot,
And its memory is only like the days remembered not;
Verbs in "M I" are aggravating, Euclid makes the foot to stamp,
Only lucid when enlightened by a moderator lamp,
The old spider and his cobwebs! would that I could sweep them out
From the dust and must of ages with a triumph and a shout;
Shall I spurn him with my foot, or shall I scorn him with mine eye?
Shall I tear him into pieces? SOUTHEY burnt him—so will I.

C. C.

B. N. C. College Rhymes, 1861.

These lines also appeared in Punch.


There was also an early parody of "Locksley Hall" in Punch,
describing the Railway Mania of 1845. This parody was rather
technical in its language, not very amusing, and is now quite out of
date.

BATTUE SHOOTING.
Gather round, my noble comrades; hardy sportsmen, gather where,
Placed in yonder shaded corner, stands for each an easy chair;
Close behind are well-packed hampers, and attendants duly wait
To reload your deadly weapons while you sit and shoot in state.
Amply fed and reared, my pheasants—tame they'll answer to your
call,
But, like whirling leaves in winter, soon you'll see them thickly fall.
Hark, the beaters drive them forward. Now, prepare—the time is
nigh,
We shall soon reduce their numbers. Peste! they're far too fat to fly!
See the startled hares and rabbits vainly shelter safe have sought,
Headlong rushing, mad with terror—surely this is noble sport!
Eh! what say you? Let go at them, now's the time to try your skill;
Crawling wounded, lame and fluttering, down they go the bag to fill.
Warmish work, and quite fatiguing—let's refresh ere we renew.
Vulgar hinds may sneer and welcome. Vive, say I, the good battue!

* * * * *

Surely those who so love slaughter might, when close time comes
for grouse,
Find congenial occupation if they donned the butcher's blouse.

D. EVANS.

The Weekly Dispatch, August 31, 1884.

GODIVA.
(A Pose Plastique, by Madame Warton, before the forthcoming
picture by Edwin Landseer, R.A.)
OR, THE PEEPING GENT OF COVENTRY STREET.
I waited in the street named Coventry;
I hung outside the 'bus from Putney Bridge,
To watch the three short fares; and there I shaped
The last new "Tableau Vivant" into this.

NOT only we, the smartest blades on Town,


Fast men that with the speed of an express
Run down the slow, not only we, that prate
Of gents and snobs, have loved the genus well,
And loathed to see them unamused; but she
Did more, and undertook, and overcame,
The Venus of the Tableaux Vivans—Madame
Warton, Queen of the Walhalla, near the street
Of Coventry: for when there was nought up
To take the Town, the Gents all came to her,
Clamouring, "If this last, we die of slowness!"
She sought a painter, found him where he strode
About the room, among his dogs, alone,
His beard shaved close before him, and his hair
Cropped short behind. She told him the Gents' fears,
And prayed him, "If this last, they die of slowness!"
Whereat he stared, replying, half-amazed,
"What would you have me do—an animal painter—
For such as these?" "A Tableau paint," said she.
He laughed, and talked about Sir Peter Laurie.[12]

Then chucked her playfully beneath the chin;


"O, ay, ay, ay, you talk!" "Talk! yes!" she said.
"But paint it, and prove what I will not do."
And with a sly wink there was no mistaking,
He answered, "Ride you as the famed Godiva,"
And I will paint it," she nodded, and in jest
They parted, and a cabman drove her home.

All was arranged. The boardmen in the street,


As curs about a bone with snarl and blow
As curs about a bone, with snarl and blow
Made war upon each other for a board:
The best man won. She sent bill-stickers forth,
And bade them cover over every hoarding
With large placards, announcing she would please
Her favourite gents; who, as they loved her well,
From then till Monday next, in crowds should come
And gaze at her,—each one his shilling paying
For seats within the public promenade.

Then went she to her dressing room, and there


Unhooked the wedded fastenings of her gown,
Some soft one's gift; but every now and then
She lingered, looking in her toilette glass,
Rougeing her cheek: anon she shook herself,
And showered the rumpled raiment 'neath her knee;
Then clad herself in silk; adown the stair
Stole on; and like a bashful maiden slid
Through passage and through passage, until she reached
The platform; there she found her palfrey trapt
With pewter logies and mosaic gold.

Then rode she forth, clothed all in silken tights:


The fiddles played beneath her as she rode,
And the reserved seats hardly breathed for fear.
The little wide-mouthed heads beyond the stalls
Had cunning eyes to see: the crimson rouge
Made her cheek flame: a fast man, winking, shot
Light horrors through her pulses: the saloon
Was all in darkness; though from overhead
The flickering gas-light dimly flared: but she
Not less through all bore up, till, last she gave
The signal to the workmen in the flats,
And round upon the pivot slow she turned.

Then rode she back, clothed all in silken tights:


And one low Gent, decked out in Joinville tie,
, ,
The certain symbol of a Gentish taste,
Using an ivory opera-glass he'd hired,
Peeped—but the glasses, ere he had his fill,
Were shivered into pieces, and the curtain
Was dropt before him; so that the deposit
Left on the glass was forfeit to the Jew;
And he that knew it grieved: Now all at once,
With twelve great shocks of sound, the interlude
Was scraped on cat-gut from a dozen fiddles,
One after one, for neither did keep time,
Nor play in tune: and Madame Warton gained
Her chamber; whence re-issuing, as "Venus
Rising from the Sea," the ennui passed away,
And she made everlasting lots of tin.

The Puppet Show, April 1, 1848.

THE VOYAGE.
WE hired a ship: we heaved a shout:
We turned her head towards the sea;
We laugh'd and scull'd, and baled her out,
We scream'd and whistled loud for glee:
We scull'd, we scream'd, we laugh'd, we sang,
Beneath the merry stars of June:
Went flute tu-tu, and banjo bang:
We meant to sail into the moon!

Far off a boatman hail'd us high:


"My boat is named the Bonny Bess;
Old Jack will charge you more than I,
For I will charge you sixpence less:
My boat is strong, and swift, and taut,
But Jack's—she is not worth a cuss."
We held his terms in scorn, for what
Was sixpence or a crown to us?

We bang'd; we baled; we scull'd; we scream'd;


The water gain'd upon us fast.
We looked upon the moon: she seem'd
As far as when we saw her last.
We look'd: no terror did we show;
We did not care a button, we;
We knew the good ship could not go
Beyond the bottom of the sea.

But one—at best he was a lout—


The same, we guess, was short of chink—
Exclaim'd in terror, "Let me out,
I am quite sure the ship will sink.
The leak is quickly gaining height;
'Twill soon be half-way up the mast."
And through the hatch that starry night
We let him out, and on we pass'd.
Slight skiffs aslant the starboard slipt,
And jet-black coal-boats, stoled in state,
And slender shallops, silvern tipp'd,
And other craft both small and great.
But we nor changed to skiff or barge,
Or slender shallops, silvern-peak'd;
We knew no vessel, small or large,
Was built by mortal hands, but leak'd.

Beyond the blank horizon burn'd;


The moon had slid below the main;
About the bows we sharply turn'd,
And scull'd the good ship home again.
Before us gleam'd the hazy dawn;
We scull'd, but ere we shockt the lea,
And paid old Jack, the ship had gone
Down to the bottom of the sea.

Above the wreck the sad sea breaks,


And many a pitying moonlight streams;
And o'er the yeasty water flakes
The snow-white sea-gull, sliding screams.
If any goods be wash'd ashore,
Or cash—if any cash be found—
To us, and not to Jack, restore:
But then—you cannot; we were drowned.

S. K. C.

Kottabos (William McGee), Dublin, 1875.


"BREAK, break, break,
On thy cold gray stones, O sea!
And I would that my tongue could utter
The thoughts that arise in me."

* * * *

TENNYSON.

It seems hard to believe that the weather was even hotter in New
York during last June than it was in London during certain days of
July and August. An American poet thus records his impressions:—

HOT, hot, hot,


Is the blistering breath of June,
And I would that my throat could utter
An anti-torridness tune.
O well for the Esquimau
That he sits on a cake of ice!
O well for the Polar bear
That he looks so cool and nice!
But the scorching heats pours down
And blisters both head and feet!
And O for a touch of vanished frost,
Or the sound of some hail and sleet!

THE LAY OF THE DRENCHED ONE.


(Time, 11.45 P.M.)
PELT, pelt, pelt,
On the cold wet earth, thou Rain!
While my tongue is about to utter
The anger that swells in my brain.

Oh, well for the waterproof'd gent,


As he walks in his shiny array:
Oh, well for the dandified swell,
As he drives in his cabriolet.

And the last lone 'bus rolls on,


As full as its guard can fill;
But oh for the sight of a vanish'd cab,
And the sound of a wheel that's still!

Pelt, pelt, pelt,


On the damp, drench'd streets, O Rain;
But the tender bloom of a dress-coat spoilt
Will never return again.

JOHN COLLETT.

"But, says the Sporting Times, Calcutta is a rough place for a 'stony-
broke,' for there is no comfortable workhouse for Europeans, such as
would remind one of Tennyson's well-known 'Workhouse Song.'"—

"Break, break, break,


All these cursed stones I see,
For that is the task they've set me,
And I wish that I wasn't me."
WAKE! wake! wake!
In thy Northern land so free,
And our eloquent leader utters
A protest for you and me.

Oh, well for Midlothian's sons


That they shout with him in the fray,
Oh, well for our British lads,
For we know he will gain us the day.

And the Franchise war goes on,


Though the Lords would have us be still;
But, O for our triumph, thou Grand Old Man,
When the people have their bill.

Wake! wake! wake!


To the war-cry of "Liberty!"
And slav'ry's old despotic days
Shall never return to thee.

RICHARD H. W. YEABSLEY.

The Weekly Dispatch, September 14, 1884.


(Parody Competition).
———♦———

RHYME FOR ROGERS.


Howe'er it be, it seems to me
A House of Peers can be no good:
Mob caps are more than coronets,
And Hyde Park crowds than Hatfield's brood.

Punch, September 6, 1884.

———♦———
Tennyson's "Enoch Arden" has been less frequently parodied than
most of his poems; some years ago the Australian Punch had a
clever burlesque of it, and a "continuation" of Enoch Arden was
privately printed in 1866. This very scarce little pamphlet consisted
of twelve pages, in a blue wrapper, and had no printer's name or
place on it. As it is now eagerly sought after by collectors of
Tennysoniana, it is here given in full:—
ENOCH ARDEN,
(CONTINUED)
BY

C. H. P.

Not by the "LAUREAT,"—but a timid hand


That grasped the Poet's golden lyre, "and back
Recoil'd,—e'en at the sound herself had made."

1866.

ENOCH ARDEN
(Continued).
So Enoch died, as he had lived so long.
Alone—alone! for Miriam Lane had pass'd
To an adjoining chamber; but she heard
Those joyous dying words, "A sail! a sail!
I'm sav'd," and hurried back to comfort him;
But wist not that the "sail" his spirit saw
Was God's own ark, propell'd by angel wings
Towards the Ocean of Eternity.
"Ah well!" she said; "poor Enoch! he is gone;
God rest his soul: give him more joy in Heaven
Than he had found on earth,—at least of late:
I thought he had not long to linger here,
The sea made such a moaning all the night:
It sounded like his death-wail; and methought
I saw the corpse-light dancing in the fen.
Now will I tell the neighbours who he was:
They'll wonder how Dame Miriam knew the truth,
But kept it close, because she loved her friend
Enoch:—they cannot call me gossip now."
It chanced that day, that Philip left his mill
Earlier than wont: the nutting-time was come,—
That season of the year so closely link'd
To Philip's destiny;—it seem'd to stir
His pulse to quicker beat, and send a thrill
Of strange mysterious feeling thro' his veins.
He knew not how, or why: but Philip hurried on
That he might keep the promised holiday
With all the children—his, and hers, and theirs—
All dear to him; nor least the bonny Ralph,
That last wee prattler, climbing to his knee.
And all were ready with their nutting crooks;
And Annie Ray, his own, his wife at last,—
His "beam of sunshine," as he called her oft.
But as he left his mill, the passing-bell,
With its first startling boom, tolled on his ear.
It is a sound that enters at the brain,
A saddening augury of woe, and strikes
The inmost chord of sympathising hearts
That fondly breathe an echoing sigh of pain.
Sudden it falls, chilly as winter's frost,
Turning to icicles the heart's warm blood.
Spoke Philip to the comrade at his side,
"Know you for whom that passing-bell is struck?
Some full-grown man: it is the minute-toll."
"Mayhap the stranger down at Miriam Lane's;
I heard that he was dying yester-e'en.
The tide has turn'd but now: 'tis running out;
Whoe'er he was, his soul upon the shore
Waited the ebbing tide to ebb away."
Then came they to a little knot of men
(Fishers in dark-blue knitted woollen vests)
Hard by "the idle corner,"—so 'twas called,—
The blacksmith's forge. The honest gossippers,
As Philip pass'd along, hushed their voices.
Could he have read their looks, he might have known
Some dark o'er-clouding sorrow was at hand,
More nigh than he could think for, and more hard.
Then passed a woman from the ale-house door,
And, all unwitting Philip was so near,
Cried, "Have you heard who died just now?
'Twas Enoch Arden,—lost, but late returned;
And Miriam Lane has known it all along!"
As if some hand had struck a sudden blow,
Philip seemed stunned: the blood forsook his cheek,
The big cold drops stood out upon his brow,
As on the victim's, stretched upon the rack.
His comrade laid his hand on Philip's arm,
And uttering no word (what could he say?)
Led him, as one half-blinded, step by step,
Until they reached the home, where Annie Ray,
Poor widow-wife, sat watching his return;
He stagger'd towards her, caught her in his arms:
God help me,—kiss me darling,—wife look up!
"My wife—his wife—I know not what I say:
If we did sin it was unwittingly;
O, Annie! darling, one more fond embrace,
E'er it be said our wedded love was wrong."
Then, as she wonder'd, gazing on his face,
And twined her loving arms around, he told,—
Yes, told her all—how Enoch had returned.
Then Philip's comrade, who had linger'd near,
Beckon'd the children out, and closed the door:
There Miriam met them, with the lock of hair:
But, loth to interrupt the sorrowers,
She led the children to the house of death;
And took a key from off the wooden peg,
Beside the settle, where she used to hang
The skeins of twine to mend the fishing nets:
Then gently led them up the narrow stair,
That creaked beneath their stealthy-moving tread.
Sacred the silence that we ever keep,
When death is in the house! we speak, we walk,
With muffled tone and step, as if the dead
Could be disturb'd, and waken out of sleep.
Then Miriam turn'd the key;—that jarring click!
How harsh it grated on the children's ear!
As do the pebbles on the boat's sharp keel.
Cold thro' the open casement came the breeze:
There stood the bed—and on the sacking lay,
Distinct beneath the sheet, a rigid form—
The feet so prominent, the arms close down!—
The children clung together, half afraid,
While Miriam turned the coverlid aside.
They dar'd not stoop to kiss the pallid face;
But gaz'd awhile, then slowly left the room.
Once they had seen their brother, as he lay
Dead in his little cot: but he had look'd
So beautiful asleep, you might have thought
Death's angel had but gently turned him round,
To rest more quietly: the tiny hands
Were clasp'd together, and the face bent down,
As resting on the pillow—not like this,—
So stiff, so cold, so utterly alone.
Now, as the twilight fell the second day,
Another mourner came: she spoke no word:
Miriam had put the key within her hand,
Turning aside, to dash away her tears:
The widowed woman went up-stairs alone.
One moment gazing on her Enoch's face,
She stoop'd to kiss it, putting back the hair,
As she had done in life: then kneeling down
She pray'd,—"forgive me,—pity me,—Oh God."
She touch'd his marble-cold, pale, hand with hers,
That bore e'en then the double wedding rings.
She laid her aching head upon his breast,—
When from her lips came forth a cry,—a shriek,
Like to a hare's when shot: and Miriam came,
And bore her senseless from the room of death.
'Twas strange how quick the widow's glance had caught
Each little circumstance of the chamber,
And noted in her loving memory,—
How on the table lay his Bible—closed:
No need had Enoch now of Holy Writ,
No need of Gospel Message; for he stood
In presence of his SAVIOUR, and his GOD.
But had she open'd where the much-worn page
Told of the frequent reading, she had seen
The marks of blistering tears upon that text,
"Whose shall she be in Heav'n? there they marry
Not, nor give in marriage, but are angels."
There was a fly upon the window pane
Whose low monotonous hum she scarcely heard,
And that unconscious; but in after years
The buzzing of a summer fly recall'd,
E'en in her happiest hours, that day,
That lonely visit to the bed of death;
And cast a moment's shadow o'er her heart.
More keenly she remarked the remnant store
Of lulling anodynes: ah! bootless all
To soothe the fever of his aching brain:
The Wise Physician healed him with a touch,
(E'en as we lay our hand on ringing glass
To still the sound that careless fingers make),
And sent a loving angel as his guide
Through the dark valley to the realms of joy.
There lay his watch, his big round silver watch,
Whose constant tick had sadly echoed "Home"
In all his wanderings; now its pulse was hushed:
No need of Time for him: he had Eternity.

* * * *

Then Philip left the village for awhile:


And when once more the nutting-season came,
And yellow "rust-spots" on the autumn leaves,
He and his Annie were again at home!
They'd learnt the lesson God had set them, "Wait:"
And now the time of their reward was come:
In Faith's strong soil Patience had taken root,
And brought forth Hope and Joy, as bloom and fruit.

ENOCH'S "HARD 'UN."


PART I.
In a fair village on the English coast
There dwelt a lad—they called him Hunky Sam.
He was but young—three years, or may be four,
But manly for his age; his appetite
For bulls'-eyes, "coker"-nuts, and such light fare
Was something awful, even for a boy;
But better far than even coker-nuts,
He loved a maiden of surpassing grace—
Of humble parentage, but very fair,
Whose name euphonious was Susan Ann.
The parents of these twain were fisher-folk
Of low degree, but honest to a fault.
They would not steal the veriest pin, unless
They were quite certain they would not be caught.
Now Hunky's love for peerless Susan Ann
Was felt by her, and given back to Hunk;
And as the twain upon the yellow sands
Would play, young Sam would say, "Now let us be,
As grown-up folks, and we'll pretend we are
A wedded pair, and I will be a man,
And you, dear Susan Ann, my little wife;
And you, go sit within yon gloomy cave,
Which we will make believe to be our house,
And I'll come staggering in like daddy does,
And you can belt me on my flaxen head
With this small stick, which we will call a broom—
For that's the way my dad and mammy do."
And so they played upon the seashore sand
Till Susan Ann had got the thing down fine.
And time sped on, and Sam and Susan Ann
Were married, and the twain became one flesh.

PART II
PART II.
Sam went to sea, and whilst upon a voyage,
He read of Enoch Arden and his woes;
And so he soon resolved to do the same
As in the book he read that Enoch did.
To carry out his plan he sent word home,
By trusty shipmate, to his Susan Ann,
That he was drowned. He really did not care
A great deal for his once-loved Susan Ann,
Who, when the knot had but been tied a year,
Had clearly showed that she could be the boss.
So time sped on, and artful Hunky Sam
In foreign climates had a jolly time
For several years. "I think I'll homeward sail,"
One day he said, "and see how Susan Ann
Gets on; like Enoch, I will softly glide
Towards the cottage there upon the cliff,
And see how she makes out with her new man,
For she is doubtless wedded once again,
Just like that Mrs. Arden in the book."
Away he sailed across the sounding surge
(A good expression that, but not my own),
And soon he reached his village on the coast.
'Twas night. He crept towards the little cot
Where once he'd dwelt. A light was burning clear;
He peered in through the window. Susan Ann
Was there, but t'other fellow was away.
His wife glanced up: she saw the faithless Sam;
She sprang towards him—grabbed him by the hair
And held him there, whilst with her other arm
She dealt him myriad thwacks with broomstick stout.
"You would," she cried—"you would say you were dead,
And with your foreign gals go cuttin' up;
And leave me here to take in washing—eh?
You wretch! take that, and that, and that, and that!"
Each "that" being followed by a sickening thud
Each that being followed by a sickening thud.

PART III.
The curtain falls on this delightful scene,
As space is precious and will not permit
Of further details; but this goes to show
That things don't always turn out just the same
As those we read about in poets' yarns.
Another thing it shows—that Susan Ann
Had learned a trick when playing at being wed
Upon the seashore in her youthful days
That stood her in good stead in after years—
The wielding of the broomstick here is meant.

Scraps, August 1884.

AFTER TENNYSON'S "GRANDMOTHER."


And Willy, with Franchise horn, is gone to blow in the North!
Sturdy, though white, and strong on his legs, bravely holding forth;
And Willy's wife is with him—she ever was true and wise,
Always a wife for Willy—he often takes her advice.

For madame, you see, is clever; she loves her Franchise Bill,
And he can talk so ready, and manage the Scots with skill.
Pretty enough, very pretty! I won't say against it for one.
Eh! but my Lords shall fear him—when Willy his task has done.

Willy, my beauty, my chieftain true, the flower of the flock,


Never a lord can move him, for Willy stands like a rock.
He has always a word for the weak, for crofter and fellaheen too;
There ne'er was his like in the land, since Eighteen-thirty-two.

Strong for the right, and strong in the fight, strong still in his
tongue;
And peers shall go down before him, though the "feller" is not
young.
Welcome him back, my brothers, from the North land far away,
Soon shall we liberty see, brothers, when Willy has won the day.

JAMES G. MEAGHER.

The Weekly Dispatch, September 14, 1884.


(Parody Competition).

KEEPING TERM AFTER COMMEMORATION.


(Not by A.—T., Esq.)
I by lawns, to check the train
STEAL
Of meditations started
By seeing duns that come in vain
For happy men departed.

By empty rooms I hurry down,


So stumbling down the staircase;
The cads within the sleepy town
Think mine a very rare case.

I hail a boat, and down I row


Along the lonely river,
For other lucky men may go,
But I seem here for ever.

I murmur under moon and stars,


I feel in lunar phrenzy,
I chide the cursèd fate that bars
My exit from B. N. C.

I slope, I slouch, I speed, I stop,


And scan the empty High Street,
I turn me into Boffin's shop,
To cheer me with an ice-treat,

Till ice and sad reflection slow


My diaphragm make quiver,
For other lucky men may go,
But I seem here for ever.

I roam about, and in and out


Poke eyes with envy yellow,
And here and there I spy a scout,
And here and there a fellow.

And here and there a good mamma,


H lli b b i
Her squalling baby nursing,
Looks on me pitying, with an "Ah,
Poor fellow, how he's cursing!"

For, sailor like, I storm and "blow


My eyes" and "timbers shiver,"
That other lucky men may go,
But I seem here for ever.

BRASENOSE COLLEGE, Oxford.

College Rhymes, 1870.

THE MAIDEN'S LAMENT.


After Tennyson (and a long way after, too).
WITH many a care my life's beset,
My charms are growing mellow,
And I have not secured as yet
An eligible fellow.
I sing, I play, and through the dance
I skim like any swallow;
The ladies look at me askance,
And say I'm vain and shallow.
I chatter, chatter as I go,
And some pronounce me clever.
But the men that come they're awfully slow,
And pop the question never, never.
Pop the question never, never,
Pop the question never.

I gad about, and in and out


My hopeless fate bewailing;
And think with secret pain and doubt
Of youth and beauty failing.
A youth there is for whose dear sake
To distant lands I'd travel;
I thought he would an offer make
One evening on the gravel.
He spoke in accents soft and low,
But word of love came never.
The men that come are sure to go,
And some take leave for ever,
Some take leave for ever, ever,
Some take leave for ever.

I strive by many cunning plots,


Their feelings to discover,
And sometimes sweet forget-me-nots
Present to backward lover;
And though with costly gems from far,
I deck my shining tresses
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like