Programming With C++ - (Chapter 1. Introduction To C++)
Programming With C++ - (Chapter 1. Introduction To C++)
++
Computer has become an essential element of our modern society. Work in offices, factories,
selling outlets, research and development laboratories, teaching, telecommunication, sports, and
even home entertainment are all being controlled by computers. Not only that, most of our
future developments are closely linked with the developments in computer systems which involve
development in hardware as well as software. This is reflected in the rapid developments in
computer hardware that we see today. Super computers that are capable of doing trillions of
instructions per second is the talk of the day. The personal computers whether desktops or laptops
have capabilities and speeds much better and prices much less than the mainframe computers of
just a decade ago. Only machines are not enough. Robust and efficient software is needed to make
these machines to perform to the fullest extent. Computer languages are the bases of efficient
software.
A typical computer hardware (Fig. 1.1) consists of one or more microprocessor chips
connected to the supporting chips and other electronic circuits. These chips include cache and
primary memory chips usually called RAM (Random Access Memory). Besides, the
microprocessor is also connected to bulk storage memory devices such as floppy disc, CD ROM
(Compact Disc Read only Memory), hard disc and magnetic tapes etc. The microprocessor chip
which is the main chip is also called CPU (Central Processing Unit). Its internal structure consists
of circuits which form a number of registers (typical number is 16), an arithmetic unit, a logic
unit and a control unit. It has large number of terminals for connection to external devices (for
instance a typical CPU has as many as 478 terminals). Out of these a group of terminals is for
data input and data output, another group is for memory addresses and still another group for
Copyright © 2009. New Age International Ltd. All rights reserved.
control purposes. Besides, several terminals are for interrupt service. An interrupt is like gate
crashing. Suppose some program is being processed in the computer and you interrupt that program
and start your own program. The computer first saves the ongoing program status, takes up your
item, and after finishing work on it, it resumes the ongoing program. Every CPU supports a set
of instructions designed by its manufacturer. We need not go into details of the complex circuitry,
however, some of the names mentioned above are often used in software and a programming
student should be familiar with them. A beginner in programming will most probably be using a
desktop personal computer (PC). A typical PC cabinet is illustrated in Fig. 1.2. The input/output
devices that a reader would in general come across are shown in Fig. 1.3.
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
❖ 2 ❖ Programming with C++
Fig. 1.1: Components of a computer system. Bus lines carry electrical pulses
from one device to another. Arrows show the data flow
Output port
Computer circuits
A
code
Copyright © 2009. New Age International Ltd. All rights reserved.
Input
port
Code output
Voltages
5 000005 Display of output
applied
Monitor - Default output device
1000001 for C++
Code
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
Introduction to C++ ❖ 3❖
MACHINE LANGUAGE
As already mentioned, a computer is a collection of electronic circuits driven by application of
high voltage (typical value is 5 volts) at some points and low voltage (typical value is 0) at other
points in the circuit. We may designate (code) high voltage as 1 and low voltage as 0. Thus the
basic code for computer instructions consists of sequences of 1s and 0s such as 00111110. The
values of variables, which are numbers, can also be represented in binary numbers (discussed later
in the chapter) which are also sequences of zeros and ones. Thus a program which comprises
instructions and data may be written as a series of sequences of zeros and ones. There are different
instruction formats (combinations of opcodes, codes and data) so that the processor can make
out which sequence of 0s and 1s is instruction and which is data. The first number in an
instruction is opcode followed by data. Some instructions may not have any data to act upon.
The complete set of these instructions for a CPU is called machine language code or simply
machine language. This is the language which machine understands.
A program written in machine language will consist of a large number of sequences of 0s
and 1s. It is very difficult to write such programs and debug them in case there is an error. Besides,
the instruction codes for processors made by different manufacturers are different for the same
process such as addition or storage of a value etc., therefore, the program written in one machine
language for one microprocessor will only work on computers having similar microprocessor but
will not work on computers based on other microprocessors. That is to say, there is no portability
of these programs. Moreover, it is very cumbersome to write and debug programs in binary codes
or to convert a program made for one make of CPU to another make of CPU. These two factors
have provided impetus for development of high level programming languages which should
be easy to understand, debug and be portable.
Assembly language is the next development. In this the instructional codes have been
converted to more readable forms, for example, for one processor instruction such as MOV AX
116 means move the immediate data that is 116 to destination register AX. The word MOV
is short form of MOVE. Assembly language instructions such as MOV, ADD which stands for
addition, SUB which stands for subtraction etc. are called mnemonics. A program written in
assembly language needs a software called assembler which converts the program consisting of
mnemonics and data into machine language. In this case also the programs are not portable.
Nevertheless, the programs written in assembly language are easier to read as well as easier to
debug than those written in machine language.
Copyright © 2009. New Age International Ltd. All rights reserved.
In the development of a high level language there has always been an endeavour to make the
language as near to the language that we speak as possible. It is worthwhile to note that the
programs written in machine language are the most efficient in execution, because there is nothing
between the code and the machine as is the case with high level languages. All high level computer
languages need a compiler or interpreter to convert the program instructions and data into
machine language for its execution, because, the machine understands only its own language, i.e.
sequences of 0s and 1s.
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
❖ 4 ❖ Programming with C++
C LANGUAGE
BCPL was one of the earliest high level computer language developed in 1967 by Martin Richards
for writing operating system which is a software needed to control various processes in computer
applications. Later the language B was developed by Ken Thompson who added many new
features in the language.
C was developed mainly from B by Dennis Ritche. Soon C became popular with
programmers and it remained so for several decades. It is still used in several applications. It is a
structured high level language. Programs written in C are easy to write and debug as well as the
programs are portable. The code is nearest to the assembly language and thus is quite efficient.
However, the code written in C language needs a compiler to convert the different instructions
and data into machine language.
Because of popularity of C many companies produced compilers for C. A compiler is a
software which converts the program into machine language. Because of the widespread use of
C, it became necessary to standardize the syntax and functions of the language so that the
programs could run with compilers developed by different organizations and on different plat-
forms. The American National Standard Institute (ANSI) prepared a standard document for C
as a national standard which later with some modifications was also adopted by ISO
(International Organization for Standardization) as an international standard. The first standard
C document was published in 1990. It is known as ISO/IEC 9899-1990, Programming
Language – C. The C language according to this document is also called C-90.
With further development of C, it became necessary to revise the earlier standard. The revised
standard was ratified by ISO in 1999. The document is known as ISO/IEC 9899-1999,
Programming language – C. The language according to this standard is known as C - 99 and
it is in vogue at present.
In order to meet the variety of demands from the real world problems, several computer
languages have been developed over the same period. These languages are more tuned to the
typical applications that these languages are put to. The number of these languages is quite large
and it is difficult to give even brief discussions of all these languages. Many of these could not
gain any popularity and are dead. However, some of these became popular and have been in use
for a number of years. The popular ones are Basic and Visual Basic, Cobol, Fortran, Logo, Prolog,
Pascal, Lisp, Ada, Simula, Smalltalk, etc. After the development of C++, another language Java
has been developed. Java is more user friendly. However, C++ is a very versatile language and finds
applications in many diverse fields and hence is very popular.
Copyright © 2009. New Age International Ltd. All rights reserved.
In eighties an average large C program was of the order of a few thousands of lines of code. With
really large programs the difficulties with C language became more apparent and researchers were
busy finding better options. C++ is a redevelopment of C carried out by Bjarne Stroustrup when
he was working with AT&T during 1983-1985. Inspired by the language Smalltalk and Simula
which are object oriented programming (OOP) languages, he added the concept of classes, in
order to impart similar capabilities in the then widely popular C language. Classes are the basis
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
Introduction to C++ ❖ 5❖
of OOP. Initially the new language was called C with classes. The name C++ was coined later
by Rick Mascitti in 1983. The symbol (++) is an operator in C which increases the value of an
integer variable by 1. The name C++ aptly shows that C++ is oneup on C. The C++ is also often
called as better C.
The C++ programming language became popular soon after it was officially launched. As a
result, scores of programmers got involved, who have not only tested the codes and recognised
the pitfalls, but have also added reusable program modules to C++ Standard Library which is a
large collection of well tested and reusable programs which facilitate the writing and execution
of diverse applications. It became necessary to standardise C++ as well. So an ISO committee
was formed in 1995 and C++ standard was ratified by ISO in 1998. The document is officially
known as ISO/IES 14882-1998, Programming Language – C++. The language according to
this standard is briefly referred to as C++ 98. Later a revise version of the standard with minor
corrections and clarifications was published in 2003. This document is known as ISO/IEC
14882::2003. This is the standard being followed at present. This is also available in the book
form with name “The C++ Standard” and published by John Wiley Ltd.
In fact, there has been continuous development in the language. Addition of inheritance of
classes, operator overloading and polymorphism has enhanced the application of the language.
The addition of template functions and template classes has given rise to generic programming.
A remarkable enhancement to the language is the addition of Standard Template Library as a part
of C++ Standard Library. These programs can be used straightway by the programmers to create
new applications as well as new programs. Addition of namespace has added additional flexibility
in combining programs written by different programmers without running the risk of ambiguity
of same names being used for different variables in different sections of the program. These
developments in C++ have enhanced the capabilities of C++ enormously. A very large program
may be broken into small modules and classes, which may be developed by different programmers
and tested for their performance before combining them into one large program. These
developments have given extensive capability to C++ to have reusable program modules and
classes which comprise the C++ Standard Library.
There has been continuous effort for upgrading C++ by way of adding new algorithms,
applications and other additions such as namespace, etc. It is really difficult to make a detailed
list of all these items, however, below only major developments are listed which are responsible
for major advantages of using C++ over C.
Copyright © 2009. New Age International Ltd. All rights reserved.
(1) Classes which provide a mechanism for data abstraction, encapsulation of data and
functions, information hiding and object oriented programming.
(2) Operator overloading.
(3) Inheritance.
(4) Polymorphism.
(5) Addition of namespaces.
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
❖ 6 ❖ Programming with C++
(6) Template functions and template classes which lead to generic programming.
(7) Addition of STL ( Standard Template Library).
(8) Many new keywords.
C++ allows procedural programming as well as object oriented programming and generic
programming. In seventies and eighties generally procedural programming were used for short
as well for long programs which comprised a few thousands to hundred thousands lines of
code. The present day big programs comprise millions of lines of code. In procedural
programming, there are many problems in production of really large programs. Debugging is
one major problem. Even after successful implementation the maintenance of the software is
not easy. It is difficult for a new programmer to comprehend the different sections of the
program.
The inclusion of classes has added the advantage of object oriented programming to C++,
though, it is also an efficient language in procedural programming. The inheritance of classes in
C++ has also made easy to reuse the existing class programs. If you have made a class program,
verified and tested and later you wish to add new things into it, you can do it without modifying
the tested and verified program. You simply make another class program which inherits the
existing class and adds the new features into it. The original program remains intact and is used
in the new program without any modification. Later on you can make still another class which
inherits any one or both of the already developed classes and adds new features to the whole
program. This allows a continuous addition of new features in an already running program
without disturbing the existing classes.
Operator overloading gives the facility for applying the same operators that we use for
fundamental types to the class objects as well. Thus the operations on vectors, complex numbers,
strings and other class objects are made easier. The operator overloading gives a large extension
to C++.
The addition of inheritance and polymorphism in C++ has extended the scope of use of
existing software. A big program may be designed to comprise convenient reusable components
or modules comprising different classes. It is possible to extend or modify the components as
explained above in case of classes. The various sub-programs may be re-assembled in different
ways to make new programs. Debugging of a big program becomes easy because each class and
module can be tested and verified independently of the whole program. Another major advantage
Copyright © 2009. New Age International Ltd. All rights reserved.
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
Introduction to C++ ❖ 7❖
For learning C++ it is not necessary to first learn C. If you already know C it will certainly help,
because, the concepts in procedural programming are similar. If you do not know C there is
nothing to worry because C++ is best learned on its own and you would be avoiding confusion
because of some differences in syntax in the two languages.
C++ has now emerged as one of the most advanced and most popular computer language
developed so far and has highest diversity in its applications. A comprehensive list of applications
has been compiled by Bjarne Stroustrup, the originator of C++ himself and is available on internet
at the following address.
http://www.research.att.com/~bs/applications.html
The list includes the names of companies who have developed many different softwares for
diverse applications and in which C++ has been used. Here we list some of the application fields
in which C++ has been used for producing software. These are listed below. The list is largely
based on the above mentioned reference.
The interested reader should consult the above mentioned internet site of Bjarne Stroustrup
for more information.
For execution of programs written in C++ you need to load a compiler software on your
computer. The function of compiler is to compile the program that you have written and present
the code to computer in machine language for execution. Besides this, the compilers in integrated
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
❖ 8 ❖ Programming with C++
development environment also assist the programmers by pointing out the mistakes in the
program listing. This aspect is very useful for learning C++, because, not only beginners even
experienced programmers would make mistakes in writing the code and if the compiler does not
point it out, the programmers will have to struggle hard to find it out. This an excellent facility
and a beginner should get acquainted with the error pointed out by compiler and the remedial
action. This can best be done by first have a correct program, then introduce different types of
errors one by one and find the response of compiler. A few trials will acquaint a beginner with
the common errors and the remedial actions needed for them.
There are many compilers available in market. Some are free and may be downloaded from
internet. Some are paid but available on trial basis for a specified period while others are on
payment systems. The reader is advised to see following internet sites for obtaining more
information.
(i) An incomplete list of C++ Compilers - by Bjarne Stroustrup at following address.
http://www.research.att.com?~bs?compilers.html
(ii) Google Directory of C++ compilers – at the following address.
http://www.rafb.net/efnet_cpp/compilers
Some of the free compilers for windows are given below.
(i) Borland C++ 5.5
(ii) Dev-C++
(iii) LCC-Win32
(iv) Microsoft Visual C++ Toolkit 2003
For Multi-platform a free compiler is
(i) GCC
For imbedded C++ applications a free compiler is
(i) djgpp for intel 80386 ( and higher)
It is better to start with an integrated development environment (IDE) like MS Visual C++ 6.
It is a rich collection of programs on classes, functions and template classes and template
functions which are helpful in program writing and in its execution. Every program requires
Copyright © 2009. New Age International Ltd. All rights reserved.
applications of several functions of C++ Standard Library. These functions are included in the
program by including the header files which contain these functions (see Chapter 2 for header
files). Standard Template Library (STL) has also been made part of C++ Standard Library. STL
mainly comprises container classes such as vectors, lists, deque, associative containers such as sets,
multisets, maps, multimaps, etc. and near-containers such as C++ strings, etc. Also it has iterator
classes which help in traversing through the containers. These programs can be directly used by
a programmer to create different applications. Besides, there are more than 70 algorithms in STL
which may be used by programmers for creating new applications and programs. All these are,
in general, supported by C++ compilers of good companies.
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
Introduction to C++ ❖ 9❖
The start is made by installing one of the compilers described above on the computer. However,
for a beginner it is better to work with an IDE like MS Visual C++ 6, which does text editing,
compiling, linking and makes a binary file of the source code (the program typed by the
programmer) which is loaded on to RAM for execution. A C++ program consists of a sequence
of statements typed by the programmer from top to bottom with the help of text editor. It is
presumed that a beginner will go through the documents provided with the compiler regarding
the instructions for its loading and running. The programmer after typing the program, can direct
for compiling. The programmer may get a list of syntax errors in the typed version of the
program. Some compilers also indicate the location of the error (the line in which error is there)
in the program. The programmer should correct these errors and again direct for compiling.
When the text of the program is error free, the programmer can direct for run or build the
program. The different elements in the process of making, compiling and running a program
are also illustrated in the Fig. 1.4. See Appendix E for starting with Microsoft Visual C++ 6.0.
Copyright © 2009. New Age International Ltd. All rights reserved.
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
❖ 10 ❖ Programming with C++
All these processes are integrated, a programmer has only to type the program, give direction
to compile, correct any error if indicated and then give direction to run the program. The various
processes illustrated in the figure are internal to the compiler.
With the development of programming languages the different programming techniques also
evolved. The distinguishable techniques are listed below.
1. Unstructured or monolithic programming.
2. Procedural Programming
3. Modular Programming
4. Object oriented Programming
For C++ we are mainly concerned with procedural programming and object oriented
programming. However for sake of being able to appreciate the differences, all the techniques
are described briefly below.
UNSTRUCTURED/MONOLITHIC PROGRAMMING
The general structure of a monolithic program consists of global data and statements which
modify the data and finally it contains the output statements. A sample is shown in Fig.1.5.
// Main program
Data
Statement1
Statement2
Statement
——————
Statement1
Statement2
end
Fig. 1.5: Programming in an unstructured programming language
The program is executed from top to bottom, statement by statement. If similar evaluations
are to be carried out at several places in the program, for example, statement1 and statement2
in above illustration, all the statements concerning that evaluation have to be repeated at all the
Copyright © 2009. New Age International Ltd. All rights reserved.
places where the evaluation is desired. This makes the program very lengthy. Besides, any
modification in the process of the evaluation has to be corrected at so many places in the
program. Such programs are lengthy, difficult to debug and difficult to maintain.
PROCEDURAL PROGRAMMING
These programs are an improvement over the monolithic programs. If a group of statements carry
out similar action at several places in the program, such a group is taken out of the main program
and is placed in a subprogram called subroutine or procedure or function. In the main program
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
Introduction to C++ ❖ 11❖
the subroutines or functions are called. When a subroutine is called, the main program is paused
and control shifts to the subroutine till it is finished. Its return value if any is fed to the main
program which is resumed from where it was left. It is illustrated in Fig.1.6.
// Main Program
Global data Procedure1 or Subroutine1
Statement Statement
Statement Statements
——————— —————
Statement
Statement
Statement
Statement Procedure2
————- Statement
Statement Statement
Statement ————
Statement
——————
Statement
end
Fig. 1.6: Procedural programming
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
❖ 12 ❖ Programming with C++
MODULAR PROGRAMMING
In this type of programming the similar procedures are grouped together into modules. Thus
the whole program may consist of modules and connecting statements. The main program
supplies data and co-ordinates the different modules. It is illustrated in Fig.(1.7).
In this technique an important factor is the data abstraction. The different procedures or
functions are built around the abstract data. Thus the data and functions are encapsulated in a
single structure called ‘class’. The classes are the bases of object oriented programming (OOP).
The classes create new data types besides the fundamental types which are already defined in C++.
In a class, the different functions/procedures are defined according to the data that an object of
the class must have. In the following the concept of classes and objects are explained with
analogies from the physical world.
and class Tigers and class Women. For the class Tiger a particular tiger say the one in the zoo is
an object of this class. Also the authors and the reader of this book are objects or instances of
class Humans. The class Humans would describe the general characteristics of all humans.
Similarly class Men describes the specialised functions which apply only to men. Any particular
man is an instance or an object of the class Men. The same argument applies to many other
objects. For instance, a line is made by points, polygonal shapes are made by lines. Thus we may
make a class Point which deals with points, class Line may be derived from class point and so
on.
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
Introduction to C++ ❖ 13❖
DATA ABSTRACTION
Every object of real world has a large amount of data associated with it. The data describes various
characteristics, some of which may be common with other objects. But for a program which is
limited by its purpose and scope some of the data associated with objects of a class may not be
useful for the purpose of the program and hence may not be needed. We have to select the data
most appropriate for the purpose of the program as well as it should be uniformly applicable
to all the objects of the class, for which the program is being prepared. In fact, if we make a
model of the behaviour of the objects of the class, the desired data in the model is the abstract
data.
data as planned in the program. In fact, the whole program is before the user who can easily
temper with data members and functions. In case of class, the function call is linked with an
object of the class. The functions of a class can not be called without linking it with the object.
Thus a class program gets implemented only if at least one object is validly defined with its data
on which the functions of the class may operate. A class program is only for its objects. The kind
of data that the objects must possess so that they can become objects of the class is also defined
by the constructor function or another public function in the class declaration. Below is an
example of simple class with name Rectangle. Statements that follow double slash (//) are
comments and are not part of the program. The first 9 lines comprise the class declaration.
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
❖ 14 ❖ Programming with C++
The main program starts after this. At this stage many readers are not acquainted with some of
the statements and key words written below, nevertheless, one can make out the difference
between this and the procedural programming.
The statements after // are the comments. They are not part of program. Following is the output
of the two cout statements in the main program.
Copyright © 2009. New Age International Ltd. All rights reserved.
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
Introduction to C++ ❖ 15❖
INFORMATION HIDING
Classes also allow the hiding of the data members as well as some function members by declaring
them as private in the class declaration. This is illustrated in the above program in which int
length and int width are declared as private. Private members are accessible only through other
functions declared public in class declaration. Private data and functions are not directly accessible
even by the objects of the class. The objects of class may access its public data and function
members.
The class itself may be hidden from the user who only includes it (includes the name of class)
in the program and deals with the interface provided by public functions in the class like
Setsides () and Area () in the above example. In case of class program, a user of the program is
like a driver of a car who only knows about pedals (accelerator, clutch and brake) and steering
wheel and light switches which are the public interfaces or we may call them as public functions.
The driver does not know the complex mechanism behind the pedals and steering wheel. In fact,
a driver need not know all that just for driving the car. Similarly in a class program, the data and
some member functions may be totally hidden from the user of the program. Because after a
class code has been tested, debugged and verified we may store in a separate file. The class code
may not be available to user who only includes the relevant filename in his/her program. Besides
a class may be derived from another class which also may be having private members. The
intention is to hide as much as possible from the user of the program and classes provide the
mechanism for this. This is called information hiding.
In most of the programs, we often use operators such as +, –, /, etc. These are used for operations
like addition, subtraction, division, etc. Let us take operator +. This operator is defined to add
two integers or two decimal point numbers. Now if you want to add two vectors this operator
will not work because a vector has a magnitude and a direction. To overcome the problem of
direction, in vector mathematics, we add components of vectors. For example in case of two
dimensional vectors, x-component of vector A is added to x- component of vector B and y-
component of vector A is added to y-component of vector B. Here the vectors are shown by
bold letters. Let Ax and Ay be components of A and Bx and By be components of B. Let C be
the resultant vector with components Cx and Cy. So the addition of A and B is expressed as below.
Cx = Ax + Bx
Copyright © 2009. New Age International Ltd. All rights reserved.
Cy = Ay + By
We can, however, overload the operator + to carry out above additions, that is, we redefine
the functionality of + operator so that it will do the above two additions and will find Cx and
Cy.
With this facility we can write the following code in our program.
C=A+B;
This statement will do Ax + Bx and assign it to Cx and do Ay + By and assign it to Cy. Thus
we can do vector addition with the same operator +. This is called operator overloading.
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
❖ 16 ❖ Programming with C++
Similarly other operators may also be overloaded if so needed. You will yourself appreciate that
such a provision gives a tremendous extension to C++. There are many applications of operator
overloading such as in manipulation of vectors, complex numbers, matrices, any object that is
represented by more than one value can be dealt with the help of operator overloading.
1.12 INHERITANCE
We have already discussed that classes may be formed for the objects which have some common
characteristics. These characteristics are passed on to the classes that are derived from the base class.
The derived class inherits the base class without any modification while it may add more
specialized characteristics to the objects. The process is called inheritance. There is no end to the
process of inheritance. One may derive another class which inherits any one or more of the already
derived classes. Inheritance makes it possible to reuse an already tested and working class program.
Thus a big program may be divided into such classes which may be useful in the present program
as well as other programs. The Fig.1.9 illustrates the application of inheritance.
For sake of illustration let us consider two dimensional space. We all know that a line is made
of points, other shapes say polygons are made out of lines. The shapes like square, rectangle and
hexagon are polygonal shapes. Therefore, the functions of class Point are also useful in class Line.
Similarly the functions of class Line are useful in class Polygons and that of polygons are useful
in classes Square, Rectangle and Hexagon. Therefore, the upstream classes may simply be
inherited instead of repeating their code again and again in downstream classes.
class Polygons
Polygons
Thus inheritance helps in the reuse of the already established software. In the chain of
inheritances shown in Fig.1.8, the class Point is base class for class Line. Similarly the class Line
Copyright © 2009. New Age International Ltd. All rights reserved.
is base class for class Polygon which is also base class for class Square, class Rectangle, etc. A class
may have more than one class as base classes. An object of class Square is also an object of class
polygon but an object of class Polygon is not an object of class Square. This is because class
Polygon does not know about the classes downstream like class Square.
1.13 POLYMORPHISM
Polymorphism is a Greek word which means the ability to take different forms. In the previous
section we have seen how the operator + may be overloaded to carry out different operations.
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
Introduction to C++ ❖ 17❖
This is an example of polymorphism. However, in such cases the choice of function is known
at the compile time itself. Therefore, this is called static binding or early binding. The run time
binding or late binding or dynamic binding is one in which the choice of appropriate function
is carried out during execution of the program (Fig.1.9). This is realised through declaration of
virtual functions in the base class and by use of base class pointer. A pointer is a variable whose
value is the address of another object to which it points.
Since computer operations are ultimately connected to manipulation of numbers in the binary
form, it is worthwhile to know about different number systems which will be often used in the
programs. Below we deal with the number systems such as decimal, binary, octal and hexadecimal
systems. We normally use decimal system in our daily life calculations. This is a system with base
10 and digits are 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. Perhaps mankind started counted on fingers and
there are ten fingers so is the base of our number system. Suppose we have a number 456, it can
be written as below.
4 × 102 + 5 × 101 + 6 × 100 = 400 + 50 + 6 = 456
Here you see that apart from the value of digit, its position in the number also matters. In
456, the first digit 6 is at unit place and has value 6 while the digit 5 is at a place next to unit
and which has place value 10. Therefore, this 5 has value 5 ×101 = 50. Similarly the digit 4 is
at hundredth place has value 4 ×102 = 400
However, computer systems work on binary system. Binary system has a base 2. In a binary
number such as 1110111, the digit at unit place (right most) has place value 20 = 1. For the next
digit, the place value is 21 = 2. So if the digit is 0 its value is 0 but if the digit is 1 its value is 2.
Similarly the digit at hundredth place has place value = 1 ×22 , i.e. 4. In other words, digit 1 in
the hundredth place is equivalent to 4. Below we have tabulated the conversion of decimal
numbers from 0 to 10 to binary numbers.
Copyright © 2009. New Age International Ltd. All rights reserved.
0 0 0 × 20 = 0
1 1 1 × 20 = 1 × 1 = 1
2 10 1 × 21 + 0 × 20 = 2 + 0 = 2
3 11 1 × 21 + 1 × 20 = 3
4 100 1 × 22 + 0 × 2 1 + 0 × 2 0 = 4
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
❖ 18 ❖ Programming with C++
5 101 1 × 22 + 0 × 21 + 1 × 20 = 5
6 110 1 × 22 + 1 × 21 + 0 × 20 = 4 + 2 = 6
7 111 1 × 22 + 1 × 21 + 1 × 20 = 4 + 2 + 1 = 7
8 1000 1 × 23 + 0 × 22 + 0 × 21 + 0 × 20 = 8
9 1001 1 × 23 + 0 × 22 + 0 × 21 + 1 × 20 = 9
10 1010 1 × 23 + 0 × 22 + 1 × 21 + 0 × 20 = 8 + 2 = 10
Numbers with base 8 and base 16 are also used. The numbers of digits in the different systems
are given in Table 1.1.
Table – 1.1
2 456
2 228 – 0
2 114 – 0
2 57 – 0
2 28 – 1
Copyright © 2009. New Age International Ltd. All rights reserved.
2 14 – 0
2 7–0
2 3–1
2 1–1
0–1
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
Introduction to C++ ❖ 19❖
Fig. 1.11
The same number 456 may also be written in octal or hexadecimal system as well. We repeat
the exercise of Fig.1.10 for octal and hexadecimal systems as shown in Fig.(1.11a) and Fig. (1.11
b) respectively. The following table shows the number 456 in different number systems.
Table – 1.2
In a computer program the octal numbers are preceded by 0 (zero) and hexadecimal numbers
are preceded by 0x or 0X. Thus 456, in octal is 0710 and in hexadecimal it is written as 0X1C8.
For conversion from binary to octal or hexadecimal see the following grouping of digits.
Binary equivalent of 456 111 001 000
Octal 7 1 0
Binary equivalent of 456 1 1100 1000
Hexadecimal 1 C 8
For converting binary into octal, make groups of binary digits with three digits in each group
starting from extreme right. The decimal digit represented by each group is the digit in octal
representation. In the above example, starting from right, the first group of three binary digits
are all zero. So the octal digit is also zero. The second group 001 is equivalent to octal 1. The
third group 111 is equivalent to 7. So the number in octal representation is 0710.
Similarly for the hexadecimal representation from binary, make groups of four binary digits
as illustrated above. Make a hexadecimal digit out of the four binary digits. The right most group
(1000) evaluates to 8. The next group 1100 evaluates to 12 in decimal which is C in hexadecimal.
Copyright © 2009. New Age International Ltd. All rights reserved.
The last group is only 1. So the number 456 in hexadecimal representation is 0X1C8 or 0x1c8.
In a program, decimal numbers should not be preceded by zero ( 0).
FRACTIONAL NUMBERS
In a decimal system a fractional or a decimal point number say 456.25 may be written as
456.25 = 4 × 102 + 5 × 101 + 6 × 100 + 2 × 10–1 + 5 × 10–2
Same method applies to binary fractional numbers. Say we have a number
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
❖ 20 ❖ Programming with C++
x = 111001000.01
in binary. It may be converted to decimal system as below.
x = 1 × 28 + 1 × 27 + 1 × 26 + 0 × 25 + 0 × 24 + 1 × 23 + 0 × 22
+ 0 × 21 + 0 × 20 + 0 × 2–1 + 1 × 2–2
= 256 + 128 + 64 + 8 + 0 + 0.25 = 456.25
For converting 0.25 from decimal system to binary, we have to successively multiply it by
2 till it is 1 or non-fractional as below.
0.25 × 2 × 2 = 1
Therefore, the number 0.25 in decimal system is equal to 0.01 in binary.
Exercise – Convert the fraction 0.1, 0.2 and 0.5 from decimal system to binary.
Solution
Conversion of 0.1—Multiply 0.1 successively by 2, till it is 1 or just more than 1.
Binary fractional number
.1 × 2 = .2 less than 1 .0
.1 × 2× 2 = .4 less than 1 .00
.1 × 2 × 2 × 2 = .8 still less than 1 .000
.1 × 2 × 2 × 2 × 2 = 1.6 now multiply fraction .6 as below .0001
.6 × 2 = 1.2 now multiply fraction .2 as below .00011
.2 × 2 × 2 × 2 = 1.2 now multiply fraction .2 by .00011001
Therefore .1 of decimal = .00011001 of binary. As shown above the fraction could still continue.
Conversion of 0.2 of decimal into binary
0.2 × 2 × 2 × 2 = 1.6 fraction part now left is .6 .001
.6 × 2 = 1.2 fraction part now left is .2 .0011
.2 × 2 × 2 × 2 = 1.6 fraction part now left is .6 .0011001
Therefore .2 of decimal = .0011001 of binary.
Similarly it can be shown that .5 of decimal = .1 of binary.
The smallest unit of computer memory is a bit, which may have values either 0 or 1. In
Copyright © 2009. New Age International Ltd. All rights reserved.
computer we often deal with groups of bits. A group of 8 bits is called a byte. The characteristics
of a memory is that if a bit has been set to one it will continue to remain in that state until it is
reset to zero. And if it is reset to 0 it would remain so unless it is set to 1. A simple example is
that of a switch. When you press the switch, it switches on a light, and it continues to remain
on untill you put it off or reset it. When a switch is put on it connects a high voltage to the light
circuit. We may call it as state 1. When it is put off the circuit voltage becomes zero. We may
call it a state 0. In electronics there are circuits which are called flip-flops. A flip-flop is just like
a switch. When it has high voltage (≈ 5 V) on its output point we say it is set and when the
voltage at its output terminal is 0 we say it is at zero or reset.
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
Introduction to C++ ❖ 21❖
The output state can be manipulated by input signal to the flip-flop. Thus we can make its
output 0 or 1 as we wish just like a switch which can be put on or put off, the difference being
that in case of flip-flop it is done by electronic circuit while in case of manual switch it is done
manually. We have qualified the switch as manual because switching can also be done
electronically. Each flip-flop is one bit of memory. A bit can have value 0 or 1. Now you
understand why binary numbers are used in computers. Binary numbers also have only two
digits, one is 0 and second is 1. Computer memory also has two states 0 or low and 1 or high.
If we have an array of such flip-flops, some set high or at 1 and some set to low or at 0 at their
outputs, we can represent a binary number. For instance, Fig.1.12 shows four bits. They have
the place values from unit for the bit on extreme right to 8 for bit on the extreme left. If all the
bits are set (have value 1) the total number stored is equal to 8 + 4 + 2 + 1 = 15 in decimal
system.
Bit number 3 2 1 0
Binary number (when set) 1 1 1 1
Place value 23 =8 22 =4 21 =2 20 =1
Number stored when all the bits are set = 1 × 8 + 1 × 4 + 1 × 2 + 1 × 1 = 15
Fig. 1.12
Below in Fig. 1.13 we show 4 flip-flops by four squares numbering from 0 to 3. In computer
terminology the counting starts from 0. Here we take right most bit (Fig.1.13) as the 0th bit at
the unit place. In programming also as you will see in the chapter on arrays that the first member
of an array is the 0th element. So it is better that you make a habit to count from 0. The next
flip-flop (shown by square at 1) is at place where place value is 2. The flip-flop next to it (3rd
from right and numbered as 2) has a place value 22 = 4 and the last has place value 23 = 8.
Now if the bit 0, 1 and 3 are set (each equal to 1) and bit 2 is 0. The number stored is 11.
It is explained below. 3 2 1 0
Output state 1 0 1 1
Number held 1 × 23 + 0 × 22 + 1 × 21 + 1 × 20 = 8 + 0 + 2 + 1 = 11
Fig. 1.13
Copyright © 2009. New Age International Ltd. All rights reserved.
Starting from right of Fig.1.13, the 0th bit is high representing 1, the next one is also high but
it is one digit to the left of 0th bit. So here 0 is zero, but 1 is equal to 1 × 21 = 2. Similarly at the
third place it is zero so it is equal to 0 × 22 = 0. At the fourth place the bit is high so it represents
1 × 23 = 8. So the total of all these is 11. Similarly, if all of them were high they would represent
a number 15, and when all of them are low they represent 0. So a set of 4 memory bits can hold
any number from 0 to 15 or from 0 to (24 – 1). Similarly, if we have 8 bits of memory arranged
as shown in Fig.1.14, we can store any number from 0 to ( 28 – 1 ) = 0 to 255.
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
❖ 22 ❖ Programming with C++
One byte
Bit No. 7 6 5 4 3 2 1 0
1 1 1 1 1 1 1 1
Fig. 1.14: One byte can store any positive number from 0 to 255
So one byte can hold any positive number (unsigned number) from 0 to 255. Similarly if
the number is unsigned (positive) 2, 3 and 4 bytes can hold numbers as given below.
2 bytes (16 bits) can hold an unsigned number from 0 to (216 – 1) = 0 to 65535
3 bytes (24 bits) can hold any unsigned number from 0 to (224 – 1) = 0 to 16,777,215
4 bytes (32 bits) can hold any unsigned number from 0 to (232 – 1) = 0 to 4,294,967,295
Often we have to deal with positive as well as negative numbers (signed numbers). In such
cases, the left most bit of the memory block allocated to the number is reserved for sign. If this
bit is 0 the number is positive and if the bit is set to 1 the number is negative. So for storage of
signed number we now have one bit less. Therefore, for signed numbers the maximum value
of number that can be stored on a n-bit memory becomes (2n-1 – 1). Thus the ranges of signed
numbers that can be stored on 1, 2, 3 and 4 bytes are as follows.
Range of signed number that 1 byte can hold
= – 28–1 to (28–1 – 1) , i.e. – 128 to 127
Range of signed number that 2 byte can hold
= – 216–1 to (216–1 – 1) = – 32768 to 32767
Range of signed number that 3 byte can hold
= – 224–1 to (224–1 – 1) = – 8388608 to 8388607
Range of signed number that 4 byte can hold
= – 232–1 to (232–1 – 1) = – 2147483648 to 2147483647
Copyright © 2009. New Age International Ltd. All rights reserved.
In general, characters such a ‘A’, ‘b’, etc., are stored in one byte, short integers (whole
numbers) are stored in two bytes, integers are stored in 4 bytes. The floating decimal numbers
are stored in 4 bytes for single precision (float) and in 8 bytes for decimal point numbers with
double precision.
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
Introduction to C++ ❖ 23❖
Computer performance is generally measured by how quickly it performs a task. If it takes more
time then its performance is low. The speed of CPU (frequency of its oscillator) is one factor
that contributes to the efficiency. But processor does not work alone. It works with support of
other electronic chips whose speed is equally important. Besides, the type of program that it is
handling, the language of program, etc., all affect its performance. Among the devices that support
CPU, the most important ones are the memory devices in which the processor stores the data
and extracts data from. Generally the speed of memory devices is much lower than the speed
of the processor and this low speed becomes a drag on the processor because it has to wait till
the process of storing data or process of extracting data is completed. Fig.1.15 shows the different
memory devices which are used by the processor to carry out a program. Different memory
devices have different speeds and hence the cost (Fig.1.16). The performance of a memory device
is measured by the access time. This is the time taken by memory for extraction of a data. The
fastest memory which is closest to the processor is L1 cache memory which in some processors
is on the processor chip itself. It has the minimum access time of the order of 1 to 2 nano-seconds
(1 nano-second =10–9 sec.). Then comes the L2 cache memory that may be on a separate chip.
Its access time is nearly twice that of L1. Then comes the RAM the main memory which is
extensively used by processor. The cache memories are also part of RAM. Speeds and prices of
memory devices vary over a good range. The slowest are the bulk storage memories such as hard
disc, magnetic tape etc., and their access time varies from seconds to minutes. Fig.1.16 gives an
idea of the access times of different memory devices.
Copyright © 2009. New Age International Ltd. All rights reserved.
Floppy Disc
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
❖ 24 ❖ Programming with C++
L1 cache
1 – 10 ns
L2 cache
cost 20 – 30 ns
Hard disc
25 – 120 ns
CD ROM
Tape
100 000 ns
in mins
Fig. 1.16
It is logical to infer that a computer with large L1 and L2 would perform better. Besides L1
and L2, the computer performance also depends on RAM and the quality of program. A
program is more efficient if it generates less machine code. In this respect the programs written
in machine language are the fastest because there is nothing between the program and the
processor. The programs written in assembly language come next , i.e. take more time as these
have to go through the assembler. The programs written in a high level language have to be
converted into machine language by a compiler or interpreter. Naturally these programs take
more time than those written in assembly language. Programs in C++, when compared with
other high level languages on efficiency scale, come midway, nearly as good as java.
EXERCISES
1. What do you understand by following terms?
(i) Machine language
(ii) Assembly language
(iii) High level languages
2. What are the major additions from C to C++?
3. What is a compiler? Why is it needed to run a program written in C++?
Copyright © 2009. New Age International Ltd. All rights reserved.
4. What is a class?
5. What are the different types of computer memories?
6. Explain the following number systems.
(i) Decimal (ii) Binary
(iii) Octal (iv) Hexadecimal
7. Convert decimal number 46535 into binary, octal and hexadecimal numbers.
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
Introduction to C++ ❖ 25❖
8. Convert the following hexadecimal numbers into binary numbers.
(i) d368c
(ii) f 0 abc7
(iii) 368c
9. Convert the following binary numbers into hexadecimal numbers.
(i) 1110101011001
(ii) 1010110001101.10101
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.
❖ 26 ❖ Programming with C++
22. Distinguish between the following styles of programming.
(i) Procedural programming.
(ii) Modular programming.
(iii) Object oriented programming.
23. Distinguish between the following terms.
(i) Class and object
(ii) Base class and derived class
(iii) Data abstraction.
24. What data should be printed on a driving licence of a person? (Hint: use data abstraction)
25. What data should be printed on the identity cards of students of a technical institute?
26. The city police decides that all domestic servants should carry an identity card. What data
do you think should be printed on it?
27. The employees of a bank are required to wear an identity card during working hours in the bank.
What data do you think should be printed on it?
❍❍❍
Copyright © 2009. New Age International Ltd. All rights reserved.
Juneja, B.L.. Programming with C++, New Age International Ltd, 2009. ProQuest Ebook Central, http://ebookcentral.proquest.com/lib/moiuniv-ebooks/detail.action?docID=437715.
Created from moiuniv-ebooks on 2023-03-13 17:39:48.