Object Oriented Programming With C Sharma A K download
Object Oriented Programming With C Sharma A K download
download
https://ebookbell.com/product/object-oriented-programming-with-c-
sharma-a-k-22104554
https://ebookbell.com/product/object-oriented-programming-with-c-4th-
edition-e-balagurusamy-33727398
https://ebookbell.com/product/object-oriented-programming-
with-c-2e-second-edition-sahay-5428484
https://ebookbell.com/product/object-oriented-programming-with-c-
second-2-mtsomashekar-7293580
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
https://ebookbell.com/product/deciphering-objectoriented-programming-
with-c-a-practical-indepth-guide-to-implementing-objectoriented-
design-principles-dorothy-r-kirk-46453652
https://ebookbell.com/product/demystified-objectoriented-programming-
with-c-1st-edition-dorothy-r-kirk-23773056
https://ebookbell.com/product/beginning-objectoriented-programming-
with-c-1st-edition-jack-purdum-2626948
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
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
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
Appendix 333
Index 335
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
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.
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.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
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
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;
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;
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
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
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.
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
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.
{
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
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 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++
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.
(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.
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.
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)
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
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
E1 ? E2 : E3
false
It may be noted here that the conditional operator (? :) is also known as a ternary operator
because it operates on three values.
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.
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).
(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.
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.
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.
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.
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++
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.
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.
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.
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.
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:
#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++
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.
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.
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.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
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++
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
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
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]
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
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,"
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,"
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,"
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.
ebookbell.com