0% found this document useful (0 votes)
23 views

Object Oriented Programming With C Sharma A K download

The document is a comprehensive guide on Object-Oriented Programming (OOP) using C++, authored by A.K. Sharma. It covers fundamental concepts such as classes, objects, inheritance, polymorphism, and advanced topics like exception handling and file management. The book is structured with detailed explanations, examples, and exercises to facilitate learning and understanding of OOP principles.

Uploaded by

visicpubali
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
0% found this document useful (0 votes)
23 views

Object Oriented Programming With C Sharma A K download

The document is a comprehensive guide on Object-Oriented Programming (OOP) using C++, authored by A.K. Sharma. It covers fundamental concepts such as classes, objects, inheritance, polymorphism, and advanced topics like exception handling and file management. The book is structured with detailed explanations, examples, and exercises to facilitate learning and understanding of OOP principles.

Uploaded by

visicpubali
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/ 79

Object Oriented Programming With C Sharma A K

download

https://ebookbell.com/product/object-oriented-programming-with-c-
sharma-a-k-22104554

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Object Oriented Programming With C 4th Edition E Balagurusamy

https://ebookbell.com/product/object-oriented-programming-with-c-4th-
edition-e-balagurusamy-33727398

Object Oriented Programming With C 2e Second Edition Sahay

https://ebookbell.com/product/object-oriented-programming-
with-c-2e-second-edition-sahay-5428484

Object Oriented Programming With C Second 2 Mtsomashekar

https://ebookbell.com/product/object-oriented-programming-with-c-
second-2-mtsomashekar-7293580

Objectoriented Programming With C Ak Sharma

https://ebookbell.com/product/objectoriented-programming-with-c-ak-
sharma-231875260
Object Oriented Programming With C 2140705 Darshan All Unit Darshan
Institute Of Engineering Technology

https://ebookbell.com/product/object-oriented-programming-
with-c-2140705-darshan-all-unit-darshan-institute-of-engineering-
technology-23267614

Deciphering Objectoriented Programming With C A Practical Indepth


Guide To Implementing Objectoriented Design Principles Dorothy R Kirk

https://ebookbell.com/product/deciphering-objectoriented-programming-
with-c-a-practical-indepth-guide-to-implementing-objectoriented-
design-principles-dorothy-r-kirk-46453652

Demystified Objectoriented Programming With C 1st Edition Dorothy R


Kirk

https://ebookbell.com/product/demystified-objectoriented-programming-
with-c-1st-edition-dorothy-r-kirk-23773056

Beginning Objectoriented Programming With C 1st Edition Jack Purdum

https://ebookbell.com/product/beginning-objectoriented-programming-
with-c-1st-edition-jack-purdum-2626948

Beginning Objectoriented Programming With C Sharp Jack Purdum

https://ebookbell.com/product/beginning-objectoriented-programming-
with-c-sharp-jack-purdum-50200364
Object-oriented
Programming with C++

A. K. Sharma
Professor and Dean
Department of Computer Science and Engineering
B. S. Anangpuria Institute of Technology and Management
Faridabad, Haryana, India

Delhi Chennai
Copyright © 2009 Dorling Kindersley (India) Pvt. Ltd.
Licensees of Pearson Education in South Asia

This eBook is licensed subject to the condition that it shall not, by way of trade or otherwise, be lent, resold, hired out, or otherwise
circulated without the publisher’s prior written consent in any form of binding or cover other than that in which it is published
and without a similar condition including this condition being imposed on the subsequent purchaser and without limiting the
rights under copyright reserved above, no part of this publication may be reproduced, stored in or introduced into a retrieval
system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording or otherwise), without the
prior written permission of both the copyright owner and the above-mentioned publisher of this eBook.

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 978-93-325-1583-3
eISBN 978-93-325-4065-1

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

Layout designed by Satwinder Singh Channey


Illustrations by Tarak Sharma
Dedicated
to
all the objects around me
This page is intentionally left blank
CONTENTS

Preface xi
About the Author xiii

1. I NTRODUCTION TO C++ 1
1.1 Introduction—1
1.2 Characters Used in C++—2
1.3 Basic Data Types—2
1.3.1 Data Types Modif ers 3
1.4 C++ Tokens—3
1.4.1 Identif ers 3
1.4.2 Keywords 4
1.4.3 Constants 4
1.4.4 Variables 5
1.5 Input–Output Statements—6
1.6 Structure of a C++ Program—8
1.6.1 Comments 9
1.7 Escape Sequence (Backslash Character Constants)—9
1.8 Operators and Expressions—12
1.8.1 Arithmetic Operators 12
1.8.2 Relational and Logical Operators 13
1.8.3 Conditional Operator 15
1.8.4 Order of Evaluation of Expressions 16
1.8.5 Some Special Operators 16
1.9 Flow of Control—18
1.9.1 The Compound Statement 19
1.9.2 Selective Execution (Conditional Statements) 20
1.9.3 Repetitive Execution (Iterative Statements) 25
1.9.4 Nested Loops 30
1.10 Arrays—31
1.10.1 One-dimensional Arrays 32
1.10.2 Multi-dimensional Arrays 33
1.10.3 Array Initialization 35
1.11 Structures—36
1.11.1 Def ning a Structure in ‘C++’ 36
1.11.2 Arrays of Structures 38
vi Contents

1.11.3 Initializing Structures 38


1.11.4 Assignment of Complete Structures 39
1.11.5 Nested Structures 39
1.12 Functions—40
1.12.1 Function Prototypes 41
1.12.2 Calling a Function 41
1.12.3 Parameter Passing in Functions 42
1.12.4 Returning Values from Functions 46
1.13 I/O Functions—48
1.13.1 getchar( ) and putchar( ) Functions 48
1.13.2 getc( ) and putc( ) Functions 50
1.13.3 gets( ) and puts( ) Functions 50
1.14 Strings—51
1.15 Summary—54
Multiple Choice Questions 54
Answers 56
Exercises 56
Answers 58

2. P OINTERS 59
2.1 Introduction—59
2.1.1 The & Operator 59
2.1.2 The * Operator 60
2.2 Pointer Variables—61
2.2.1 Dangling Pointers 66
2.3 Pointers and Arrays—67
2.4 Array of Pointers—73
2.5 Pointers and Structures—74
2.6 Dynamic Allocation—76
2.6.1 Self Referential Structures 82
2.7 Summary—88
Multiple Choice Questions 89
Answers 89
Exercises 89
Answers 93

3. P ROGRAMMING T ECHNIQUES : A S URVEY 94


3.1 Introduction—94
3.2 Unstructured Programming—95
3.3 Structured Programming—96
3.3.1 Procedural Programming 97
3.3.2 Modular Programming 98
3.4 Drawbacks of Structured Programming—99
Contents vii

3.5 Object-Oriented Programming—101


3.6 Summary—103
Multiple Choice Questions 104
Answers 105
Exercises 105

4. C LASSES AND O BJECTS 106


4.1 Introduction to Objects—106
4.2 Classes—109
4.3 Declaration of Classes in C++—110
4.3.1 Abstraction and Encapsulation 111
4.3.2 Member Function Def nition 112
4.4 Creating Objects—115
4.4.1 Calling Member Functions 116
4.5 Array of Objects—119
4.6 Objects as Function Arguments—121
4.7 Scope Resolution Operator—124
4.8 Static Data Members—129
4.9 Properties of Classes and Objects—131
4.10 Summary—132
Multiple Choice Questions 132
Answers 133
Exercises 133

5. M ORE ON F UNCTIONS : A DVANCED


C ONCEPTS 136
5.1 Polymorphism—136
5.2 Function Overloading—136
5.3 Inline Functions—143
5.4 Friend Functions—146
5.4.1 Member Functions of a Class as Friends
of Another Class 153
5.4.2 Friend Function as a Bridge Between
Two Classes 153
5.5 Friend Classes—157
5.6 Recursion—160
5.6.1 Types of Recursion 167
5.7 Summary—173
Multiple Choice Questions 173
Answers 174
Exercises 174
Answers 176
viii Contents

6. C ONSTRUCTORS AND D ESTRUCTORS 177


6.1 Constructors—177
6.2 Types of Constructors—178
6.2.1 Default Constructor and User
Def ned Constructor 178
6.2.2 Parameterized Constructors 181
6.2.3 Copy Constructor 185
6.2.4 Constructors with Default Arguments 193
6.2.5 Rules for Constructor Def nition and Usage 193
6.3 Destructors—193
6.4 Summary—195
Multiple Choice Questions 195
Answers 196
Exercises 196

7. I NHERITANCE : E XTENDING C LASSES 198


7.1 Introduction to Code Reuse—198
7.2 Containership—198
7.3 Inheritance—204
7.3.1 Visibility Modes 210
7.4 Types of Inheritance—211
7.4.1 Multilevel Inheritance 212
7.4.2 Multiple Inheritance 213
7.5 Function Overriding—214
7.5.1 Virtual Functions 216
7.6 Role of Constructors and Destructors
in Inheritance—226
7.7 Virtual Base Class—230
7.8 Summary—232
Multiple Choice Questions 233
Answers 233
Exercises 233

8. T EMPLATES : C ODE S HARING (G ENERICITY ) 235


8.1 Introduction to Code Sharing—235
8.2 Templates—236
8.3 Generic Classes—240
8.4 Templates with More than One Generic Parameter—243
8.5 Summary—245
Multiple Choice Questions 245
Answers 245
Exercises 245
Contents ix

9. O PERATOR OVERLOADING 247


9.1 Introduction—247
9.2 Operator Overloading—249
9.3 Binary Operators—250
9.3.1 Arithmetic Assignment Operators 255
9.4 Unary Operators—256
9.5 Input/Output Operators—258
9.6 Rules for Operator Overloading—260
9.7 Summary—260
Multiple Choice Questions 261
Answers 261
Exercises 261

10. F ILE H ANDLING I N C++ 262


10.1 File Concepts—262
10.2 Files and Streams—264
10.3 Opening and Closing a File (Text Files)—266
10.3.1 Function get( ) 267
10.3.2 Function getline( ) 269
10.3.3 Function put( ) 272
10.4 Opening the Files by Using Function Open( )—273
10.5 Reading and Writing Blocks
and Objects (Binary Files)—274
10.5.1 Storing Objects in Files 280
10.6 Detecting End of File—284
10.7 Summary—289
Multiple Choice Questions 289
Answers 290
Exercises 290

11. E XCEPTION H ANDLING 292


11.1 Introduction—292
11.2 Traditional Error Handling—292
11.3 Exception Handling in C++—296
11.3.1 Multiple Throw Statements
and Multiple Catch Blocks 299
11.3.2 Throwing Objects 303
11.4 Summary—309
Multiple Choice Questions 309
Answers 309
Exercises 309
x Contents

12. I NTRODUCTION TO U ML 311


12.1 Introduction to Uml—311
12.2 Class Diagrams (Static)—312
12.2.1 Relationships Among Classes 313
12.3 Use Case Diagrams (Static)—316
12.4 Behavioral Diagrams (Dynamic)—318
12.4.1 Interaction Diagrams 318
12.4.2 State Chart Diagrams 320
12.4.3 Activity Diagrams 322
12.5 Implementation Diagrams—324
12.5.1 Component Diagram 324
12.5.2 Deployment Diagram 325
12.6 Summary—326
Multiple Choice Questions 327
Answers 328
Exercises 328

13. P OLYMORPHISM : A R EVIEW 329


13.1 Polymorphism—329
13.2 Taxonomy of Polymorphism—330
13.2.1 Universal Polymorphism 330
13.2.2 Ad Hoc Polymorphism 330

Appendix 333

Index 335
PREFACE

My quest for object-oriented programming (OOP) started at University of Roorkee in Novem-


ber 1989 when my guru Prof. J. P. Gupta asked me the question: “what is object-oriented pro-
gramming?” I did not have a compelling answer at that time. However, I started looking into
the available literature to find the answers. A critical look at the literature revealed that OOP
was more of a philosophy than a programming paradigm. In fact, it is nearer to the oriental
philosophy which states that the world around us is not absolute but relative to an individual’s
capacity to perceive the world around him or her. In fact, whatever we perceive through our
senses is nothing but an object.
When we look around, we find that we are surrounded by objects only. Everything around us,
be it a book, pen, paper, laptop, or even me and you, can all be considered as objects. In fact, any
real-world program has to be a collection of objects. For instance, a program about a university
has to involve objects such as students, professors, clerks, class rooms, books, chalk and mark
sheets. Then, why not write programs using objects, which would be a natural way of creating
useful software comprising of interacting objects.
The programming process has evolved through many phases. The journey started with
programmers who would write programs which somehow worked, without giving importance
to the readability of the program. Languages such as FORTRAN and BASIC neither enforced
any discipline nor were they user-centric. The result was the creation of unstructured programs
that were susceptible to bugs like the Y2K problem acting as time bombs. The major problem
with these programs was that they were not maintainable.
The advent of structured programming techniques did enforce some discipline on the
programmers by way of shunning the use of ‘goto’ statements and encouraging the ‘easy to
read and difficult to write’ style of code statements i.e., choosing long and meaningful names
for the variables, functions, procedures, modules etc. The major emphasis was to use block
structures in the program. For instance, any code enclosed between a pair of curly braces was
termed as a block. Pascal and ‘C’ supported blocks such as compound statements, loops, func-
tions, procedures, and files. This technique worked well for hardcore programmers, who were
able to write large and complex programs using structured programming techniques. The Unix
operating system was written using ‘C’.
Nevertheless, procedures that helped to solve the problem at hand were emphasized. For a
developer, algorithm development consumed more time while data was given least importance.
Thus, a program turned out to be a collection of decomposed components i.e., interacting func-
tions or modules exchanging data and data structures among them. Such data, especially the
global data, was vulnerable to inadvertent corruption by the fellow programmers.
xii Preface

The above-mentioned drawbacks are remedied by paying more attention to data and trying
to create reusable software components. The reusable components can further be combined to
get bigger and more powerful software. In our day-to-day life, we create bigger objects from
smaller objects. For example, the desktop computer is made up of many smaller objects such as
the mother board, RAM, HDD, SMPS, the mouse and the keyboard. We utilize the functions of
these objects without being keen to understand how they work or who made them.
OOP is a paradigm shift in programming that defines, creates, and manipulates objects to de-
velop reusable software. C++ is an imperative language developed to support OOP components
and features such as classes, objects, abstraction, encapsulation, inheritance, and polymorphism.
I have taught OOP at I.I.I.T.M Gwalior, JMI Delhi, YMCAUST Faridabad, and BSAITM
Faridabad. And at these institutions, there has been a consistent demand from my students and
fellow teachers to write a book on this subject.
Object-oriented programming with C++ has been written to help the readers look at OOP
as a philosophy and think of the problem at hand as a collection of objects. It helps the reader
to identify the classes to which the objects belong and also establish the relationship among the
classes.
C++ supports the creation and manipulation of OOP components and tools such as classes,
objects, abstraction, encapsulation, code reuse, code sharing, and polymorphism. Hence, the
book introduces C++ as an object-oriented programming language.
UML is an object-oriented modelling language. An introduction to UML has been given
with a view to acquaint the reader with various graphical tools offered by UML to represent
OOP components.
This book would not have been possible without the good wishes, comments and suggestions
I had received from many significant people. I place on record my thanks to Dr Atul Mishra,
Dr Jyoti, Dr Anuradha Pillai, Dr Naresh Chauhan, Dr Rahul Rishi, Dr Divya Jyoti, and
Sh. Pawan Bhadana. In fact, Dr. Atul Mishra has already taught his odd-semester class of 2013
using the proofs of this book.
I am indebted to my teachers and research guides Prof. J. P. Gupta, Prof. Padam Kumar,
Prof. Moinuddin, and Prof. D. P. Agarwal for their encouragement. I am also thankful to
my friends Prof. Ashok De, Prof. Qasim Rafiq, Prof. Rajender Sahu, Prof. N. S. Gill, and
Prof. S. S. Tyagi for their support.
I commend the excellent job done by the team at Pearson Education, which made this
beautiful book happen.
My parents always encouraged me and gave me all the strength I needed. And not to miss the
everlasting companionship of the two most important people in my life, I convey my heartfelt
thanks to my wife Suman and daughter Sagun for their support throughout.
While this book has been written with meticulous care, it is possible that some errors might
have unwittingly crept in. I shall be grateful if they are brought to my notice. I shall also be
happy to acknowledge suggestions for further improvement of this book.

A. K. Sharma
ABOUT THE AUTHOR

A. K. Sharma is currently Professor (CSE) and Dean (PG and


Research) at B. S. Anangpuria Institute of Technology and
Management. Earlier, he was Professor and Dean, Faculty of
Engineering and Technology, YMCA University of Science and
Technology, Faridabad.
A member of the board of studies and academic council of
several renowned universities, Dr Sharma has guided more than
twenty students in doctoral programs leading to their Ph.D.
degrees. He has published more than 250 research papers in na-
tional and international journals of repute and made presenta-
tions in numerous academic conferences. He heads a group of
researchers actively working on the design of Web crawlers.
This page is intentionally left blank
INTRODUCTION TO 1
C++
1.1 INTRODUCTION
The ‘C’ programming language was created as a structured programming tool for writing large
and complex system programs such as operating systems. No wonder that in 1973, Unix operat-
ing system was developed using ‘C’. The software developers liked ‘C’ because of its charac-
teristics such as speed, compactness, and ability to harness the power of the hardware through
low-level features.
Niklaus Wirth has defined that a program is composed of two components Algorithms and
Data structures, as given below:
Algorithms + Data Structures = Programs

Thus, there can be two approaches towards the development of software, i.e. to develop pro-
grams either centered around functions or with an emphasis given to data. The structured/
top-down/modular programming was focussed on functions, with less importance given to
the associated data. On the contrary, object oriented paradigm of programming, developed in
1960s, focused on data instead of functions.
Simula 67 was the first Object Oriented Programming language developed in 1960s. It was
followed by Smalltalk in 1970s.
In 1980s the computing world grew at a tremendous rate and the need for thousands of
system programmers was felt. Whereas the number of hard core ‘C’ programmers who could
write and manage large and complex programs was hopelessly less. It was found that the struc-
tured programming itself had flaws and limitations, as there was no inherent support for code
reusability, sharing, and extensibility. Therefore, it became necessary to develop a new pro-
gramming language that could support fast development of extremely large, complex, and
extendable software.
In 1983, Bjarne Stroustrup created C++ on the principles of object-oriented programming.
It supported much-required features such as code reusability, extensibility, sharing and variety
of polymorphism. Obviously, it was quickly adapted by programmers mainly because of its
support for inheritance.
A comparison of various programming paradigms is provided in Chapter 2.
It may be noted that in addition to the Object Oriented Programming features, almost all the
procedural programming features are available in C++. For instance, C++ supports basic data
2 Object-oriented Programming with C++

types (int, float, char, etc.), control structures, pointers, files, etc. Therefore, to start with, non-
object oriented features of C++ are discussed in the following sections.

1.2 CHARACTERS USED IN C++


The set of characters allowed in C++ consists of alphabets, digits, and special characters as
listed below:
1. Letters: both lower case and upper case letters of English:
A, B, C, … X, Y, Z.
a, b, c, …, x, y, z.
2. Decimal digits:
0,1, 2, …, 7, 8, 9.
3. Special characters:
!, *, +, \, “, <, #, (, =, {, >, %, ), ~, :, }, /, ^, −, [, &, ], ?, ‘, ., blank.

1.3 BASIC DATA TYPES


Every program specifies a set of operations to be carried out on some data in a particular
sequence. The data can be of many types such as numbers, characters, Boolean, etc. In fact a
data type defines the range of values and the set of operations that could be applied on that type
of data. The range of values allowed for a data type depends upon the number of bytes allocated
for its storage by the system. For example, one byte of allocation allows values ranging from
−128 to +127 and two bytes allow values ranging from −32,768 to +32,767.
The basic data types supported by C++ are integer, floating point, and character types. A
brief discussion on these types is given below:
1. Integer (int). An integer is an integral whole number without a decimal point. These
numbers are used for counting. Examples of some valid integers are 525, 28, −24, 571,
209, −9.
C++ supports two types of integers: ‘int’ and ‘long’. These types are used for normal
and extremely large values of counting numbers, respectively. The range of values that
can be held in these data types is given in Table 1.1.
2. Floating point (float). A floating point number has a decimal point. Even if it has an
integral value, it must include a decimal point at the end. These numbers are used
for measuring quantities. Examples of some valid floating point numbers are 435.21,
−987.1, 123., 0.435.
C++ supports three types of floating points: ‘float’, ‘double’, ‘long double’. They can
hold values in the increasing order of precision as given in Table1.1
3. Character (char). It is a non-numeric data type consisting of a single alphanumeric
character. Examples of some valid characters are ‘X’, ‘9’, ‘r’, ‘V’, ‘&’, etc.
It may be noted that the data items: ‘9’ and 9 are of different types. The former is of type
char and later of type int.
Introduction to C++ 3

4. void. It is a special type that represents an empty set of different data types. No object
can be defined of type void. At this moment, it is not worthwhile to discuss more on this
data type. We shall discuss more on this type later in the book especially when we reach
a stage where it can be used.

1.3.1 Data Types Modifiers


The range of values supported by a particular data type can be very large. A data type modifier
can be used by programmer to refer to different sub-ranges of the values supported by a data
type. The various data modifiers, their associated data types, range of values, and memory size
occupied in bytes are tabulated in Table 1.1.

Table 1.1 Data Type Modifiers and Range of Values

Data Type Modifier Range of Values Memory Size (bytes)


Integer short −32,768 to 32,767 2
signed short −32,768 to 32,767 2
unsigned short 0–65,535 2
int Same as short 2
unsigned int Same as unsigned short 2
signed int Same as signed short 2
long −2,147,438,648 to 2,147,438,647 4
Floating point float 3.4 * 10−38 to 3.4 * 1038 4
double 1.7 * 10−308 to 1.7 * 10308 8
long double 3.4 * 10−4932 to 3.4 * 104932 10
Character char −128 to 127 1
signed char −128 to 127 1
unsigned char 0 to 255 1

1.4 C++ TOKENS


A token is a group of characters that belong together. It is the lowest level of semantic unit of
C++. Therefore, any sentence or statement written in C++ must contain tokens such as if, +,
1008, for, while, etc. C++ supports the following types of tokens:
■ Identifiers
■ Keywords
■ Constants
■ Operators

1.4.1 Identifiers
An identifier is a symbolic name that is used to identify and refer to data items or objects used
by a programmer in his/her program. For example, if it is desired to store a value (say 27) in a
memory location then the programmer must choose a symbolic name (say Num) and perform
the following assignment:
4 Object-oriented Programming with C++

Num = 27;
The symbol ‘=’ is an assignment operator that stores the value ‘27’ into a memory location
called ‘Num’ as shown in Fig. 1.1. The character ‘;’ marks the end of a statement and therefore
it is called a statement terminator.
Num

Num = 27; 27

Figure 1.1 Identifier ‘Num’ is being assigned the value ‘27’

As defined earlier, an identifier is a token, i.e. a sequence of characters taken from C++
character set. The rules of formation of C++ identifiers are given below:
1. An identifier can consist of alphabets, digits, and/or underscore. However special char-
acters such as space, comma etc., are not allowed to be included in an identifier name.
2. It must not start with a digit.
3. C++ is case sensitive language, i.e. upper case and lower case letters are considered
different from each other. However, the identifier name can be a combination of upper-
case and lower case letters.
4. An identifier name can start with an underscore.
Examples of some acceptable identifiers are:
salary
basicPay
_bit
age_of_student
sri1008
Examples of some unacceptable identifiers are:
Salary (blank not allowed)
Basic,Pay (special characters such as ‘,’ not allowed)
345bit (first character cannot be a digit)

It may be noted that salary and Salary are two different identifiers.

1.4.2 Keywords
A keyword is a reserved word of C++. This cannot be used as an identifier in a program. The set
of C++ keywords is given in Appendix.

1.4.3 Constants
A symbolic name or identifier, which does not change its contents during execution of a program
is known as a constant. Any attempt to change the contents of a constant will result in an error
message. The C++ constant can be of any basic data types, i.e. integer constants, floating point
constants, and character constants.
Introduction to C++ 5

const qualifier can be used to declare a constant as shown below:


const float Pi = 3.1415;

The above declaration means that identifier ‘Pi’ is a floating point constant having a fixed value
equal to 3.1415.
Examples of some valid constant declarations are:
const int rate = 50;
const float Pi = 3.1415;
const char ch = ‘A’;

It may be noted that a character sequence enclosed within double quotes is called as a string
literal. For instance the character sequence, “saiRam” is a string literal. When a string literal is
assigned to an identifier, declared as a constant, then it is known as a string constant.

1.4.4 Variables
A variable is an identifier. It is the most fundamental aspect of any computer language. It is a
location in the memory whose contents can change. It is given a symbolic name for easy refer-
ence. To understand this concept, let us have a look at the following statements:
1. total = 500.25;
2. net = total – 100;
In statement number (1) a value 500.25 is being assigned to a variable called total. The variable
total is used in statement number (2) wherein the result of the expression on right-hand side
(total – 100) is being assigned to another variable called net, appearing on the left-hand side of
‘=’, the assignment operator. The point worth noting is that the variable ‘total’ is being referred
by its name in statement (2) but not by its content. In fact, all variables are referred to by their
names and not by their contents. This important feature of variables makes them a powerful tool
in the hands of a programmer.
However, a variable needs to be defined of a particular type before it is used in a program. This
activity enables the compiler to make available the appropriate amount of memory for the given
type of the variable asked by the programmer. The definition of variable has the following format:
<data type> <variable name>;

where <data type> is the type of data to be stored and <variable name> is the user defined name
of the variable.
For example, a variable called ‘roll’ of type integer can be defined as:
int roll;

Similarly, a variable called ‘salary’ of type float can be defined as:


float salary;

Examples of some valid variable declarations are:


1. char ch;
2. int i, j, k;
6 Object-oriented Programming with C++

3. float payMonth;
4. int rollStudent;
5. long num;
C++ also allows initialization of a variable with a value at the time of declaration. For example,
the variable called ‘sum’ of type int can be initialized to a value 100 as shown below:
int sum = 100;

1.5 INPUT–OUTPUT STATEMENTS


Input–output statements are program instructions used for interaction of data and messages
with the user of the program and/or input-output devices. Input statements are used to provide
data to the program. Output statements are used to display data on the screen. These statements
can also be used to store the data on auxiliary devices such as hard disk, pen-Ram, etc.
In hills, the villagers bring an input stream of water underneath their houses from a river as
shown in Fig. 1.2. The water for the kitchen is taken from the input stream and the waste water
is let out into the output stream.

River

Input Stream

Output Stream

Figure 1.2 Input and output streams of water for houses in hills

Likewise, C++ also maintains input and output streams. The input and output devices are
attached to the input and output streams, respectively, as shown in Fig. 1.3.
Memory
Input Stream
>>
Get From
Keyboard Operator
Mouse
LCD Monitor
Printer

<<
Output Stream Put to
Operator

Figure 1.3 Input–output streams in C++


Introduction to C++ 7

cin is the standard input stream (keyboard) and it can be used to input a value entered by the
user from the keyboard. However, cin uses a get from operator (i.e. >>) to get the typed value
from keyboard. The value is stored at a designated location of a variable in the main memory.
Let us consider the following program segment:
int marks;
cin >> marks;

In the above segment, the user has defined a variable called marks of integer type in the first
statement and in the second statement he/she is asking to read a value from the keyboard into
marks. Once this set of statements is obeyed by the computer, whatever is typed on the keyboard
(say 98) is received by the input stream cin which then hands over the received value to (get
from operator) >>. The operator stores the value in the corresponding memory location called
marks as shown in Fig. 1.4.
Main Memory

cin >> Marks ≡ 98

Figure 1.4 Value inputted to a variable marks through cin

cout is the standard output stream (visual display unit) and it can be used to display a value stored
in a variable onto a display device such as an LCD display. Similar to cin, cout also uses a put to
operator (i.e. <<) to extract the value from the variable. The value is then sent to the LCD display.
The contents of the variable (marks) can be displayed on the screen by the statement given
below:
cout << marks;

The output of the above statement will be displayed on the screen as:
98

A message can be displayed on the screen as text enclosed within parentheses. Let us consider
a situation where a user desires to display a message “My first attempt” on the screen. This can
be achieved through the following statement:
cout << “My first attempt”;

Once the above statement is executed by the computer, the following message will appear on
the screen.
8 Object-oriented Programming with C++

My first attempt

Similarly, the following program segment defines a variable some of integer type, initializes it
to a value 500 and displays the contents of the variable on the screen
:
int some;
some = 500;
cout << “The value of variable some =”;
cout << some;
:
Once the above program segment is executed by the computer, the following output is displayed
on the screen:
The value of variable some = 500

In fact, we can also use more than one output or put to operators within the same output state-
ment as shown below. This activity is known as cascading of operators:
cout << “The value of variable some = ” << some;

Similarly, cascading of get from operators can also be done with a cin statement. For example,
the following statement would input three variables val1, val2, and val3 from the keyboard.
cin >> val1 >> val2 >> val3;

Note: A stream acts as an interface between the Input/Output (I/O) system of the oper-
ating system and the program. This helps in making I/O statements independent of the actual
physical devices attached to the system.

1.6 STRUCTURE OF A C++ PROGRAM


Every program written in C++ must follow the format or structure specified by the language.
The general structure of a C++ program is given below:
# include <header file>
main( )
{
..........;
..........;
..........;
}

It may be observed that the C++ program starts with a function called main( ). The body of the
function is enclosed between curly braces. These braces are equivalent to Pascal’s BEGIN and
END keywords. The program statements are written within the braces. Each statement must end
by a semicolon (the statement terminator).
A C++ program may contain as many functions as required. However, when the program is
loaded in the memory, the control is handed over to function main( ) and it is the first function
to be executed.
Introduction to C++ 9

Let us now write our first program:


#include <iostream.h>
void main( )
{
cout << “My first attempt”;
}
When the above program is executed the following output is displayed on the visual display unit
(VDU) screen.
My first attempt

It may be noted here that the statement # include <iostream.h>, has been placed at the top of
the program. This is one of the header files defined by C++. It contains declarations for stan-
dard library functions for stream I/O.

1.6.1 Comments
A comment can be added to the program by enclosing the text between the pair: /* ... */, i.e. /*
indicates the beginning of the comment and */marks the end of it. For example, the following
line is a comment:
/* This is my first program */

A single line comment can be added in a C++ program by using double slash sequence (//) as
shown in the following program:
// This is my first program
#include <iostream.h>
void main( )
{
cout << “My first attempt”;
}
It may be noted here that a comment is a non-executable statement in the program.

1.7 ESCAPE SEQUENCE


(BACKSLASH CHARACTER CONSTANTS)
‘C++’ has some special character constants called backslash character constants. These are
unprintable ASCII characters that can perform special functions in the output statements. A
back slash character constant is nothing but a back slash (‘\’) character followed by another
character.
For example, “\n” can be used in a cout statement to send the next output to the beginning
of the next line.
Consider the following program:
#include <iostream.h>
void main( )
10 Object-oriented Programming with C++

{
cout << “Our body has five Koshas as given below:”;
cout << “Anna, Prana, Mann, Gyan, and Anand”;
}
The output of this program would be:
Our body has five Koshas as given below: Anna, Prana, Mann,
Gyan, and Anand

It may be noted that though two separate cout statements were written in the above program, the
output has been displayed on the same line.
In order to display the text in two lines, the “\n” character constant should be placed either
at the end of the text in the first cout statement or at the beginning of the text in the second cout
statement.
Consider the following modified program:
#include <iostream.h>
void main( )
{
cout << “Our body has five Koshas as given below:”;
cout << “\n Anna, Prana, Mann, Gyan, and Anand”;
}
The character constant “\n” has been placed at the beginning of the text of the second cout state-
ment and therefore the output of the program would be:
Our body has five Koshas as given below:
Anna, Prana, Mann, Gyan, and Anand

Some important backslash constants are listed below:

Backslash Character Constant Meaning


\t Tab
\b Backspace
\a Bell (alert)
\n Newline character

Note: The backslash characters are also known as escape sequences. Such characters
can be used within apostrophes or within double quotes.
A brief discussion on these backslash characters follows:
1. ‘\t’ (Tab): this character is called as a tab character. Wherever it is inserted in an output
statement, the display moves over to the next present tab stop. Generally a tab is of 8
blank spaces on the screen. An example of usage of character ‘\t’ is given below:
#include <iostream.h>
void main( )
Introduction to C++ 11

{
cout << “\n \tAnna \tPrana \tMann \tGyan \tAnand”;
}

The output of the above statement would be on the new line with spacing as shown
below:
Anna Prana Mann Gyan Anand
2. ‘\b’ (Backspace): this character is also called as backspace character. It is equivalent to
the backspace key symbol (←) available on the computer or typewriter. It moves one
column backward and positions the cursor on the character displayed on that column. An
example of usage of character ‘\b’ is given below:
#include <iostream.h>
void main( )
{
cout << “\n ASHOKA\b?”;
}

The output of the above statement would be:


ASHOK?
We can see that the trailing letter ‘A’ has been overwritten by the character ‘?’ at the end of
the string constant <ASHOKA> the reason being: ‘\b’ moved the cursor one column back-
ward, i.e. at ‘A’ and the cout statement printed the character ‘?’ on that column position.
3. ‘\a’ (Alert): this character is also called as alert or bell character. Whenever it is inserted
in an output statement, it sounds a bell which can be heard by the user sitting on com-
puter terminal. It can be used in a situation where the programmer wants to catch the
attention of the user of this program. An example of usage of ‘\a’ character is given
below:
#include <iostream.h>
void main( )
{
cout << “\n Error in data \a”;
}

The output of the above statement would be the following message on the screen and
thereafter sounding of a bell on the system speaker.
Error in data
4. ‘\n’ (new line): as discussed earlier, this character is called as newline character. Wher-
ever it appears in the output statement, the immediate next output is taken to the begin-
ning of the next new line on the screen. Consider the program given below:
#include <iostream.h>
void main( )
{
cout << “\n This is \n a test”;
}
12 Object-oriented Programming with C++

The output of this program would be:


This is
a test

1.8 OPERATORS AND EXPRESSIONS


An operator is a symbol or letter used to indicate a specific operation to be carried out on
variables in a program. For example, the symbol ‘+’ is an add operator that adds two data items
called operands.
An expression is a combination of operands (i.e. constants, variables, numbers, etc.) con-
nected by operators and parenthesis. For example, in the expression given below, A and B are
operands and ‘+’ is an operator.
A + B

C++ supports three basic types of operators: arithmetic, relational, and logical. An expression
that involves arithmetic operators is known as an arithmetic expression. The computed result of
an arithmetic expression is always a numerical value. The expression which involves relational
and/or logical operators is called a Boolean expression or logical expression. The computed
result of such an expression is a logical value, i.e. either 1 (True) or 0 (False).
The rules for formation of an expression are:
1. A signed or unsigned constant or variable is an expression.
2. An expression connected by an operator to a variable or a constant is an expression.
3. Two expressions connected by an operator is also an expression.
4. Two operators should not occur in continuation.

1.8.1 Arithmetic Operators


The valid arithmetic operators supported by C++ are given in Table 1.2.

Table 1.2 Arithmetic Operators

Symbol Stands For Example


+ Addition x+y
− Subtraction x−y
* Multiplication x*y
/ Division x/y
% Modulus or remainder x%y
−− Decrement −−x
x−−
++ Increment ++x
x++
Introduction to C++ 13

1.8.1.1 Unary Arithmetic Operators


A unary operator requires only one operand or data item. The unary arithmetic operators
supported by C++ are, unary minus (‘−’), increment (‘++’), and decrement (‘−−’). As compared
to binary operators, the unary operators are right associative in the sense that they evaluate from
right to left.
The unary minus operator is written before a numerical value, variable or an expression.
Examples of usage of unary minus operator are given below:

(i) -57; (ii) -2.923; (iii) -x; (iv) -(a * b); (v) 8 * (-(a + b))

It may be noted here that the result of application of unary minus on an operand is the negation
of its operand.
The operators ‘++’ and ‘−−’ are unique to C and C++. These are called increment and decre-
ment operators, respectively. The increment operator ++ adds 1 to its operand. Therefore, we
can say that, the following expressions are equivalent.

i = i + 1 ≡ ++i;

For example, if the initial value of i is 10 then the expression ++i will increment the contents of
i to 11. Similarly, the decrement operator −− subtracts 1 from its operand. We can say that, the
following expressions are equivalent:

j = j − 1 ≡ −−j ;

For example, if the initial value of j is 5 then the expression −−j will decrement the contents of
j to 4.
The increment and decrement operators can be used both as a prefix and postfix to a variable
as shown below:

++x or x ++
−−y or y−−

As long as the increment or decrement operator is not used as part of an expression, the prefix
and postfix forms of these operators do not make any difference. For example, ++ x and x ++
would produce the same result. However, if such an operator is part of an expression then the
prefix and postfix forms would produce entirely different results.
In the prefix form the operand is incremented or decremented before the operand is used in
the program.

1.8.2 Relational and Logical Operators


A relational operator is used to compare two values and the result of such an operation is always
logical, i.e. either true or false. The valid relational operators supported by C++ are given in
Table 1.3.
14 Object-oriented Programming with C++

Table 1.3 Relational Operators

Symbol Stands For Example


> Greater than x>y
>= Greater than equal to x >= y
< Less than x<y
<= Less than equal to x <= y
== Equal to x == y
!= Not equal to x != y

A logical operator is used to connect two relational expressions or logical expressions. The
result of such an operation is always logical, i.e. either true or false. The valid logical operators
supported by C++ are given in Table 1.4.

Table 1.4 Logical Operators

Symbol Stands For Example


&& Logical AND x && y
|| Logical OR x || y
! Logical NOT !x

Rules of logical operators:


1. The output of a logical AND operation is true if its both the operands are true. For all
other combinations the result is false.
2. The output of logical OR operation is false if both of its operands are false. For all other
combinations the result is true.
3. The logical NOT is a unary operator. It negates the value of the operand.
For initial value of x = 5 and y = 7, consider the following expression
(x < 6) && (y > 6)

The operand x < 6 is true and the operand y > 6 is also true. Thus, the result of above given
logical expression is also true. However, the result of following expression is false because one
of the operands is false:
(x < 6) && (y > 7)

Similarly, consider the following expression:


(x < 6) || (y > 7)

The operand x < 6 is true whereas the operand y > 7 is false. Since these operands are connected
by logical OR, the result of this expression is true (Rule 2). However, the result of following
expression becomes false (negation of true).
Introduction to C++ 15

!(x < 6) || (y > 7)

Note: The expression on the right-hand side of logical operators && and ||, does not get
evaluated in case the left-hand side determines the outcome.
Consider the expression given below:
x && y
If x evaluates to false (zero) then the outcome of above expression is bound to be false irrespec-
tive of y evaluating to any logical value. Therefore, there is no need to evaluate the term y in the
above expression.
Similarly, in the following expression, if x evaluates to true (non-zero) then the outcome is
bound to be true. Thus, y will not be evaluated.
x || y

1.8.3 Conditional Operator


C++ provides a conditional operator (? :) which can help the programmers in performing simple
conditional operations. It is represented by the symbols ‘?’ and ‘:’. For example, if one desires
to assign the bigger of two variables x and y to a third variable z the conditional operator is an
excellent tool. The general form of this operation is:
E1 ? E2 : E3

where E1, E2 and E3 are expressions.


In the conditional operation, the expression E1 is tested, if E1 is true then E2 is evaluated
otherwise the expression E3 is evaluated as shown in Fig. 1.5.
true

E1 ? E2 : E3

false

Figure 1.5 Conditional operation

Consider the following conditional expression:


z = (x > y) ? x : y;
The expression x > y is evaluated. If x is greater than y, then z is assigned x otherwise z gets y.
Examples of valid conditional expressions are:
(i) y = (x >= 10) ? 0 : 10;
(ii) Res = (i < j) ? sum + i : sum + j;
(iii) q = (a = = 0) ? 0 : (x/y);
16 Object-oriented Programming with C++

It may be noted here that the conditional operator (? :) is also known as a ternary operator
because it operates on three values.

1.8.4 Order of Evaluation of Expressions


A number of logical and relational expressions can be linked together with the help of logical
operators as shown below:
(x < y) || (x > 20) && !(z) || ((x < y) && (z > 5))

For the above complex expression, it becomes difficult to make out as to in what order the
evaluation of sub-expressions would take place.
In C++, the order of evaluation of an expression is carried out according to the operator
precedence given in Table 1.5.

Table 1.5 Operator Precedence

Operators Priority Associativity


− ++ −− ! Highest Right to left
*/% Left to right
+− Left to right
< <= > >= Left to right
== != Left to right
&& Left to right
|| Lowest Left to right

It may be noted here that in C++, false is represented as zero. True is represented as any non-zero
value. Thus, expressions that use relational and logical operators return either 0 (false) or 1 (true).

1.8.5 Some Special Operators


There are many other operators in C++. In this section, the two frequently used operators: sizeof
and comma operators have been discussed.

1.8.5.1 sizeof( ) Operator


C++ provides a compile time unary operator called sizeof. When applied on an operand, it
returns the number of bytes the operand occupies in the main memory. The operand could be a
variable, a constant or a data type. For example, the following expressions:
a = sizeof(“sum”);
b = sizeof(char);
c = sizeof(123L);
would return the sizes occupied by arguments: sum, data type char and constant ‘123L’ on your
machine. It may be noted that
Introduction to C++ 17

(i) The parentheses used with sizeof are required when the operand is a data type. With
variables or constants, the parentheses are not necessary.
(ii) sizeof( ) operator has the same precedence as prefix increment/decrement operators.

Example 1. Write a program that illustrates the usage of sizeof( ) operator.


Solution: We would print the values of a, b, and c which contain the size of arguments:
“sum”, data type char and constant ‘123L’ respectively. The required program is given below:
// The usage of sizeof operator
# include<iostream.h>
void main( )
{
int a, b, c;
a = sizeof (“sum”);
b = sizeof (char);
c = sizeof (123L);
cout << “\n size of string : ‘sum’ = “<< a <<” bytes”;
cout << “\n size of data type : char = “<< b <<” bytes”;
cout << “\n size of number : 123L= “<< c <<” bytes”;
}

The output of the program is given below:


size of the string : ‘sum’ =4 bytes
size of the data type :char =1 bytes
size of number : 123L=4 bytes_

1.8.5.2 Comma Operator


The comma operator is used to string together a number of expressions which are performed in
a sequence from left to right.
For example, the following statement
a = (x = 5, x + 2);
executes in the following order
(i) value 5 is assigned to variable x;
(ii) x is incremented by 2;
(iii) the value of expression x + 2 (i.e. 7) is assigned to the variable a.
The following points may be noted regarding comma operators:
1. A comma-separated list of expressions is always evaluated from left to right.
18 Object-oriented Programming with C++

2. The final data type of a comma-separated list of expressions is always same as the data
type of the rightmost expression in the list.
3. The comma operator has the lowest precedence among all C++ operators.

1.8.5.3 Assignment Operator


Statements are the smallest executable units of a C++ program and each statement is terminated with
a semicolon. An assignment statement assigns the value of the expression on the right-hand side to a
variable on the left-hand side of the assignment operator (=). Its general form is given below:
<variable name> = <expression>;

The expression on the right-hand side could be a constant, a variable or an arithmetic, relational,
or logical expression. Some examples of assignment statements are given below:
a = 10;
a = b;
a = b * c;
(i) The assignment operator is a kind of a store statement, i.e. the computed value of the
expression on the right-hand side is stored in the variable appearing on the left-hand side
of the assignment operator. The variable on the left-hand side of the assignment operator
is also called lvalue and is an accessible address in the memory. Expressions and con-
stants on the right-hand side of the assignment operator are called rvalue.
(ii) The assignment statement overwrites the original value contained in the variable on the
left-hand side with the new value of the right-hand side.
(iii) Also the same variable name can appear on both the sides of the assignment operator as
shown below:
count = count +1;
(iv) Multiple assignments in a single statement can be used specially when same value is to
be assigned to a number of variables.
a = b = c = 30;
These multiple assignment statements work from right to left and at the end all variables
have the same value. The above statement assigns the value (i.e. 30) to all variables c, b,
and a. However, the variables must be of same type.
(v) A point worth nothing is that C++ converts the type of value on the right-hand side to the
data type on the left.

1.9 FLOW OF CONTROL


A statement is the smallest executable unit of a C++ program. It is terminated with a semicolon.
It is an instruction given to the computer to perform a particular task like reading input, display-
ing output, evaluating an expression, etc.
A single statement is also called as a simple statement. Some examples of simple statements
are given below:
Introduction to C++ 19

(i) int a = 100;


(ii) S = S + a;
(iii) count ++;
A statement can also be an empty or null statement as shown below:
;
The high-level languages such as Pascal, C, and C++ have been designed for computers based
on Von-Neumann architecture. Since this architecture supports only sequential processing, the
normal flow of execution of statements in a high-level language program is also sequential, i.e.
each statement is executed in the order of its appearance in the program. For example in the fol-
lowing C++ program segment, the order of execution is sequential from top to bottom:
x = 10;
y = 20; Order of execution
z = x + y;
:
The first statement to be executed is ‘x = 10’, and the second statement is ‘y = 20;’. The execution
of statement ‘z = x + y’ will take place only after the execution of the statement ‘y = 20’. Thus,
the processing is strictly sequential. Moreover, every statement is executed one and only once.
Depending upon the requirements of a problem, it is often needed to alter the normal
sequence of execution in the program. This means that we may desire to selectively and/or
repetitively execute a program segment. A number of ‘C++’ control structures, are available
for controlling the flow of processing. These structures are discussed in the following sections.

1.9.1 The Compound Statement


A compound statement is a group of statements separated from each other by a semicolon. The
group of statements, also called a block of code, is enclosed between a pair of curly braces,
i.e. ‘{’ and ‘}’. The significance of a block is that the sequence of statements enclosed in it, is
treated as a single unit. For example, the following group of statements is a block.
/* a block of code */
{
cin >> a >> b;
c = a + b;
cout << c;
}

One compound statement can be embedded in another as shown below:


{
:
{
:
}
:
}
20 Object-oriented Programming with C++

In fact, the function of curly braces ‘{’ and ‘}’ in a C or C++ program is same as the function of
Begin and End, the reserved words in Pascal. C and C++ call these braces as delimiters.

1.9.2 Selective Execution (Conditional Statements)


In some cases, it is desired that a selected segment of a program be executed on the basis of a
test, i.e. depending upon the state of a particular condition being true or false. In C++, ‘if state-
ment’ is used for selective execution of a program segment.

1.9.2.1 The if Statement


This statement helps us in the selection of one out of two alternative courses of action. The
general form of if statement is given below:
if (expression)
{
statement sequence
}
where ‘if ’ is a reserved word; expression is a Boolean expression enclosed within a set of
parentheses. These parentheses are necessary even if there is a single variable in the expression.
Statement sequence is either a simple statement or a block. However, it cannot be a declaration.
Examples of acceptable if statements are:
(i) if (A > B) A = B;
(ii) if (total < 100) {
total = total + val;
count = count + 1;
}
(iii) if ((Net > 7000) && (I_tex == 500)) {
:
}

1.9.2.2 The if–else Statement


It may be observed from the above examples that the simple if statement does nothing when the
expression is false. An if–else statement takes care of this aspect.
The general form of this construct is given below:
if (expression)
{
statement sequence1
}
else
{
statement sequence2
}
Introduction to C++ 21

where ‘if ’ is a reserved word; expression is a Boolean expression, written within parentheses;
statement sequence1 can be a simple or a compound statement; ‘else’ is a reserved word; state-
ment sequence2 can be a simple or a compound statement.
Examples of if–else statements are:
(i) if (A > B) C = A;
else C = B;
(ii) if (x == 100)
cout << “Equal to 100”;
else
cout “\n Not Equal to 100”;
It may be noted here that both the if and else parts are terminated by semicolons.

Example 2. Write a program that reads a year and determine whether it is a leap year or not.
Solution: We know that a year is leap if it is evenly divisible by 4 or 400. However, a century
year such as 1900 is not a leap year. Thus, it should not be divisible by 100. The program for
this problem is given below:
//This program determines whether an input
//year is a leap year or not
#include <iostream.h>
# include <conio.h>
void main( )
{
int leapyear;
clrscr( );
cout << “Enter the year =”;
cin >> leapyear;
//check if it is divisible by 4 & not divisible by 100
// or divisible by 400
if ((leapyear % 4 == 0)&&(leapyear % 100 != 0)
|| (leapyear % 400 == 0))
cout << leapyear << “is a leap year\n”;
else
cout << leapyear << “is not a leap year \n”;
}
Sample outputs are given below:
Enter the year =2000
2000 is a leap year
Enter the year =2006
2006 is not a leap year
22 Object-oriented Programming with C++

1.9.2.3 Nested if Statements (if–else–if ladder)


The statement sequence of if or if–else may contain another if statement, i.e. the if–else
statements can be nested within one another as shown below:
if (exp1)
if (exp2)
{
:
}
else
if (exp3)
{
:
}
else
{
:
}
It may be noted here that sometimes the nesting may become complex in the sense that it
becomes difficult to decide “which if does the else match”. This is called as “dangling else
problem”. The ‘C++’ compiler follows the following rule in this regard:
Rule: each else matches to its nearest unmatched preceding if.
Consider the following nested if:
if (x < 50) if (y > 5) Net = x + y; else Net = x - y;

In the above statement, the else part matches the second if (i.e. if (y > 5)) because it is the near-
est preceding if. It is suggested that the nested ifs should be written with proper indentation. The
else(s) should be lined up with their matching if(s). Nested if(s) written in this fashion are also
called if–else–if ladder. For example, the nested if given above should be written as:
if (x < 50)
if (y > 5)
Net = x + y;
else
Net = x − y;

However, if one desires to match the else with the first if, then the braces should be used as
shown below:
if (x < 50) {
if (y > 5)
Net = x + y;
}
else
Net = x − y;

The evaluation of if–else–if ladder is carried out from top to bottom. Each conditional expres-
sion is tested and if found true only then its corresponding statement is executed. The remaining
Introduction to C++ 23

ladder is, therefore, bypassed. In a situation where none of the nested conditions is found true
then the final else part is executed.

1.9.2.4 Switch Statement (Selection of One Out of Many Alternatives)


If it is required in a program to select one out of several different courses of action then the
switch statement of C++ can be used. In fact, it is a multi-branch selection statement that makes
the control to jump to one of the several statements based on the value of an integer variable or
expression. The general form of this statement is given below:
switch (expression)
{
case constant 1: statement; break;
case constant 2: statement; break;
:
default : statement;
}
where switch is a reserved word; expression must evaluate to an integer or character value;
case is a reserved word; constant must be an int or char compatible value; statement is a
simple or compound statement; default is a reserved word and is an optional entry; break is a
reserved word that stops the execution within the switch and the control comes out of the switch
construct.
The switch statement works according to the following rules:
1. The value of the expression is matched with the random case constants of the switch
construct.
2. If a match is found then its corresponding statements are executed and when break is
encountered, the flow of control jumps out of the switch statement. If break statement is
not encountered then the control continues across other statements. In fact, switch is the
only statement in ‘C++’ which is error prone. The reason being that is if the control is in
a particular case then it keeps running through all the cases in the absence of a proper
break statement. Thus, absence of a break statement is a common error. This phenom-
enon is called as “fall-through”.
3. If no match is found and if a default label is present then the statement corresponding to
default is executed.
4. The values of the various case constants must be unique.
5. There can be only one default statement in a switch statement.
Examples of acceptable switch statements are:
(i) switch (BP)
{
case 1 : total + = 100;
break;
case 2 : total + = 150;
24 Object-oriented Programming with C++

break;
case 3 : total + = 250;
}
(ii) switch (code)
{
case 101 : Rate = 50; break;
case 102 : Rate = 70; break;
case 103 : Rate = 100; break;
default : Rate = 95;
}
From the statement (ii) it may be observed that depending on the value of the code one out of
the four instructions is selected and obeyed. For example, for the code 103, the third instruction
(i.e. Rate = 100;) would be selected. On the other hand, if the code evaluates to 101 then the first
instruction (i.e. Rate = 50) would be selected.

Example 3. Write a program that determines in which quadrant an angle lies.


Solution: The program for this problem is given below:
// This program determines the quadrant for a given angle. It checks
for the value of angle
// between the range 0 to 360
# include <iostream.h>
void main( )
{
foat val_angle;
int term;
cout << “Enter the angle in degrees 0–360”;
cin >> val_angle;
if ((val_angle > 0) && (val_angle <= 360))
{
term = (int) val_angle/90;
switch (term)
{
case 0 : cout << “\n Ist quadrant”; break;
case 1 : cout << “\n 2nd quadrant”; break;
case 2 : cout << “\n 3rd quadrant”; break;
case 3 : cout << “\n 4th quadrant”;
}
}
else
cout << “\n Error in data”;
}
Introduction to C++ 25

1.9.3 Repetitive Execution (Iterative Statements)


Some problems require that a set of statements be executed a number of times, each time chang-
ing the values of one or more variables, so that every new execution is different from the previ-
ous one. This kind of repetitive execution of a set of statements in a program is known as a Loop.
We can categorize loop structures into two categories: non-deterministic loops and determin-
istic loops. When the number of times the loop is to be executed is not known then the loop is
called as non-deterministic loop, otherwise it is called a deterministic loop.
C++ supports while, do–while, and ‘for’ loop constructs to help repetitive execution of a
compound statement in a program. The ‘while’ and ‘do–while’ loops are non-deterministic
loops and the ‘for’ loop is a deterministic loop.

1.9.3.1 The while Loop


It is the fundamental conditional repetitive control structure in C and C++. The general form of
this construct is given below:
while <cond> statement;

where while is a reserved word of C++; <cond> is a Boolean expression; statement can be a
simple or compound statement.
The sequence of operation in a while loop is as follows:
1. Test the condition.
2. If the condition is true then execute the statement and repeat step 1.
3. If the condition is false, leave the loop and go on with the rest of the program.
Thus, it performs a pre-test before the body of the loop is allowed to execute.

Example 4. Write a program that computes the factorial of a number N.


N! = N * (N − 1) * (N −2) * ··· * 3 * 2 * 1

Solution: We would use the while loop for the iterations required in the computation of the
factorial.
// This program computes the factorial of a number N
# include <iostream.h>
# include <conio.h>
void main( )
{
int N;
int fact;
clrscr( );
cout << “Enter the Number =”;
cin >> N;
26 Object-oriented Programming with C++

// initialize fact
fact = N;
// accumulate factorial in fact
while (N > 1)
{
N = N − 1;
fact = fact * N;
}
// print factorial
cout << “\n The factorial of” << N << “is =” << fact;
}

It may be noted here that the variables used in the <cond> or Boolean expression must be suit-
ably initialized somewhere before the while statement is encountered otherwise the loop may
not execute even once.

1.9.3.2 The do–while Loop


It is another conditional repetitive control structure provided by C and C++. The syntax of this
construct is given below:
do
{
statement;
}
while <cond>;

where do is a reserved word; statement can be a simple or a compound statement; while is a


reserved word; <cond> is a Boolean expression.
The sequence of operations in a do–while loop is as follows:
1. Execute the statement.
2. Test the condition.
3. If the condition is true then repeat steps 1–2.
4. If the condition is false, leave the loop and go on with the rest of the program.
Thus, it performs a post-test in the sense that the condition is not tested until the body of the
loop is executed at least once. Therefore, it is suitable for constructing “Menus”.

Example 5. Write a program that displays the following “Menu” to the user and asks for his/
her choice. Thereafter, appropriate messages are displayed.
Menu: mode of travel
Travel by air 1
Introduction to C++ 27

Travel by train 2
Travel by bus 3
Travel by taxi 4
Quit 5
Enter your choice:

Solution: We would use the do–while loop to display the menu and switch statement to pick
the choice entered by the user. The required program is given below:

// This program displays a Menu to the user

#include <iostream.h>
# include <conio.h>
void main( )
{
int choice;
clrscr( );
do
{ clrscr( ); //display Menu
cout << “\n \tMenu:mode of travel”;
cout << “\n”;
cout << “\n \tTravel by Air 1”;
cout << “\n \tTravel by Train 2”;
cout << “\n \tTravel by Bus 3”;
cout << “\n \tTravel by Taxi 4”;
cout << “\n \tQuit 5”;
cout << “\n”;
cout << “\n Enter your choice:”;
// Get the choice
cin >> choice;
switch (choice)
{
case 1 : cout << “\n Fast and Risky”;
break;
case 2 : cout << “\n Comfortable and Safe”;
break;
case 3 : cout << “\n Slow and Jerky”;
break;
case 4 : cout << “\n Quick and costly”;
}
getch( ); // wait for a key
}
while (choice !=5);
}
28 Object-oriented Programming with C++

1.9.3.3 The for Loop


It is a count-controlled loop in the sense that the program knows in advance how many times the
loop is to be executed. The general form of this construct is given below:
for (initialization; expression; increment)
{
statement
}
where for is a reserved word; initialization is usually an assignment expression wherein a loop
control variable is initialized; expression is a conditional expression required to determine
whether the loop should continue or be terminated; increment modifies the value of the loop
control variable by a certain amount; statement can be a simple or a compound statement.
The loop is executed with the loop control variable at initial value, final value and the values
in between.
We can increase the power of for-loop with the help of the comma operator. This operator allows
the inclusion of more than one expressions in place of a single expression in the for statement
as shown below:
for (exp1a, exp1b; exp2; exp3a, exp3b;) statement;

Example 6. Write a program that computes xy where x and y are integers.


xy = x * x * x * ··· * x

Solution: We would iteratively multiply x to itself y times as shown below:


64 = 6 * 6 * 6 * 6
The required program is given below:
// This program computes x to the power y
#include <iostream.h>
# include <conio.h>
void main( )
{
int x, y, pow;
int i;
clrscr( );
cout << “\n Enter the values for x and y”;
cin >> x >> y;
// initialize
pow = x;
for (i = 2; i <= y; i++)
{
pow = pow * x;
}
cout << x << “^” << y << “=” << pow;
Introduction to C++ 29

A sample output is given below:


Enter the values for X and y 6 4
6^4=1296

Consider the following program segment:


:
for (i = 1, j = 10; i < = 10; i ++, j −−)
{
:
}

The variables i and j have been initialized to values 1 and 10, respectively. Please note that these
initialization expressions are separated by a ‘comma’. However, the required semicolon remains
as such. During the execution of the loop, i increases from 1 to 10 whereas simultaneously j
decreases from 10 to 1. Similarly the increment and decrement operations have been separated
by a ‘comma’ in the for statement.
Though the power of the loop can be increased by including more than one initialization and
increment expressions separated with the comma operator but there can be only one test expres-
sion which could be simple or complex.

1.9.3.4 The ‘break’ and ‘continue’ Statements


The break statement can be used in a loop to terminate its execution. We have already seen that
it is used to exit from a switch statement. In fact, whenever the break statement is encountered
in a loop, the control is transferred out of the loop. This is used in a situation where some error
is found in the program inside the loop or it becomes unnecessary to continue with the rest of
the execution of the loop.
Consider the following program segment:
:
while (val != 0)
{
cin >> val;
cout << “val =” << val;
if (val < 0){
cout << “\n Error in input”;
break;
}
:
}

Whenever the value read in variable val is negative, the message: ‘Error in input’, would be
displayed and because of the break statement the loop will be terminated.
30 Object-oriented Programming with C++

A continue statement can also be used in loop to bypass the rest of the code segment of the
current iteration of the loop. The loop, however, is not terminated. The execution of the loop
resumes with the next iteration. For example, the following loop computes the sum of positive
numbers in a list of 50 numbers:
:
sum = 0;
for (i = 0; i < 50; i ++)
{
cout << val;
if (val < = 0) continue;
sum = sum + val;
}
:

It may be noted here that continue statement has no relevance as far as switch statement is con-
cerned. Therefore, it cannot be used in a switch statement.

1.9.3.5 The exit( ) Function


In the event of encountering a fatal error, the programmer may desire to terminate the program
itself. For such a situation, C++ supports a function called exit( ) which can be invoked by the
programmer to exit from the program. This function can be called from anywhere inside the
body of the program. For normal termination, the programmer can include an argument 0 while
invoking this library function as shown below:
#include <iostream.h>
#include <process.h>
void main( )
{
:
if (error) exit (0);
:
}

It may be noted here that the file process.h has to be included as header file because it contains
the function prototype of the library function exit( ).

1.9.4 Nested Loops


It is possible to nest one loop construct inside the body of another. The inner and outer loops
need not be of the same construct.
while <cond>
{
do
{
} while <cond>;
for (init; exp; inc)
{
Introduction to C++ 31

:
}
:
}

The rules for the formation of nested loops are:


1. An outer for loop and an inner for loop cannot have the same control variable.
2. The inner loop must be completely nested inside the body of the outer loop.

1.10 ARRAYS
An array is a data structure with the help of which a programmer can refer to and perform
operations on a collection of similar data types such as simple lists or tables of information. For
example, a list of names of ‘N’ number of students of a class can be grouped under a common
name (say studList). This list can be easily represented by an array called studList for ‘N = 45’
students as shown in Fig. 1.6.
0 1 2 43 44

studList Sagun Rishi Bhavana Ridhi Preksha

Figure 1.6 Schematic representation of an array

In fact, the studList shown in Fig. 1.6 can be looked upon by the following two points of views:
1. It is a linear list of 45 names stored in contiguous locations – an abstract view of a list
having finite number of homogeneous elements (i.e. 45 names) .
2. It is a set of 0–44 memory locations sharing a common name called studList – it is an
array data structure in which 45 names have been stored.
It may be noted that all the elements in the array are of same type, i.e. string of char in this
case. The individual elements within the array can be designated by an index. The individual
elements are randomly accessible by integers, called the index.
For instance, the 0th element (Sagun) in the list can be referred to as studList [0] and the
43rd element (Ridhi) as studList [43], where 0 and 43 are the indices and an index has to be of
type integer.
An index is also called as a subscript. Therefore, individual elements of an array are called
as subscripted variables. For instance, studList [0] and studList [43] are subscripted variables.
From the above discussion, we can arrive at the following definition:
Array: a finite ordered collection of items of same type. It is a set of index, value pairs.
An array is a built-in data structure in every programming language. Arrays are designed to have
a fixed size. Some languages provide 0-based indexing whereas other languages provide 1-based
indexing. ‘C++’ is an example of 0-based indexing language because the index of its arrays starts
from 0. Pascal is the example of 1-based addressing because the index of its arrays starts from 1.
An array whose elements are specified by a single subscript is known as one-dimensional ar-
ray. The array whose elements are specified by two or more than two subscripts is called as multi-
dimensional array.
32 Object-oriented Programming with C++

1.10.1 One-dimensional Arrays


One-dimensional arrays are suitable for processing lists of items of identical types. They are
very useful for problems that require the same operation to be performed on a group of data.
For example, an array called list of 50 locations of integer type can be declared as shown below:
int LIST [50];

The above declaration means that LIST is an array of 50 memory locations, each of which is of
integer type. Once this declaration is obeyed, we get a group of 50 locations of integer type in
the memory of the computer as shown in Fig. 1.7.
0 1 2 3 49
LIST

Figure 1.7 A one-dimensional array of 50 locations

It may be noted here that in C and C++ the first array element has the subscript 0. Therefore, the
last subscript, in this case, has been designated as 49.
Examples of some valid array declarations are:
(i) int series [100];
(ii) char names [20];
(iii) float sal [50];
Generally, arrays are manipulated in a fashion of component-by-component processing. In simple
words, we can say that similar operations are performed on some or all the components of the array.

Example 7. Write a program which f nds the largest number and its position in a list of N
numbers.
Solution: The basic solution is that if the list contains only one element then that element is
the largest. Therefore, we would consider the zeroth number as the largest. The program is
given below:
// This program fnds the largest number in a list and its position
# include <iostream.h>
main( )
{
int set [100];
int lar, pos, i;
int N; // Size of the list
cout << “\n Enter the size of the list”;
cin >> N;
cout << “\n Enter the list \n”;
for (i = 0; i <= N − 1; i++)
Introduction to C++ 33

cin >> set [i];


pos = 0;
lar = set [0]; // Set the frst value equal to large
for (i = 1; i <= N − 1; i++)
{
if (set [i] > lar)
{
lar = set[i];
pos = i;
}
}
pos ++;
cout << “\n The largest =” << lar << “ ” << “pos =” << pos;
}
A sample output is given below:

Enter the size of the list 5


Enter the list
12 5 67 52 31
The largest =67 Pos =3

1.10.2 Multi-dimensional Arrays


An array having more than one subscript is known as a multi-dimensional array. A two-dimen-
sional array (having two subscripts) is suitable for table processing or matrix manipulations. For
this purpose, we use two subscripts enclosed in square brackets. The first subscript designates
the number of rows and the second subscript designates the number of columns. For example, a
two-dimensional array of 5 rows and 4 columns (i.e. total 5 * 4 = 20 locations) of integer type
can be declared as given below. Let us assume that the name of the array is mat.
int mat [5][4];

The above declaration means that mat is a two-dimensional array having 5 rows and 4 columns,
i.e. totally 20 locations with each location of integer type as shown in Fig. 1.8.
mat [0][0] [0][1] [0][3]
[0][0]
[1][0]

[4][0]
[4][0] [4][1] [4][3]

Figure 1.8 A two-dimensional array


34 Object-oriented Programming with C++

An individual element of the array can be referred to by two subscripts, i.e. row and column sub-
scripts. For example, a memory location at 4th row and 2nd column can be designated as mat [4] [2].

Example 8. Given two matrices A and B of order m × n. Compute the sum of the two matrices
such that:
C(I, J) = A(I, J) + B(I, J), I = 1, …, m and J = 1, …, n
Solution: The solution for this problem involves two-dimensional arrays. We would employ
two nested loops, the outer for row traversal and the inner for column traversal. The required
program is given below:
/* This program adds two matrices. The matrices are stored in
the 2-dimensional array MATA and MATB. The result of computation
is stored in a third two-dimensional array MATC */
# include <iostream.h>
# include <conio.h>
void main( )
{
int MATA [10][10], MATB [10][10], MATC [10][10]; int i, j; //
Indexes of nested loops
int m, n; //Order of matrices
cout << “\n Enter the order of matrices \n”;
cin >> m >> n;
cout << “\n Enter the elements of matrix A \n”;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
cin >> MATA [i][j];
}
cout << “\n Enter the elements of matrix B \n”;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j ++)
cin >> MATB [i][j];
}
// Compute the sum
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
MATC [i][j] = MATA [i][j]+ MATB [i][j];
}
cout << “\n The resultant matrix is ... \n”;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
Introduction to C++ 35

cout << MATC [i][j] << ‘ ’;


cout << ‘\n’;
}
}

1.10.3 Array Initialization


A programmer can initialize an array even at the time of its declaration. This is done by specify-
ing the values of some or all its elements. For example, the string “SCHOOL” can be initialized
in an array called ‘texts’ in the following two ways:
char texts [7] = {“SCHOOL”};
char texts [7] = {‘S’, ‘C’, ‘H’, ‘O’, ‘O’, ‘L’, ‘\0’};

In the first case the string “SCHOOL” has been moved to the array text of size 7 where 6 loca-
tions have been used for the characters in the string and 7th for the null character ‘\0’. In the
first case, the null character gets automatically attached at the end. However in second case, the
string “SCHOOL” is being moved character by character. Therefore, it is necessary to provide
the null character ‘\0’ at the end of the string.
During initialization of arrays, one need not specify the dimension of the array as shown below:
int rol [ ] = {101, 105, 210, 319, 570};

The C++ compiler automatically calculates the dimensions of the un-sized initialized arrays.
This type of un-sized array initialization is also possible for strings in C++. For example, the
following array initialization is a valid initialization:
char text [ ] = {“SCHOOL”};

In this case also, the C++ compiler automatically computes the dimensions of the array. The multi-
dimensional arrays can also be initialized in the similar fashion. Consider the matrix of order
4 * 3 given below:

⎛ 5 2 7⎞
⎜ 3 2 9⎟
A=⎜
8 2 5⎟
⎜ ⎟
⎝1 2 6 ⎠
This matrix can be initialized in a two-dimensional array as shown below:
int A [4][3] = {5, 2, 7,
3, 2, 9,
8, 2, 5,
1, 2, 6};

Note: The initialization of arrays at the time of declaration is possible only outside a
function. Inside the function the initialized array has to be declared as static.
Exploring the Variety of Random
Documents with Different Content
rich and full, sixty bushels to the acre. Oats, which do not take so
kindly to the soil and air, produce sometimes only forty-eight.
Burns was but sixteen when his father moved from Mount Oliphant
to the Lochlea farm, in the parish of Tarbolton. It was in Tarbolton
that he first went to dancing-school, joined the Freemasons, and
organized the club which, no doubt, cost him dear, "The Bachelors of
Tarbolton." In the beginning this club consisted of only five members
besides Burns and his brother; afterward it was enlarged to sixteen.
Burns drew up the rules; and the last one—the tenth—is worth
remembering, as an unconscious defining on his part of his ideal of
human life:—
"Every man proper for a member of this society must have
a friendly, honest, open heart, above everything dirty or
mean, and must be a professed lover of one or more of
the sex. The proper person for this society is a cheerful,
honest-hearted lad, who, if he has a friend that is true,
and a mistress that is kind, and as much wealth as
genteelly to make both ends meet, is just as happy as this
world can make him."
Walking to-day through the narrow streets of Tarbolton, it is wellnigh
impossible to conceive of such rollicking good cheer having made
abiding-place there. It is a close, packed town, the houses of stone
or white plaster,—many of them low, squalid, with thatched roofs
and walls awry; those that are not squalid are grim. The streets are
winding and tangled; the people look poor and dull. As I drove up to
the "Crown Inn," the place where the Tarbolton Freemasons meet
now, and where some of the relics of Burns's Freemason days are
kept, the "first bells" were ringing in the belfry of the old church
opposite, and the landlord of the inn replied with a look of great
embarrassment to my request to see the Burns relics,—
"It's the Sabbath, mem."
Then he stood still, scratching his head for a few moments, and then
set off, at full run, down the street without another word.
"He's gone to the head Mason," explained the landlady. "It takes
three to open the chest. I think ye'll na see it the day." And she
turned on her heel with a frown and left me.
"They make much account o' the Sabbath in this country," said my
driver. "Another day ye'd do better."
Thinking of Burns's lines to the "Unco Guid," I strolled over into the
churchyard opposite, to await the landlord's return. The bell-ringer
had come down, and followed me curiously about among the graves.
One very old stone had carved upon it two high-top boots; under
these, two low shoes; below these, two kneeling figures, a man and
a woman, cut in high relief; no inscription of any sort.
"What can it mean?" I asked.
The bell-ringer could not tell; it was so old nobody knew anything
about it. His mother, now ninety years of age, remembered seeing it
when she was a child, and it looked just as old then as now.
"There's a many strange things in this graveyard," said he; and then
he led me to a corner where, enclosed by swinging chains and stone
posts, was a carefully kept square of green turf, on which lay a
granite slab. "Every year comes the money to pay for keeping that
grass green," he said, "and no name to it. It's been going on that
way for fifty years."
The stone-wall around the graveyard was dilapidated, and in parts
was falling down.
"I suppose this old wall was here in Burns's time," I said.
"Ay, yes," said the bell-ringer; and pointing to a low, thatched
cottage just outside it, "and yon shop—many's the time he's been in
it playin' his tricks."
The landlord of the inn now came running up, with profuse
apologies for the ill success of his mission. He had been to the head
Mason, hoping he would come over and assist in the opening of the
chest, in which were kept a Mason's apron worn by Burns, some
jewels of his, and a book of minutes kept by him. But "bein' 's it's
the Sabbath," and "he's sick in bed," and it was "against the rules to
open the regalia chest unless three Masons were present," the kindly
landlord, piling up reason after reason, irrespective of their
consistency with each other, went on to explain that it would be
impossible; but I might see the chair in which Burns always sat. This
was a huge oaken chair, black with age, and furrowed with names
cut deep in the wood. It was shaped and proportioned like a child's
high-chair, and had precisely such a rest for the feet as is put on
children's high-chairs. To this day the Grand Mason sits in it at their
meetings, and will so long as the St. James Lodge exists.
"They've been offered hundreds of pounds for that chair, mem, plain
as it is. You'd not think it; but there's no money'd buy it from the
lodge," said the landlord.
The old club-house where the jolly "Bachelors of Tarbolton" met in
Burns's day is a low, two-roomed, thatched cottage, half in ruins.
The room where the bachelors smoked, drank, and sang is now little
more than a cellar filled with rubbish and filth,—nothing left but the
old fireplace to show that it was ever inhabited. In the other half of
the cottage lives a laborer's family,—father, mother, and a young
child: their one room, with its bed built into the wall, and their few
delf dishes on the dresser, is probably much like the room in which
Burns first opened his wondrous eyes. The man was lying on the
floor playing with his baby. At the name of Burns, he sprang up with
a hearty "Ay, weel," and ran out in his blue-stocking feet to show me
the cellar, of which, it was plainly to be seen, he was far prouder
than of his more comfortable side of the house. The name by which
the inn was called in Burns's day he did not know. But "He's a Mason
over there; he'll know," he cried; and before I could prevent him, he
had darted, still shoeless, across the road, and asked the question of
a yet poorer laborer, who was taking his Sunday on his door-sill with
two bairns between his knees. He had heard, but had "forgotten."
"Feyther'll know," said the wife, coming forward with the third bairn,
a baby, in her arms. "I'll rin an' ask feyther." The old man tottered
out, and gazed with a vacant, feeble look at me, while he replied
impatiently to his daughter: "Manson's Inn, 't was called; ye've
heard it times eneuch."
"I dare say you always drink Burns's health at the lodge when you
meet," I said to the laborer.
"Ay, ay, his health's ay dronkit," he said, with a coarse laugh, "weel
dronkit."
A few rods to the east, and down the very road Burns was wont to
come and go between Lochlea and Tarbolton, still stands "Willie's
mill,"—cottage and mill and shed and barn, all in one low, long,
oddly joined (or jointed) building of irregular heights, like a
telescope pulled out to its full length; a little brook and a bit of gay
garden in front. In the winter the mill goes by water from a lake
near by; in the summer by steam,—a great change since the night
when Burns went
"Todlin' down on Willie's mill,"

and though he thought he


"Was na fou, but just had plenty,"

could not for the life of him make out to count the moon's horns.
"To count her horns, wi' a' my power,
I set mysel';
But whether she had three or four
I could na tell."
To go by road from Tarbolton to Lochlea farm is to go around three
sides of a square, east, north, and then west again. Certain it is that
Burns never took so many superfluous steps to do it; and as I drove
along I found absorbing interest in looking at the little cluster of
farm buildings beyond the fields, and wondering where the light-
footed boy used to "cut across" for his nightly frolics. There is
nothing left at Lochlea now of him or his; nothing save a worn lintel
of the old barn. The buildings are all new; and there is a look of
thrift and comfort about the place, quite unlike the face it must have
worn in 1784. The house stands on a rising knoll, and from the
windows looking westward and seaward there must be a fine
horizon and headlands to be seen at sunset. Nobody was at home
on this day except a barefooted servant-girl, who was keeping the
house while the family were at church. She came to the door with an
expression of almost alarm, at the unwonted apparition of a carriage
driving down the lane on Sunday, and a stranger coming in the
name of a man dead so long ago. She evidently knew nothing of
Burns except that, for some reason connected with him, the old
lintel was kept and shown. She was impatient of the interruption of
her Sabbath, and all the while she was speaking kept her finger in
her book—"Footprints of Jesus"—at the place where she had been
reading, and glanced at it continually, as if it were an amulet which
could keep her from harm through the worldly interlude into which
she had been forced.
"It's a pity ye came on the Sabba-day," remarked the driver again,
as we drove away from Lochlea. "The country people 'ull not speak
on the Sabbath." It would have been useless to try to explain to him
that the spectacle of this Scottish "Sabba-day" was of itself of almost
as much interest as the sight of the fields in which Robert Burns had
walked and worked.
The farm of Mossgiel, which was Burns's next home after Lochlea, is
about three miles from Tarbolton, and only one from Mauchline.
Burns and his brother Gilbert had become tenants of it a few months
before their father's death in 1784. It was stocked by the joint
savings of the whole family; and each member of the family was
allowed fair rates of wages for all labor performed on it. The
allowance to Gilbert and to Robert was seven pounds a year each,
and it is said that during the four years that Robert lived there, his
expenses never exceeded this pittance.
To Mossgiel he came with new resolutions. He had already reaped
some bitter harvests from the wild oats sown during the seven years
at Lochlea. He was no longer a boy. He says of himself at this time,

"I entered on Mossgiel with a full resolution, 'Come, go; I will be
wise.'"
Driving up the long, straight road which leads from the highway to
the hawthorn fortress in which the Mossgiel farm buildings stand,
one recalls these words, and fancies the brave young fellow striding
up the field, full of new hope and determination. The hawthorn
hedge to-day is much higher than a man's head, and completely
screens from the road the farm-house and the outbuildings behind
it. The present tenants have lived on the farm forty years, the first
twenty in the same house which stood there when Robert and
Gilbert Burns pledged themselves to pay one hundred and twenty
pounds a year for the farm. When the house was rebuilt, twenty
years ago, the old walls were used in part, and the windows were
left in the same places; but, instead of the low, sloping-roofed,
garret-like rooms upstairs, where Burns used to sleep and write, are
now comfortable chambers of modern fashion.
"Were you not sorry to have the old house pulled down?" I said to
the comely, aged farm-wife.
"'Deed, then, I was very prood," she replied; "it had na
'coomodation, and the thatch took in the rain an' all that was vile."
In the best room of the house hung two autograph letters of Burns's
plainly framed: one, his letter to the lass of ——, asking her
permission to print the poem he had addressed to her; the other, the
original copy of the poem. These were "presented to the house by
the brother of the lady," the woman said, and they had "a great
value now." But when she first came to this part of the country she
was "vary soorpreezed" to find the great esteem in which Burns's
poetry was held. In the North, where she had lived, he was "na
thocht weel of." Her father had never permitted a copy of his poems
to be brought inside his doors, and had forbidden his children to
read a word of them. "He thocht them too rough for us to read." It
was not until she was a woman grown, and living in her husband's
house, that she had ever ventured to disobey this parental
command, and she did not now herself think they were "fitted for
the reading of young pairsons." "There was much more discreet
writin's," she said severely; an opinion which there was no
gainsaying.
There is a broader horizon to be seen, looking westward from the
fields of Mossgiel, than from those of Lochlea; the lands are higher
and nobler of contour. Superb trees, which must have been superb a
century ago, stand to right and left of the house,—beeches, ashes,
oaks, and planes. The fields which are in sight from the house are
now all grass-grown. I have heard that twenty years ago, it was
confidently told in which field Burns, ploughing late in the autumn,
broke into the little nest of the
"Wee sleekit, cow'rin', tim'rous beastie,"

whom every song-lover has known and pitied from that day to this,
and whose misfortunes have answered ever since for a mint of
reassuring comparison to all of us, remembering that "the best-laid
schemes o' mice an' men" must "gang aft aglee;" and the other
field, also near by, where grew that mountain daisy,
"Wee, modest, crimson-tippèd flower,"

whose name is immortal in our hearts as that of Burns. This farm-


wife, however, knew nothing about them. The stern air of the north
country in which she had been reared still chilled somewhat her
thoughts of Burns and her interest in his inalienable bond on the
fields of her farm.
It is but a mile from Mossgiel's gate to Mauchline, the town of
"bonnie Jean" and Nansie Tinnoch and Gavin Hamilton. Surely a
strange-assorted trio to be comrades of one man. Their houses are
still standing: Jean's a tumble-down thatched cottage, looking out of
place enough between the smart, new houses built on either side of
it; Gavin Hamilton's, a dark, picturesque stone house, joined to the
ruins of Mauchline Castle; and Nansie Tinnoch's, a black and
dilapidated hovel, into which it takes courage to go. It stands
snugged up against the wall of the old graveyard, part below it and
part above it,—a situation as unwholesome as horrible; a door at the
head of the narrow stairway opening out into the graveyard itself,
and the slanting old stones leering in at the smoky windows by
crowds. In the days when all the "country side" met at the open-air
services in this churchyard,
"Some thinkin' on their sins, an' some on their claes,"

no doubt Nancy Tinnoch's was a lighter, whiter, cheerier place than


now; else the "Jolly Beggars" would never have gone there to tipple.
It was the nooning between services when I reached Mauchline, and
church-goers from a distance were taking their beer and crackers
decorously in the parlor of the inn. As the intermission was only
three quarters of an hour long, this much of involuntary dissipation
was plainly forced on them; but they did not abuse it, I can testify.
They partook of it as of a passover: young men and maidens as
sober and silent as if they had been doing solemn penance for sins,
as indeed, from one point of view, it might perhaps be truly said that
they were.
By dint of some difficult advances I drew one or two of them into
conversation about the Mossgiel farm and the disappearance of the
old relics of Burns's life in that region. It was a great pity, I said, that
the Mossgiel house had to be taken down.
"'Deed, then, it was na such thing," spoke up an elderly man. "It
was na moor than a wreck, an' I'm the mon who did it."
He was the landlord of the farm, it appeared. He seemed much
amused at hearing of the farm-wife's disapproval of Burns's verses,
and of her father's prohibition of them.
"He was a heepocritical auld Radical, if ye knows him," he said
angrily. "I hope we'll never have ony worse readin' in our country
than Robert Bur-r-r-ns." The prolongation of the "r" in the Scotch
way of saying "Burns" is something that cannot be typographically
represented. It is hardly a rolling of the "r," nor a multiplication of it;
but it takes up a great deal more time and room than any one "r"
ought to.
After the landlady had shown to me the big hall where the
Freemasons meet, "the Burns' Mother Lodge," and the chest which
used to hold the regalia at Tarbolton in Burns's day, and the little
bedroom in which Stedman and Hawthorne had slept,—coming also
to look at Burns's fields,—she told me in a mysterious whisper that
there was a nephew of Burns's in the kitchen, who would like to see
me, if I would like to see him. "A nephew of Burns's!" I exclaimed.
"Weel, not exactly," she explained, "but he's a grand-nephew of
Burns's wife; she thet was Jean, ye know," with a deprecating nod
and lowering of the eyelid. So fast is the clutch of a Scotch
neighborhood on its traditions of offended virtue, even to-day poor
Jean cannot be mentioned by a landlady in her native town without
a small stone cast backward at her.
Jean's grand-nephew proved to be a middle-aged man; not "ower
weel-to-do," the landlady said. He had tried his hand at doctoring
both in Scotland and America,—a rolling stone evidently, with too
much of the old fiery blood of his race in his veins for quiet and
decorous prosperity. He, too, seemed only half willing to speak of
poor "Jean,"—his kinswoman; but he led me to the cottage where
she had lived, and pointed out the window from which she was said
to have leaned out many a night listening to the songs of her lover
when he sauntered across from the Whiteford Arms, Johnny Pigeon's
house, just opposite, "not fou, but having had plenty" to make him
merry and affectionate. Johnny Pigeon's is a "co-operative store"
now; and new buildings have altered the line of the street so that
"Rob Mossgiel" would lose his way there to-day.
The room in which Burns and his "bonnie Jean" were at last married
in Gavin Hamilton's house, by Hamilton himself, is still shown to
visitors. This room I had a greater desire to see than any other spot
in Mauchline. "We can but try," said the grand-nephew; "but it's a
small chance of seeing it the Sabba."
The sole tenant of this house now is the widow of a son of Gavin
Hamilton's. Old, blind, and nearly helpless, she lives there alone with
one family servant, nearly as old as herself, but hale, hearty, and
rosy as only an old Scotchwoman can be. This servant opened the
door for us, her cap, calico gown, and white apron all alike bristling
with starch, religion, and pride of family. Her mistress would not
allow the room to be shown on the Sabbath, she said. Imploringly it
was explained to her that no other day had been possible, and that I
had come "all the way from America."
"Ye did na do weel to tak the Sabbath," was her only reply, as she
turned on her heel to go with the fruitless appeal to her mistress.
Returning, she said curtly,—
"She winna shew it on the Sabbath."
At this crisis my companion, who had kept in the background,
stepped forward with,—
"You don't know me, Elspie, do ye?"
"No, sir," she said stiffly, bracing herself up mentally against any
further heathenish entreaties.
"What, not know ——?" repeating his name in full.
Presto! as if changed by a magician's trick, the stiff, starched,
religious, haughty family retainer disappeared, and there stood, in
the same cap, gown, and apron, a limber, rollicking, wellnigh
improper old woman, who poked the grand-nephew in the ribs,
clapped him on the shoulder, chuckling, ejaculating, questioning,
wondering, laughing, all in a breath. Reminiscence on reminiscence
followed between them.
"An' do ye mind Barry, too?" she asked. (This was an old man-
servant of the house.) "An' many's the quirrel, an' many's the gree
we had."
Barry was dead. Dead also was the beautiful girl whom my
companion remembered well,—dead of a broken heart before she
was eighteen years of age. Forbidden to marry her lover, she had
drooped and pined. He went to India and died. It was in a December
the news of his death came, just at Christmas time, and in the next
September she followed him.
"Ay, but she was a bonnie lass," said Elspie, the tears rolling down
her face.
"I dare say she [nodding his head toward the house]—I dare say
she's shed many a salt tear over it; but naebody 'ill ever know she
repentit," quoth the grand-nephew.
"Ay, ay," said Elspie. "There's a wee bit closet in every hoos."
"'Twas in that room she died," pointing up to a small ivy-shaded
window. "I closed her eyes wi' my hands. She's never spoken of. She
was a bonnie lass."
The picture of this desolate old woman, sitting there alone in her
house, helpless, blind, waiting for death to come and take her to
meet that daughter whose young heart was broken by her cruel will,
seemed to shadow the very sunshine on the greensward in the
court. The broken arches and crumbling walls of the old stone abbey
ruins seemed, in their ivy mantles, warmly, joyously venerable by
contrast with the silent, ruined, stony old human heart still beating
in the house they joined.
In spite of my protestations, the grand-nephew urged Elspie to show
us the room. She evidently now longed to do it; but, casting a
fearful glance over her shoulder, said: "I daur na! I daur na! I could
na open the door that she'd na hear 't." And she seemed much
relieved when I made haste to assure her that on no account would
I go into the room without her mistress's permission. So we came
away, leaving her gazing regretfully after us, with her hand shading
her eyes from the sun.
Going back from Mauchline to Ayr, I took another road, farther to the
south than the one leading through Tarbolton, and much more
beautiful, with superb beech-trees meeting overhead, and
gentlemen's country-seats, with great parks, on either hand.
On this road is Montgomerie Castle, walled in by grand woods, which
Burns knew so well.
"Ye banks and braes and streams around
The castle o' Montgomery,
Green be your woods and fair your flowers,
Your waters never drumlie!
There simmer first unfauld her robes,
And there the langest tarry,
For there I took the last fareweel
O' my sweet Highland Mary."

Sitting in the sun, on a bench outside the gate-house, with his little
granddaughter on his lap, was the white-haired gate-keeper. As the
horses' heads turned toward the gate, he arose slowly, without a
change of muscle, and set down the child, who accepted her altered
situation also without a change of muscle in her sober little face.
"Is it allowed to go in?" asked the driver.
"Eh—ye'll not be calling at the hoos?" asked the old man, surprised.
"No, I'm a stranger; but I like to see all the fine places in your
country," I replied.
"I've no orders," looking at the driver reflectively; "I've no orders—
but—a decent pairson"—looking again scrutinizingly at me,—"I think
there can be no hairm." And he opened the gate.
Grand trees, rolling tracts of velvety turf, an ugly huge house of
weather-beaten stone, with white pillars in front; conservatories
joining the wings to the centre; no attempt at decorative landscape
art; grass, trees, distances,—these were all; but there were miles of
these. It was at least a mile's drive to the other entrance to the
estate, where the old stone gateway house was in ruin. I fancy that
it was better kept up in the days before an Earl of Eglinstoune sold it
to a plain Mr. Patterson.
At another fine estate nearer Ayr, where an old woman was gate-
keeper, and also had "no orders" about admitting strangers, the
magic word "America" threw open the gates with a sweep, and bent
the old dame's knees in a courtesy which made her look three times
as broad as she was long. This estate had been "always in the
Oswald family, an' is likely always to be, please God," said the loyal
creature, with another courtesy at the mention, unconsciously
devout as that of the Catholic when he crosses himself. "An' it's a
fine country ye've yersel' in America," she added politely. The
Oswald estate has acres of beautiful curving uplands, all green and
smooth and open; a lack of woods near the house, but great banks
of sunshine instead, make a beauty all their own; and the Ayr Water,
running through the grounds, and bridged gracefully here and there,
is a possession to be coveted. From all points is a clear sight of sea,
and headlands north and south,—Ayr harbor lying like a crescent,
now silver, now gold, afloat between blue sky and green shore, and
dusky gray roof-lines of the town.
The most precious thing in all the parish of Ayr is the cottage in
which Burns was born. It is about two miles south from the centre of
the town, on the shore of "Bonnie Doon," and near Alloway Kirk. You
cannot go thither from Ayr over any road except the one Tam o'
Shanter took: it has been straightened a little since his day, but
many a rod of it is the same that Maggie trod; and Alloway Kirk is as
ghostly a place now, even at high noon, as can be found "frae
Maidenkirk to Johnny Groat's." There is nothing left of it but the
walls and the gable, in which the ancient bell still hangs, intensifying
the silence by its suggestion of echoes long dead.
The Burns cottage is now a sort of inn, kept by an Englishman
whose fortunes would make a tale by themselves. He fought at
Balaklava and in our civil war; and side by side on the walls of his
dining-room hang, framed, his two commissions in the Pennsylvania
Volunteers and the menu of the Balaklava Banquet, given in London
to the brave fellows that came home alive after that fight. He does
not love the Scotch people.
"I would not give the Americans for all the Scotch ever born," he
says, and is disposed to speak with unjust satire of their apparent
love of Burns, which he ascribes to a perception of his recognition by
the rest of the world and a shamefaced desire not to seem to be
behindhand in paying tribute to him.
"Oh, they let on to think much of him," he said. "It's money in their
pockets."
The room in which Burns was born is still unaltered, except in having
one more window let in. Originally, it had but one small square
window of four panes. The bed is like the beds in all the old Scotch
cottages, built into the wall, similar to those still seen in Norway.
Stifling enough the air surely must have been in the cupboard bed in
which the "waly boy" was born.
"The gossip keekit in his loof;
Quo' scho, 'Wha lives will see the proof,—
This waly boy will be nae coof;
I think we'll ca' him Robin.'"

Before he was many days old, or, as some traditions have it, on the
very night he was born, a violent storm "tirled" away part of the roof
of the poor little "clay biggin," and mother and babe were forced to
seek shelter in a neighbor's cottage. Misfortune and Robin early
joined company, and never parted. The little bedroom is now the
show-room of the inn, and is filled with tables piled with the well-
known boxes, pincushions, baskets, paper-cutters, etc., made from
sycamore wood grown on the banks of Doon and Ayr. These articles
are all stamped with some pictures of scenery associated with Burns
or with quotations from his verses. It is impossible to see all this
money-making without thinking what a delicious, rollicking bit of
verse Burns would write about it himself if he came back to-day.
There are those who offer for sale articles said to be made out of
the old timbers of the Mossgiel house; but the Balaklava Englishman
scouts all that as the most barefaced imposture. "There wasn't an
inch of that timber," he says,—and he was there when the house
was taken down—"which wasn't worm-eaten and rotten; not enough
to make a knife-handle of!"
One feels disposed to pass over in silence the "Burns Monument,"
which was built in 1820, at a cost of over three thousand pounds; "a
circular temple supported by nine fluted Corinthian columns,
emblematic of the nine muses," say the guide-books. It stands in a
garden overlooking the Doon, and is a painful sight. But in a room in
the base of it are to be seen some relics at which no Burns lover can
look unmoved,—the Bibles he gave to Highland Mary, the ring with
which he wedded Jean (taken off after her death), and two rings
containing some of his hair.
It is but a few steps from this monument down to a spot on the
"banks o' bonnie Doon," from which is a fine view of the "auld brig."
This shining, silent water, and the overhanging, silent trees, and the
silent bell in the gable of Alloway Kirk, speak more eloquently of
Burns than do all nine of the Corinthian muse-dedicated pillars in his
monument.
So do the twa brigs of Ayr, which still stand at the foot of High
Street, silently recriminating each other as of old.
"I doubt na, frien', ye'll think ye'r nae sheep-shank
When ye are streekit o'er frae bank to bank,"

sneers the Auld; and


"Will your poor, narrow foot-path of a street,
Where twa wheelbarrows tremble when they meet,
Your ruined, formless bulk o' stane and lime,
Compare wi' bonny brigs o' modern time?"

retorts the New; and "the sprites that owre the brigs of Ayr preside"
never interrupt the quarrel. Spite of all its boasting, however, the
new bridge cracked badly two years ago, and had to be taken down
and entirely rebuilt.
The dingy little inn where
"Tam was glorious,
O'er a' the ills o' life victorious,"

is still called by his name, and still preserves, as its chief claims to
distinction, the big wooden mug out of which Tam drank, and the
chair in which he so many market-nights
"Gat planted unco richt."

The chair is of oak, wellnigh black as ebony, and furrowed thick with
names cut upon it. The smart young landlady who now keeps the
house commented severely on this desecration of it, and said that
for some years the house had been "keepit" by a widow, who was
"in no sense up to the beesiness," and "a' people did as they pleased
in the hoos in her day." The mug has a metal rim and base; but spite
of these it has needed to be clasped together again by three ribs of
cane, riveted on. "Money couldn't buy it," the landlady said. It
belongs to the house, is mentioned always in the terms of lease, and
the house has changed hands but four times since Tam's day.
In a tiny stone cottage in the southern suburbs of Ayr, live two
nieces of Burns, daughters of his youngest sister, Isabella. They are
vivacious still, and eagerly alive to all that goes on in the world,
though they must be well on in the seventies. The day I called they
had "just received a newspaper from America," they said. "Perhaps I
knew it. It was called 'The Democrat.'" As I was not able to identify
it by that description, the younger sister made haste to fetch it. It
proved to be a paper printed in Madison, Iowa. The old ladies were
much interested in the approaching American election, had read all
they could find about General Garfield, and were much impressed by
the wise reticence of General Grant. "He must be a vary cautious
man; disna say enough to please people," they said, with sagacious
nods of approbation. They remembered Burns's wife very well, had
visited her when she was living, a widow, at Dumfries, and told with
glee a story which they said she herself used to narrate, with great
relish, of a pedler lad who, often coming to the house with wares to
sell in the kitchen, finally expressed to the servant his deep desire to
see Mrs. Burns. She accordingly told him to wait, and her mistress
would, no doubt, before long come into the room. Mrs. Burns came
in, stood for some moments talking with the lad, bought some trifle
of him, and went away. Still he sat waiting. At last the servant asked
why he did not go. He replied that she had promised he should see
Mrs. Burns.
"But ye have seen her; that was she," said the servant.
"Eh, eh?" said the lad. "Na! never tell me now that was 'bonnie
Jean'!"
Burns's mother, too (their grandmother), they recollected well, and
had often heard her tell of the time when the family lived at Lochlea,
and Robert, spending his evenings at the Tarbolton merry-makings
with the Bachelors' Club or the Masons, used to come home late in
the night, and she used to sit up to let him in. These doings sorely
displeased the father; and at last he said grimly, one night, that he
would sit up to open the door for Robert. Trembling with fear, the
mother went to bed, and did not close her eyes, listening
apprehensively for the angry meeting between father and son. She
heard the door open, the old man's stern tone, Robert's gay reply;
and in a twinkling more the two were sitting together over the fire,
the father splitting his sides with half-unwilling laughter at the boy's
inimitable descriptions and mimicry of the scenes he had left. Nearly
two hours they sat there in this way, the mother all the while
cramming the bed-clothes into her mouth, lest her own laughter
should remind her husband how poorly he was carrying out his
threats. After that night "Rob" came home at what hour he pleased,
and there was nothing more heard of his father's sitting up to
reprove him.
They believed that Burns's intemperate habits had been greatly
exaggerated. Their mother was a woman twenty-five years old, and
the mother of three children when he died, and she had never once
seen him the "waur for liquor." "There were vary mony idle people i'
the warld, an' a great deal o' talk," they said. After his father's death
he assumed the position of the head of the house, and led in family
prayers each morning; and everybody said, even the servants, that
there were never such beautiful prayers heard. He was a generous
soul. After he left home he never came back for a visit, however
poor he might be, without bringing a present for every member of
the family; always a pound of tea for his mother, "and tea was tea
then," the old ladies added. To their mother he gave a copy of
Thomson's "Seasons," which they still have. They have also some
letters of his, two of which I read with great interest. They were to
his brother, and were full of good advice. In one he says:—
"I intended to have given you a sheetful of counsels, but
some business has prevented me. In a word, learn
taciturnity. Let that be your motto. Though you had the
wisdom of Newton or the wit of Swift, garrulousness
would lower you in the eyes of your fellow-creatures."
In the other, after alluding to some village tragedy, in which great
suffering had fallen on a woman, he says,—
"Women have a kind of steady sufferance which qualifies
them to endure much beyond the common run of men;
but perhaps part of that fortitude is owing to their short-
sightedness, as they are by no means famous for seeing
remote consequences in their real importance."
The old ladies said that their mother had liked "Jean" on the whole,
though "at first not so weel, on account of the connection being
what it was." She was kindly, cheery, "never bonny;" but had a good
figure, danced well and sang well, and worshipped her husband. She
was "not intellectual;" "but there's some say a poet shouldn't have
an intellectual wife," one of the ingenuous old spinsters remarked
interrogatively. "At any rate, she suited him; an' it was ill speering at
her after all that was said and done," the younger niece added, with
real feeling in her tone. Well might she say so. If there be a touching
picture in all the long list of faithful and ill-used women, it is that of
"bonnie Jean,"—the unwedded mother of children, the forgiving wife
of a husband who betrayed others as he had betrayed her,—when
she took into her arms and nursed and cared for her husband's
child, born of an outcast woman, and bravely answered all curious
questioners with, "It's a neebor's bairn I'm bringin' up." She wrought
for herself a place and an esteem of which her honest and loving
humility little dreamed.
There is always something sad in seeking out the spot where a great
man has died. It is like living over the days of his death and burial.
The more sympathetically we have felt the spell of the scenes in
which he lived his life, the more vitalized and vitalizing that life was,
the more are we chilled and depressed in the presence of places on
which his wearied and suffering gaze rested last. As I drove through
the dingy, confused, and ugly streets of Dumfries, my chief thought
was, "How Burns must have hated this place!" Looking back on it
now, I have a half-regret that I ever saw it, that I can recall vividly
the ghastly graveyard of Saint Michael's, with its twenty-six thousand
gravestones and monuments, crowded closer than they would be in
a marble-yard, ranged in rows against the walls without any
pretence of association with the dust they affect to commemorate.
What a ballad Burns might have written about such a show! And
what would it not have been given to him to say of the "Genius of
Coila, finding her favorite son at the plough, and casting her mantle
over him,"—that is, the sculptured monument, or, as the sexton
called it, "Máwsolem," under which he has had the misfortune to be
buried. A great Malvern bathwoman, bringing a bathing-sheet to an
unwilling patient, might have been the model for the thing. It is
hideous beyond description, and in a refinement of ingenuity has
been made uglier still by having the spaces between the pillars filled
in with glass. The severe Scotch weather, it seems, was discoloring
the marble. It is a pity that the zealous guardians of its beauty did
not hold it precious enough to be boarded up altogether.
The house in which Burns spent the first eighteen months of his
dreary life in Dumfries is now a common tenement-house at the
lower end of a poor and narrow street. As I was reading the tablet
let into the wall, bearing his name, a carpenter went by, carrying his
box of tools slung on his shoulder.
"He only had three rooms there," said the man, "those three up
there," pointing to the windows; "two rooms and a little kitchen at
the back."
The house which is usually shown to strangers as his is now the
home of the master of the industrial school, and is a comfortable
little building joining the school. Here Burns lived for three years;
and here, in a small chamber not more than twelve by fifteen feet in
size, he died on the 21st of July, 1796, sadly harassed in his last
moments by anxiety about money matters and about the
approaching illness of his faithful Jean.
Opening from this room is a tiny closet, lighted by one window.
"They say he used to make up his poetry in here," said the servant-
girl; "but I dare say it is only a supposeetion; still, it 'ud be a quiet
place."
"They say there was a great lot o' papers up here when he died,"
she added, throwing open the narrow door of a ladder-like stairway
that led up into the garret, "writin's that had been sent to him from
all over the world, but nobody knew what become of them. Now
that he's so much thought aboot, I wonder his widow did not keep
them. But, ye know, the poor thing was just comin' to be ill; that
was the last thing he wrote when he knew he was dyin', for some
one to come and stay with her; and I dare say she was in such a
sewither she did not know about anything."
The old stone stairs were winding and narrow,—painted now, and
neatly carpeted, but worn into depressions here and there by the
plodding of feet. Nothing in the house, above or below, spoke to me
of Burns so much as did they. I stood silent and rapt on the landing,
and saw him coming wearily up, that last time; after which he went
no more out forever, till he was borne in the arms of men, and laid
away in Saint Michael's graveyard to rest.
That night, at my lonely dinner in the King's Arms, I had the
Edinburgh papers. There were in them three editorials headed with
quotations from Burns's poems, and an account of the sale in
Edinburgh, that week, of an autograph letter of his for ninety-four
pounds!
Does he think sadly, even in heaven, how differently he might have
done by himself and by earth, if earth had done for him then a tithe
of what it does now? Does he know it? Does he care? And does he
listen when, in lands he never saw, great poets sing of him in words
simple and melodious as his own?
"For now he haunts his native land
As an immortal youth: his hand
Guides every plough;
He sits beside each ingle-nook,
His voice is in each rushing brook,
Each rustling bough.

"His presence haunts this room to-night,


A form of mingled mist and light
From that far coast.
Welcome beneath this roof of mine!
Welcome! this vacant chair is thine,
Dear guest and ghost!"[8]

GLINTS IN AULD REEKIE.

As soon as one comes to know Edinburgh, he feels a gratitude to


that old gentleman of Fife who is said to have invented the
affectionate phrase "Auld Reekie." Perhaps there never was any such
old gentleman; and perhaps he never did, as the legend narrates,
regulate the hours of his family prayers, on summer evenings, by the
thickening smoke which he could see rising from Edinburgh
chimneys, when the cooking of suppers began.
"It's time now, bairns, to tak the beuks an' gang to our beds; for
yonder's Auld Reekie, I see, putting on her nichtcap," are the words
which the harmless little tradition puts into his mouth. They are
wisely dated back to the reign of Charles II., a time from which none
now speak to contradict; and they serve as well as any others to
introduce and emphasize the epithet which, once heard, is not
forgotten by a lover of Edinburgh, remaining always in his memory,
like a pet name of one familiarly known.
It is not much the fashion of travellers to become attached to
Edinburgh. Rome for antiquity, London for study and stir, Florence
for art, Venice for art and enchantment combined,—all these have
pilgrims who become worshippers, and return again and again to
them, as the devout return to shrines. But few return thus to
Edinburgh. It continually happens that people planning routes of
travel are heard to say, "I have seen Edinburgh," pronouncing the
word "seen" with a stress indicating a finality of completion. Nobody
ever uses a phrase in that way about Rome or Venice. It is always,
"We have been in," "spent a winter in," "a summer in," or "a month
in" Rome, or Venice, or any of the rest; and the very tone and turn
of the phrase tell the desire or purpose of another winter, or
summer, or month in the remembered and longed-for place.
But Edinburgh has no splendors with which to woo and attract. She
is "a penniless lass;" "wi' a lang pedigree," however,—as long and as
splendid as the best, reaching back to King Arthur at least, and
some say a thousand years farther, and assert that the rock on
which her castle stands was a stronghold when Rome was a village.
At any rate, there was a fortress there long before Edinburgh was a
town, and that takes it back midway between the five hundredth and
six hundredth year of our Lord. From that century down to this it
was the centre of as glorious and terrible fighting and suffering as
the world has ever seen. Kingly besieged and besiegers, prisoners,
martyrs, men and women alike heroic, their presences throng each
doorway still; and the very stones at a touch seem set ringing again
with the echoes of their triumphs and their agonies.
To me, the castle is Edinburgh. Looking from the sunny south
windows of Prince's Street across at its hoary front is like a wizard's
miracle, by which dead centuries are rolled back, compressed into
minutes. At the foot of its north precipices, where lay the lake in
which, in the seventeenth century, royal swans floated and plebeian
courtesans were ducked, now stretches a gay gardened meadow,
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like