UG BCA Computer Applications 101 23 Programming in C++ 3653
UG BCA Computer Applications 101 23 Programming in C++ 3653
sruIncrease
oC eht fothe
ezifont
s tnosize
f ehof
t esthe
aerCourse
cnI .1 Name.
.egaP revoC e2.ht nuse
i rethe
daefollowing
h a sa gniwasolaloheader
f eht esin
u the
.2 Cover Page.
YTISREVINUALAGAPPA
APPAGALAUNIVERSITY
B.C.A. elcyC drihT eht ni )46.3:APGC( CA[Accredited
AN yb edarG
]CGU-DRHM yb ytisrevinU I–yrogeand
300 036 – IDUKIARA
KARAIKUDI
K
with
’+A’’A+’
taC Graded
htiw
sa dedaras
– 630 003
Grade
detidby
ercNAAC
cA[ (CGPA:3.64) in the Third Cycle
G Category–I
dna University by MHRD-UGC]
PROGRAMMING IN C++
II - Semester
PROGRAMMING IN C++
B.C.A.
101 23
itnem sYou
a egaare
p reinstructed
voc eht etatodpupdate
u ot dethe
tcurcover
tsni erpage
a uoYas mentioned below:
.emaN e1.sruIncrease
oC eht fothe
ezifont
s tnosize
f ehof
t esthe
aerCourse
cnI .1 Name.
aP revoC e2.ht nuse
i rethe
daefollowing
h a sa gniwasolaloheader
f eht esin
u the
.2 Cover Page.
ISREVINUALAGAPPA
APPAGALAUNIVERSITY
rihT eht ni )46.3:APGC( CA[Accredited
AN yb edarGwith
’+A’’A+’
htiwGrade
detidby
ercNAAC
cA[ (CGPA:3.64) in the Third Cycle
]CGU-DRHM yb ytisrevinU I–yrogeand
taC Graded
sa dedarasG Category–I
dna University by MHRD-UGC]
300 036 – IDUKIARA
KARAIKUDI
TACUDE ECNATSIDDIRECTORATE
K
FO ETAROTCEOF
– 630 003
RIDDISTANCE EDUCATION
PROGRAMMING IN C++
B.C.A.
II - Semester
ALAGAPPA UNIVERSITY
[Accredited with ‘A+’ Grade by NAAC (CGPA:3.64) in the Third Cycle
and Graded as Category–I University by MHRD-UGC]
(A State University Established by the Government of Tamil Nadu)
KARAIKUDI – 630 003
B.C.A.
II - Semester
101 23
PROGRAMMING IN C++
Author
Rohit Khurana, ITL Education Solutions Ltd.
All rights reserved. No part of this publication which is material protected by this copyright notice
may be reproduced or transmitted or utilized or stored in any form or by any means now known or
hereinafter invented, electronic, digital or mechanical, including photocopying, scanning, recording
or by any information storage or retrieval system, without prior written permission from the Alagappa
University, Karaikudi, Tamil Nadu.
Information contained in this book has been published by VIKAS® Publishing House Pvt. Ltd. and has
been obtained by its Authors from sources believed to be reliable and are correct to the best of their
knowledge. However, the Alagappa University, Publisher and its Authors shall in no event be liable for
any errors, omissions or damages arising out of use of this information and specifically disclaim any
implied warranties or merchantability or fitness for any particular use.
Work Order No. AU/DDE/DE1-291/Preparation and Printing of Course Materials/2018 Dated 19.11.2018 Copies - 500
SYLLABI-BOOK MAPPING TABLE
Programming in C++
Syllabi Mapping in Book
Self-Instructional
Material
Object-Oriented
BLOCK I Programming
PRINCIPLES OF OBJECT-ORIENTED
PROGRAMMING
NOTES
UNIT 1 OBJECT-ORIENTED
PROGRAMMING
Structure
1.0 Introduction
1.1 Objectives
1.2 Software Crisis and Evolution
1.2.1 Software Characteristics
1.2.2 Software Crisis
1.3 Principles of Objected Oriented Programming (OOP)
1.3.1 Approach of OOP Principles
1.4 Basic Concepts of OOP
1.4.1 Objects
1.4.2 Classes
1.4.3 Abstraction
1.4.4 Encapsulation
1.4.5 Inheritance
1.4.6 Polymorphism and Overloading
1.4.7 Message Passing
1.4.8 Dynamic Binding
1.5 Benefits of OOP
1.6 OOP Languages
1.7 Applications of OOP
1.7.1 Application of C++
1.8 Answers to Check Your Progress Questions
1.9 Summary
1.10 Key Words
1.11 Self Assessment Questions and Exercises
1.12 Further Readings
1.0 INTRODUCTION
In this unit, you will learn about object oriented programming. The goal of
programmers is to develop software which is correct, reliable and maintainable,
and which satisfies the requirements of users. Software development is not a static
process. It needs to be modified or redesigned according to changes in users’
requirements, business rules and strategies. In addition, the complexity of the
software also increases. With the development of computers, different approaches
to programming have been developed to cope with the dynamic nature and
complexity of software. These approaches are known as programming paradigms. Self-Instructional
Material 1
Object-Oriented A programming paradigm (programming methodology) describes the structure of
Programming
a program. C++ is a powerful programming language which supports the principles
of object oriented programming, such as data abstraction, encapsulation, inheritance
and polymorphism. C++ is particularly suitable for use in the development of
NOTES reusable software building blocks in the form of class libraries. This high level
language permits selective use of the advantages of object oriented programming.
C++ supports the creation of class libraries. Class libraries are reusable software
building blocks. The concept of OOP discusses the basics and functions of objects,
classes, encapsulation, inheritance, polymorphism and overloading.
1.1 OBJECTIVES
Self-Instructional
4 Material
launch. The crash occurred because there was a software bug in the rocket Object-Oriented
Programming
guidance system.
x In 1996, one of the largest bank of US credited accounts of nearly 800
customers with approximately $924 lacs. Later, it was detected that the
NOTES
problem occurred due to programming bug in banking software.
x During the Gulf War in 1991, the United States of America used Patriot
missiles as a defense against Iraqi Scud missiles. However, the Patriot failed
to hit the Scud many times. As a result 28 US soldiers were killed in Dhahran,
Saudi Arabia. An inquiry into the incident concluded that a small bug had
resulted in the miscalculation of missile path.
Initially, when computers were invented, the binary language was used to write
programs. However, as programs grew in size, it became difficult to write programs
using binary language. Then the assembly language, though also not user friendly,
was developed to write large programs. With changes in users’ requirements, the
size and the complexity of the programs continued to grow which led to the
development of high level languages, such as Beginner’s All-Purpose Symbolic
Instruction Code or BASIC and FORmula TRANslation or FORTRAN.
However, these languages provided an unstructured way of writing programs.
In the unstructured programming paradigm, all the instructions of a program
were written one after the other in a single function and, hence, these languages
were suitable for writing only small and simple programs. For large and complex
programs, it became difficult to trace and debug errors.
To overcome the limitations of unstructured programming paradigm, other
programming paradigms, namely procedural and Object Oriented Programming
or OOP paradigms were developed which help the programmers to develop the
programs in a structured way.
Object Oriented Programming Paradigm
To overcome the limitations of procedural programming, the OOP paradigm has
been developed that has revolutionized the process of software development. It
not only includes the best features of the structured programming, but has also
introduced some new and advanced features that the procedural programming
lacked. The most important feature is that unlike the procedural approach in which
the program is divided into a number of functions, OOP divides the program into
a number of objects. An object is a unit of structural and behavioural modularity
that contains a set of properties (or data) as well as the associated functions. In
addition, programmers can create relationships between one object and another.
Self-Instructional
Material 5
Object-Oriented The functions of the object (also known as member functions) provide the
Programming
only way to access the object’s data. If a user wants to read or manipulate any
data item, then it is possible only if the member function to do the same is available
in the object. Therefore, the data is hidden from the outside world, and hence safe
NOTES from accidental modifications. The basic idea behind OOP is shown in Figure 1.2.
As stated earlier, OOP has introduced some new and advanced features that the
procedural programming lacked. The most important feature is that unlike
procedural approach in which the program is divided into a number of functions,
OOP divides the program into a number of objects. Some of the other features of
OOP are also described here.
x OOP emphasises on data rather than the functions or the procedures.
x OOP models the real world very well by binding the data and associated
functions together under a single unit and thus, prevents the free movement
of data from one function to another.
x The data of one object can be accessed by the associated functions of
that object only. Other functions are not allowed to access that data. In
other words, data is hidden from the outside world. However, the
functions of one object can access the functions of other object.
x The objects of the entire system can interact with each other by sending
messages to each other.
x The programs written in OOP are easy to maintain and extend as new
objects can be easily added to the existing system whenever required
without modifying the other objects.
Self-Instructional
6 Material
x OOP follows the bottom-up approach for designing the programs. That Object-Oriented
Programming
is, first objects are designed and then these objects are combined to
form the entire program.
1.3.1 Approach of OOP Principles NOTES
C++ is a powerful programming language which supports the principles of object
oriented programming, such as data abstraction, encapsulation, inheritance and
polymorphism. C++ is particularly suitable for use in the development of reusable
software building blocks in the form of class libraries. This high level language
permits selective use of the advantages of object oriented programming. C++
supports the creation of class libraries. Class libraries are reusable software building
blocks.
C++ avoids runtime errors by strict type checking. This greatly improves
the stability of the programs. C++ supports object oriented programming which is
based on the following principles:
x Data Abstraction: The data abstraction refers to the act of representing
the essential features without including the background details or explanations.
This concept uses the classes and objects. Classes use the concept of
abstraction and are defined as a list of abstract attributes, such as size,
weight and cast functions to operate on these attributes. The attributes are
sometimes called data members because they hold information. The reasons
of abstraction are defined as follows:
o Flexibility in Approach: By hiding data or abstracting details that are
not needed for presentation, the programmer achieves greater flexibility
in approach.
o Enhanced Security: Abstraction gives access to data or details that
are needed by users and hide the implementation details, giving enhanced
security to application.
o Easier Replacement: With the concept of abstraction in object oriented
programming language, it is possible to replace code without
recompilation. This makes the process easier and saves time for users.
o Modular Approach: In object oriented programming language C++,
the abstraction concept helps users to divide the project application into
modules and test each of them separately. Then all modules are integrated
and ultimately tested together. This approach makes the application
development easier.
There are various ways of achieving abstraction in object oriented programming
language C++. One approach is to take modular based code that is broken apart into
smaller segments known as functions. This functional or modular approach helps
the code to be reused again and again when needed. For example, a programmer
might write a function for computing an average and another programmer might
write a function for computing salary. These functions can be reused when needed
Self-Instructional
Material 7
Object-Oriented by anyone. The modular based approach helps to centralize all data of a similar
Programming
type, under the control of a type module. Defining module types allow the module to
be an abstract data type. Data abstraction lets you to create new data types which
are not available in the programming languages. It is, in fact, is a process of
NOTES representing the essential features without including implementation details. It is the
process of defining function and is used several times as needed with the required
properties. With reference to object oriented programming, class student is
designed to represent the data elementary. These data elements can be student
ID, name, marks, grade, etc., and in the same way, for class car, car
model name, colour, price, etc., are considered as data elements. The
classes designed to object oriented language is also known as user defined data
types. In programming language, standard or built in data type has two attributes.
These attributes refer to a set of values and a collection of allowable operations for
the defined values. The instances are commonly known as variables. Often, the
high level languages are not primitive to correlate with the real world data, for
example Password, StudentList and BusSchedule, etc., data types
are not supported by C++. Data abstraction can be implemented by two methods.
In first method, abstraction can be implemented if data representation is chosen for
the abstract data. It is noted that data types already exist in the chosen programming
language. The second method implements each allowable operation in terms of
program instruction. The four terms used in data abstraction are as follows:
o Object Instance: Each single entity in an object model is called an
object instance. For example, the Figure 1.3 represents a single object
instance, i.e., Car.
Self-Instructional
8 Material
Object-Oriented
Programming
NOTES
Figure 1.4 shows two references. The object instance representing Car
stores two OIDs. One OID represents Honda City. The other OID
represents Maruti Esteem. The OIDs appear as arrows. These
references represent the parents of Car. The objects representing Honda
City and Maruti Esteem store an OID that represents Car.
o Object Identity: Object identity in object models means that every
object instance has a unique, unchanging identity. Object identification
is often referred to as an OID. OIDs are used to refer the object instances.
They are independent of data contained in the object. The internal data
values are not used to generate identification and also are generated by
the object system. Users or programs have no control over identification
for object identity. They last the lifetime of the object. The OID never
changes even when the data contents may change.
o Class and Objects: Object instances are grouped together into a class.
The class defines the structure and the attributes or fields for each of the
objects. In this example, there is a Car class that has possible attributes
of ‘car model’ and ‘price’. It also has relationships of parents and children.
x Encapsulation: Objects encapsulate states and functions. In C++, objects
are described by means of class definitions. A class definition collectively
defines data and the functions that operate on this data. Software produced
according to this principle is more robust, easier to maintain and easier to
extend since there are fewer dependencies between the modules and the
details of the implementation are encapsulated in classes.
Self-Instructional
Material 9
Object-Oriented x Inheritance: Classes can inherit attributes from other classes. Inheritance
Programming
permits better structuring of the software and helps in reducing the amount
of code, as common sections of code can be reused.
x Polymorphism: Objects of different types can share a common function
NOTES
interface, enabling a developer to use the various objects without needing
to know their type. The use of polymorphism produces software that is
more general purpose, more flexible and more reusable.
The match between programming objects and real world objects produce a good
result of combining data and functions and the resulting objects offer a revolution
in program design.
1.4.2 Classes
A class is defined as a user defined data type that contains the entire set of similar
data and the functions that the objects possess. In other words, a class in OOP
represents a group of similar objects. As stated earlier, in the real world millions of
Self-Instructional
Material 11
Object-Oriented objects exist and each of them has its own identity. However, each of them can be
Programming
categorized under different groups depending on the common properties they
possess and the functions they perform. Cars, scooters, motorbikes, buses, etc.,
for example can be grouped under the category vehicles. Similarly, dogs, cats,
NOTES horses, etc., can be grouped under the category animals. Thus, vehicles and animals
can be considered as classes.
A class serves as a blueprint or template for its objects, that is, once a
class has been defined, any number of objects belonging to that class can be
created. The objects of a class are also known as the instances or the variables
of that class and the process of creating objects from a class is known as
instantiation. Note that a class does not represent an object, rather it represents
the data and functions that an object will have.
A class , for example, consists of data, such as ,
, and that specify the attributes or features
of the objects of the Product class. In addition, it consists of functions, such as
and that specify the actions that
can be performed on data (refer Figure 1.5).
Note that the data belonging to a particular class is known as its data members
and the functions of the class are known as the member functions and both
collectively are known as the members of the class.
1.4.3 Abstraction
Abstraction is a mechanism to hide irrelevant details and represent only the essential
features so that one can focus on important things at a time. It allows managing
Self-Instructional
12 Material
complex systems by concentrating on the essential features only. While driving a Object-Oriented
Programming
car, for example a driver only knows the essential features to drive a car, such as
how to use clutch, brake, accelerator, gears, steering, etc., and is least bothers
about the internal details of the car, such as motor, engine, wiring, etc.
NOTES
Abstraction can be of two types, namely (i) Data abstraction and (ii) Control
abstraction. Data abstraction (also known as data hiding) means hiding the details
about the data and control abstraction means hiding the implementation details.
In object oriented approach, one can abstract both data and functions. However,
generally, the classes in OOP are defined in such a way that the data is hidden
from the outside world and the functions form the public interface. Thus, the
functions of the class can be directly accessed by other functions outside the class,
and the hidden data can be accessed indirectly with the help of these functions.
Note that the values of the hidden data members cannot be passed to the
outside world unless the functions are written to pass that information outside the
class. Since the internal details of the class are hidden from the outside world, data
abstraction ensures security of data by preventing it from accidental changes or
manipulations by other parts of the program.
Note: Classes in the object oriented programming are also known as Abstract Data Types
(ADT) as they use the concept of abstraction.
1.4.4 Encapsulation
Encapsulation is the technique of binding or keeping the data and functions (that
operate on them) together in a single unit called a class. Encapsulation is the way
to implement data abstraction. A well encapsulated object acts as a ‘black box’
for other parts of the program, that is, it provides services to the external functions
or other objects that interact with it. However, these external functions or the
objects do not need to know its internal details. For example, in Figure 1.5 the
data , , and qty_in_hand and the functions
and are encapsulated in a class
.
1.4.5 Inheritance
Inheritance can be defined as the process whereby an object of a class acquires
characteristics from the object of another class. As stated earlier, all the objects of
a similar kind are grouped together to form a class. However, sometimes a situation
arises when different objects cannot be combined together under a single group as
they share only some common characteristics. In this situation, the classes are
defined in such a way that the common features are combined to form a generalized
class and the specific features are combined to form a specialized class. The
specialized class is defined in such a way that in addition to the individual
Self-Instructional
Material 13
Object-Oriented characteristics and functions, it also inherits all the properties and the functions of
Programming
its generalized class.
In the real world, for example, all the vehicles cannot be automobiles—
NOTES some of them are pulled-vehicles also. Thus, car and scooter both are vehicles
that come under the category of automobiles. Similarly, rickshaw and bicycle
are vehicles that come under the category of pulled-vehicles. Thus, automobiles
and pulled-vehicles inherit the common properties of the vehicle class and also
have some other properties that are not common and differentiate them. Thus,
the vehicles class is the generalization of automobiles and pulled-vehicles class
and automobiles and pulled-vehicles classes are the specialized versions of the
vehicles class. Note that while inheriting the vehicle class, the automobiles and
pulled-vehicles do not modify the properties of the vehicle class, however, they
can add new properties that are exclusive for them (refer Figure 1.6).
In the same way, OOP allows one class to inherit the properties of another class
or classes. The class, which is inherited by the other classes, is known as superclass
or base class or parent class and the class, which inherits the properties of the
base class, is called sub class or derived class or child class. The sub class can
further be inherited to form other derived classes. In Figure 1.6, for example, car
and scooter are the derived classes of automobiles, and rickshaw and bicycle are
the derived classes of pulled-vehicles.
Inheritance can be of two types: (i) Single inheritance and (ii) Multiple
inheritance. If a class acquires properties from a single class, it is termed as single
inheritance and if it acquires characteristics from two or more classes, it is known
as multiple inheritance. The main advantage of inheritance is reusability. The
existing classes can be simply re-used in new software instead of writing a new
code. Moreover, new features can be added without altering or modifying the
features of the existing class.
Self-Instructional
14 Material
Reusability and Extensibility Object-Oriented
Programming
Inheritance allows code reusability, that is, it facilitates classes to reuse the existing
code. It is useful when several classes having similar features are to be created. In
such a case, one class is created having common features of all the classes which NOTES
is used as the base class. Whenever a new class is to be generated, it inherits this
base class and only the unique features of the new class are added, thereby avoiding
repetition of code. The new class acquires the members of the old class that are
already tested and debugged.
The base classes having common features can also be stored in a reservoir
so that they can be used by any programmer. These classes stored in the reservoir
form part of general-purpose programming tools and new classes generated on
the basis of these classes become their specialized versions. Hence, inheritance
allows extending and reusing already existing classes, thereby, saving time as well
as increasing the reliability. A common class , for example can be
created having some basic features, which can be used by any program requiring
classes (such as, , , ,
, etc.) to be generated having similar features. These features
of inheritance play an important role in the program development.
Abstract Classes and Concrete Classes
While inheriting a base class, a derived class not only inherits the data and functions
of its base class, but can also provide a different implementation (definition) for the
functions of the base class. In such a case, the base class may or may not provide
an implementation for its function. It only provides the interface for the functions.
A class that provides only the interface of one or more functions and not
their implementations is known as an abstract class. An abstract class only specifies
what the function does, what all it requires, etc., but it does not specify how the
function works. Implementations of such functions are provided in the classes that
inherit the abstract class. Note that the instances (objects) of an abstract class
cannot be created. This is due to the fact that it does not provide the implementation
of the functions. The class that provides an implementation for all its functions is
known as a concrete class. The concrete classes can have one or more objects.
Remember that derived classes that provide implementation of all the functions
that have not been implemented in the abstract class are also considered as concrete
classes.
1.4.6 Polymorphism and Overloading
Polymorphism (a Greek word meaning having multiple forms) is the ability of
an entity, such as a function or a message to be processed in more than one
form. It can also be defined as the property of an object belonging to the same
or different class to respond to the same message or function in a different way.
Self-Instructional
Material 15
Object-Oriented If a message , for example is passed to all the vehicles then
Programming
the automobiles will respond to the message appropriately, however, the pulled
vehicles will not respond. The concept of polymorphism plays an important role
in OOP as it allows an entity to be represented in various forms.
NOTES
In C++, polymorphism can be achieved either at compile-time or at runtime.
At compile time, polymorphism is implemented using operator overloading and
function overloading. However, at runtime, it is implemented using virtual functions
.
Operator overloading is the process that enables an operator to exhibit different
behaviour, depending on the data provided, for example, when the ‘+’ operator is
used with two numbers, it adds the two numbers and produces the sum. However,
if it is used with two strings, it concatenates the two strings and produces the third
concatenated string (refer Figure 1.7).
Self-Instructional
16 Material
function is determined at runtime. This form of polymorphism is called runtime Object-Oriented
Programming
polymorphism (refer Figure 1.9).
NOTES
Self-Instructional
Material 17
Object-Oriented
Programming
NOTES
The object oriented programming paradigm came into use as it overcame certain
limitations of the structured and unstructured programming paradigms. The new
and advanced features of OOP, such as encapsulation, abstraction, inheritance
and polymorphism helped in the development of high quality software. High quality
software can be developed due to its certain advantages. Some of the benefits of
OOP are as follows:
x In OOP, writing programs with the help of objects is much similar to working
with real world objects; that is, the real world objects can be conveniently
represented in a program that reduces the complexity of the program and
also makes the program structure clear.
Self-Instructional
18 Material
x In it, each object is an independent and separate entity that makes modifying, Object-Oriented
Programming
locating and fixing problems in a program an easy task. In addition, any
change made inside the class does not affect the other parts of the program.
Thus, OOPs are easy to write and easy to maintain.
NOTES
x In it, data integrity and data security is high, as it focusses on the data and its
protection from manipulation by different parts of the program. As a result,
OOPs are less error-prone, more reliable and secure.
x Object oriented programs are easy to extend, as new features in a program
can be added easily by introducing a few new objects without modifying
the existing ones.
x It allows reusability of code, that is, the objects created in one program can
be re used in other programs. In addition, new classes can be created with
the help of existing ones using inheritance. It leads to faster software
development and high quality programs.
x These are easier to adapt and scale, that is, large system can be created by
assembling reusable subsystems.
Since 1960, when Simula-67 was developed, object oriented paradigm has touched
many major application areas of software development. Some of the application NOTES
areas where OOP has been used to develop software are listed here.
x Simulations and Modelling: Simulation is the technique of representing
the real world entities with the help of a computer program. Simula-67 and
Smalltalk are the two object oriented languages that are designed for making
simulations.
x User Interface Design: Another popular application of OOP has been in
the area of designing graphical user interfaces, such as Windows. C++ is
mainly used for developing user interfaces.
x Developing Computer Games: OOP is also used for developing
computer games, such as Diablo, Startcraft and Warcraft III. These games
offer virtual reality environments in which a number of objects interact with
each other in complex ways to give the desired result.
x Scripting: In recent years, OOP has also been used for developing
HyperText Markup Language or HTML, eXtensible HTML or XHTML
and XML documents for the Internet. Python, Ruby and Java are the
scripting languages based on object oriented principles which are used to
control one or more applications.
x Object Databases: These days OOP concepts have also been introduced
in database systems to develop a new Database Management System
(DBMS) named object databases. These databases store the data directly
in the form of objects. However, these databases are not as popular as the
traditional Relational Database Management System (RDBMS).
Some other areas of applications include office automation systems, decision
support systems, Artificial Intelligence (AI) and expert systems, Neural networks
and parallel programming and Computer Aided Design (CAD) systems.
1.7.1 Application of C++
Various applications areas of C++ are:
1. Games
2. Graphic User Interface (GUI) based applications
3. Web Browsers
4. Advance Computations and Graphics
5. Database Software
6. Operating Systems
7. Enterprise Software
Self-Instructional
Material 21
Object-Oriented 8. Medical and Engineering Applications
Programming
9. Compilers etc.
1.9 SUMMARY
Self-Instructional
22 Material
x The structured programming paradigm had certain limitations that led to the Object-Oriented
Programming
development of object oriented paradigm.
x In an object oriented programming paradigm, programmers define not only
the data but also the operations (functions) that can be performed on it,
NOTES
together under a single unit. It follows the bottom-up approach.
x OOP is based on certain important concepts that include objects, classes,
abstraction, encapsulation, inheritance and polymorphism.
x An object is a unit of structural and behavioural modularity that contains a
set of properties (or data) as well as the associated functions.
x A class is defined as a user defined data type that contains the entire set of
similar data and the functions that objects possess. The process of creating
objects from a class is known as instantiation.
x Abstraction is a mechanism to hide irrelevant details and represent only the
essential features so that one can focus on important things at a time.
Abstraction can be of two types, namely (i) Data abstraction and (ii) Control
abstraction.
x Inheritance is defined as the process whereby an object of a class acquires
characteristics from the object of the other class. Inheritance can be of two
types, namely (i) Single inheritance and (ii) Multiple inheritance.
x Inheritance allows code reusability, that is, it facilitates classes to reuse the
existing code. It is useful when several classes having similar features are to
be created. The new class acquires the members of the old class that are
already tested and debugged.
x Polymorphism is the ability of an entity, such as a function or a message to
be processed in more than one form.
x Class: User defined data type that contains the entire set of similar data
and the functions that the objects possess.
x Instantiation:The process of creating objects from a class.
x Abstraction: A mechanism to hide irrelevant details and represent only the
essential features so that one can focus on important things.
x Encapsulation: The technique of binding or keeping data and functions
that operate on them together in a single unit.
x Inheritance: The process whereby an object of a class acquires
characteristics from the object of another class.
Self-Instructional
Material 23
Object-Oriented
Programming 1.11 SELF ASSESSMENT QUESTIONS AND
EXERCISES
Self-Instructional
24 Material
Structure of a C++ Program
2.0 INTRODUCTION
In this unit, you will learn about C++ programs structure and elements. During the
late 1980s and early 1990s, OOP began to replace the more traditional structured
programming techniques. This approach led to the development of many new
languages including C++ which supports programming with objects. C++ has
Self-Instructional
Material 25
Structure of a C++ Program become one of the most popular commercial programming languages since its
development. In this unit, you will learn about structure of C++ programs which
include comments, headers, iostream header file, namespace and main()
function. A namespace permits grouping of various entities, such as classes, objects,
NOTES functions and various C++ tokens, etc., under a single name. The main() is a
startup function that starts the execution of a C++ program. All C++ statements
that need to be executed are written within main(). Programming elements of
C++ includes tokens, various data types, variables, constants and operators
provided by that language. To write a C++ program, basic data types are used.
The selection of data types can be built-in data type, floating-point data type and
user defined data type which depends on program requirement. A variable is an
identifier that refers to the data item stored at a particular memory location. This
data item can be accessed in the program simply by using the variable name.
2.1 OBJECTIVES
Note that C++ provides the flexibility of writing a program with or without a class
and its member functions definitions. A simple C++ program (without a class)
Self-Instructional
26 Material
includes comments, headers, namespace, main() and input/output statements Structure of a C++ Program
NOTES
2.2.1 Comments
Comments are a vital element of a program that is used to increase the readability
of a program and to describe its functioning. Comments are not executable
statements and hence do not increase the size of a file.
C++ supports two comment styles: single line comment and multiline comment.
Single line comments are used to define line-by-line descriptions. Double slash (
) is used to represent single line comments.
To understand the concept of single line comment, consider this statement:
// An example to demonstrate single line
comment
It can also be written as follows:
// An example to demonstrate
// single line comment
Multiline comments are used to define multiple lines descriptions and are
represented as /* … */. For example, consider this statement.
/* An example to demonstrate
multiline comment */
Note: Multiline comment cannot contain another multiline comment. However, it may contain
single line comment. This implies that /*……./*…….*/……*/ is not valid whereas /*….//
…….*/ is valid.
Generally, multiline comments are not used in C++, as they require more space on
the line. However, they are useful within the program statements where single line
comments cannot be used. For example, consider this statement:
for(int i=0; i<10; //loop runs 10 times
i++)
A compiler ignores everything written after the single line comment and,
hence, an error occurs. Therefore, in this case, multiline comments are used. For
example, consider this statement.
Self-Instructional
Material 27
Structure of a C++ Program for(int i=0; i<10; /*loop runs 10 times */
i++)
2.2.2 Headers
NOTES Generally, a program includes various programming elements, such as built-in
functions, classes, keywords, constants, operators, etc., that are already defined
in the standard C++ library. In order to use such pre-defined elements in a program,
an appropriate header must be included in the program. The standard headers
contain information, such as prototype, definition and return type of library functions,
data type of constants, etc. As a result, programmers do not need to explicitly
declare (or define) the pre-defined programming elements. Standard headers are
specified in a program through the preprocessor directive #include.
2.2.3 iostream Header File
When a compiler processes the instruction #include<iostream>, it includes
the contents of iostream in the program. This enables a programmer to use
standard input, output and error facilities that are provided only through the
standard streams defined in <iostream>. These standard streams process
data as a stream of characters, that is, data is read and displayed in a continuous
flow. The standard streams defined in <iostream> are listed here.
x Pronounced ‘see in’ and is the standard input stream that is associated
with the standard input device (keyboard) and is used to take the input
from users.
x Pronounced ‘see out’ and is the standard output stream that is
associated with the standard output device (monitor) and is used to display
the output to users.
x Pronounced ‘see err’ and is the standard error stream that is
associated with the standard error device (monitor) and is used to report
errors to the users. The cerr object does not have a buffer (temporary
storage area) and hence immediately reports errors to users.
x Pronounced ‘see log’ and is the buffered error stream that is
associated with the standard error device (computer screen) and is used to
report errors to users. Unlike cerr, clog reports errors to users only
when the buffer is full.
Note: The letter in , , and stands for ‘console’.
For many years, C++ applied C-style headers, that is, .h extension in the headers.
However, the standard C++ library introduced new style headers that include
only header name. Hence, most modern compilers do not require any extension,
though they support the older .h extension. Some of the C-style headers and
their equivalent C++ style headers are listed in Table 2.1.
Self-Instructional
28 Material
Table 2.1 C Style and C++Style Headers Structure of a C++ Program
NOTES
2.2.4 Namespace
Since its creation, C++ has gone through many changes by the C++ Standards
Committee. One of the new features added to this language is namespace. A
namespace permits grouping of various entities, such as classes, objects, functions
and various C++ tokens, etc., under a single name. Different users can create
separate namespaces and, thus, can use similar names of the entities. This avoids
compile-time error that may exist due to identical name conflicts.
The C++ Standards Committee has rearranged the entities of the standard
library under a namespace called std. The statement using namespace
std informs the compiler to include all the entities present in the namespace
std. The entities of a namespace can be accessed in different ways which are
listed here:
x By specifying the using directive:
using namespace std;
cout<<“Hello World”;
x By specifying the full member name:
std::cout<<“Hello World”;
x By specifying the using declaration:
using std::cout;
cout<<“Hello World”;
Note: All the entities of a namespace are public.
As soon as the new-style header is included, its contents are included in the std
namespace. Thus, all modern C++ compilers support these statements:
Self-Instructional
Material 29
Structure of a C++ Program #include<iostream>
using namespace std;
However, some old compilers may not support these statements. In that
NOTES case, the statements are replaced by this single statement:
#include<iostream.h>
2.2.5 main() Function
The main() is a startup function that starts the execution of a C++ program. All
C++ statements that need to be executed are written within main(). The compiler
executes all the instructions written within the opening and closing curly braces
‘{}’ that enclose the body of the main(). Once all the instructions in the
main()are executed, the control passes out of the main()terminating the
entire program and returning a value to the operating system.
By default, the main()in C++ returns an int value to the operating
system. Therefore, the main() should end with the return 0 statement. A
return value zero indicates success and a non-zero value indicates failure or error.
Following are the features of main() function:
x The main() function is the mandatory function for all C++ programs.
x All functions require a return type whereas main() function requires
either an int or void return type.
x The main() function also has a variety of input variable formats that are
placed place in the () parentheses.
x The curly braces {and} represent the opening and closing of the scope in
the main() function.
Note: Every C++ program must have one and only one main() function, and it is automatically
called by the compiler.
Operators are the symbols that represent various computations (such as addition,
subtraction, etc.) performed on various data items. These data items on which
operators act are known as operands.
Depending on the number of operands and functions performed, the C++
operators can be classified into various categories. This includes arithmetic
operators, relational operators, logical operators, the conditional operator
assignment operators, bitwise operators and other operators. These categories
are further classified into unary operators, binary operators and ternary
operators, as shown in Figure 2.3.
Self-Instructional
30 Material
Structure of a C++ Program
NOTES
This program is similar to Program 2.1. The only difference is that the value of the
variable a is displayed through the instruction cout<<a;.
2.3.3 Additional Operators in C++
In addition to the operators, such as arithmetic operators, relational operators,
logical operators, conditional operators and assignment operators that most of the
languages support, C++ provides some additional operators which are listed in
Table 2.2.
Table 2.2 Some Additional C++ Operators
Operators Description
Scope resolution operator
Pointer-to-member declarator
Pointer-to-member operator
Pointer-to-member operator
Memory allocation operator
Memory release operator
Self-Instructional
32 Material
Here, only scope resolution, and new and delete operators are discussed. Structure of a C++ Program
In this program, three variables with same name x are declared. The x declared
outside main() has global scope which is hidden by both the variables x declared
in the outer block and the inner block inside main(). The variable x inside the
inner block overrides both the variables (global variable and the variable declared
Self-Instructional
Material 33
Structure of a C++ Program in the outer block). Thus, the global version of variable x is accessed using ::x
in the inner and the outer block.
new and delete
NOTES C++ provides two dynamic allocation operators new and delete to allocate
and de-allocate memory at runtime, respectively. The new operator is a unary
operator that allocates memory and returns a pointer to the starting of the allocated
space. The syntax of allocating memory using the new operator is as follows:
where,
p_var= The name of a pointer variable
new=C++ keyword
data_type= Any valid data type of C++
To dynamically allocate memory to a variable of type intat runtime, for example,
a pointer to type int is defined first and then the memory is allocated at runtime
using the new operator as shown here.
In these statements, the new operator returns the address of the memory allocated
for an int variable from the free store and this address is stored in the pointer
iptr. The pointer declaration and allocation of the memory can also be performed
using a single statement as given here.
Moreover, the allocated memory using new operator can also be initialized. The
syntax to initialize the memory using new operator is as follows:
Like built-in data types, the memory can also be allocated dynamically to derived
and user defined data types, such as arrays, structures and classes. These examples
illustrate this concept.
x To allocate memory to a one-dimensional array, consider these statements:
Self-Instructional
34 Material
x To allocate memory to a multi-dimensional array, consider these statements: Structure of a C++ Program
NOTES
Note that all the dimensions must be specified while creating multi-dimensional
arrays with the new operator. However, the first dimension can be a variable
whose value is provided at runtime. For example, consider these statements.
The lifetime of a variable created at runtime using the new operator is not restricted
till the execution of the program. Rather, it remains in the memory until it is explicitly
deleted using the delete operator. When a dynamically allocated variable is no
longer required, it must be destroyed using the delete operator to ensure safe
and efficient use of the memory.
The syntax for using the delete operator is as follows:
For example, to delete the pointers iptr and fptr of types int and float
respectively, these statements are used.
Note: It is necessary to put square brackets ([]) after the delete operator to delete
dynamically created arrays. The square brackets indicate that it is an array and, hence,
avoids unpredictable results.
The function performed by the new and delete operator is similar to
the malloc() and free() (library functions used in C). However, new
and delete operators have several advantages over malloc()and free()
which are listed here.
x Operator new automatically returns a pointer to the appropriate data type.
There is no need to explicitly typecast the pointer as required in malloc().
x It automatically allocates enough memory to accommodate the object without
using the sizeof operator.
x An object can be initialized while allocating space using the new operator.
x Both new and delete operators can be overloaded.
Self-Instructional
Material 35
Structure of a C++ Program 2.3.4 Operators Precedence
Generally, an expression consists of more than one operator, hence, a compiler
needs to know which operator is to be evaluated first. For this, it is important to
determine the precedence and associativity of operators. The order in which
NOTES
different operators in an expression are evaluated is determined by the precedence
of operators. The operators with a higher precedence are evaluated before the
operators with a lower precedence. However, the order in which operators of the
same precedence are evaluated is determined by the associativity of the operators.
The associativity of an operator can be either from the left to the right or from the
right to the left. The operators with the left to right associativity are evaluated from
the left-hand side while the operators with the right to left associativity are evaluated
from the right-hand side.
The precedence and associativity of the C++ operators are listed in Table
2.3. Note that the precedence of operators decreases from the top to bottom.
Table 2.3 Precedence and Associativity of C++ Operators
Operator Description Associativity
scope resolution Left to right
Function call Left to right
Array subscript Left to right
Indirect member selector Left to right
Direct member selector Left to right
Post increment Left to right
Post decrement Left to right
Logical negation Right to left
Bitwise complement Right to left
Unary plus Right to left
Unary minus Right to left
Pre increment Right to left
Pre decrement Right to left
Address of Right to left
Dereference Right to left
Cast Right to left
Size in bytes Right to left
Allocate memory Right to left
Deallocate memory Right to left
Direct pointer to class member Left to right
selection
Indirect pointer to class member Left to right
Multiplication Left to right
Division Left to right
Modulus Left to right
Addition Left to right
Subtraction Left to right
Bitwise shift left Left to right
Bitwise shift right Left to right
Less than Left to right
Less than or equal to Left to right
Greater than Left to right
Greater than or equal to Left to right
Equal to Left to right
Not equal to Left to right
Bitwise AND Left to right
Self-Instructional
36 Material
Bitwise AND Left to right
Bitwise exclusive OR Left to right Structure of a C++ Program
Bitwise inclusive OR Left to right
Logical AND Left to right
Logical OR Left to right
Conditional operator Left to right
Assignment operator Right to left NOTES
2.4 TOKENS
2.4.2 Identifiers
Identifiers are the names given to uniquely identify various programming elements,
such as variables, arrays, functions, classes, structures, namespaces and so
on. While defining identifiers in C++, programmers must follow the rules listed
here.
Self-Instructional
Material 37
Structure of a C++ Program x An identifier must be unique in a program.
x An identifier must contain only upper case and lower case letters, underscore
character ( _ ) or digits 0 to 9.
NOTES x An identifier must start with a letter or an underscore.
x An identifier in an upper case is different from that in a lower case.
x An identifier must be different from a keyword. In addition, identifiers that
start with a double underscore ‘—’ or an underscore followed by an upper
case letter must be avoided, as these names are reserved by the Standard
C++ Library.
x An identifier must not contain other characters, such as ‘*’, ‘;’ and whitespace
characters (tabs, space and newline).
Some valid and invalid identifiers in C++ are given here.
Note: Unlike C, there is no limit to the length of an identifier in C++. Thus, all the characters
are significant in C++, however, in C, the first 32 characters are significant.
2.4.3 Constants
Constants, also known as literals, are the values that a program cannot alter
during its execution, for example ‘391’, ‘Byron’, ‘51.072’ and ‘p’ are all
constants. Based on the type of value (data), C++ constants are broadly classified
into three categories, namely (i) Numeric constants, (ii) Character constants
and (iii) String constants.
Numeric Constants
Numeric constants refer to the numbers consisting of a sequence of digits (with
or without decimal point) that can be either positive or negative. However, by
default, numeric constants are positive. Integer constants refer to integer-valued
numbers. Integer constants can be represented by three different number systems,
namely decimal (base 10), octal (base 8) and hexadecimal numbers (base 16).
The octal constants are preceded by a 0 (zero) and hexadecimal constants are
preceded by a 0x or 0X. Examples for integer constants are 54, -646, 0x38A,
etc. Floating-point constants refer to the real numbers, i.e., the numbers with a
decimal point. Floating-point constants are also written in the floating-point
notation in which the constant is divided into a mantissa and an exponent.
Examples for floating-point constants are 64.2, -74.32, 537E-9, etc.
Note: Use of special characters, such as comma ‘,’, semicolon ‘;’ and question mark ‘?’ are
Self-Instructional not permitted in numeric constants.
38 Material
Character Constants Structure of a C++ Program
In this example, 15 is a literal constant. The code is easy to read and maintain, if
you a symbolic constant for this value is substituted. Then, the statement is written
in the following way:
The number of students in each class can be changed and for this, you need to
define the constant studentsPerClass without having to make a change
every place you used that value. There are two ways to declare a symbolic constant
Self-Instructional
Material 39
Structure of a C++ Program in C++. An obsolete way is with a preprocessor directive #define. Defining
constants with #define, the statement will be written in the following way:
Character Set
A character set can be defined as a set of characters that either individually or in
combination, represents information. In C++, a character set includes the upper
case (A – Z) and lower case (a – z) letters, decimal digits (0 – 9), blank spaces
(tabs, new line, space, etc.) and special characters (characters that perform a
specific action based on the context in which they are used). The special characters
are listed in Table 2.5.
Self-Instructional
Material 41
Structure of a C++ Program Table 2.5 Special Characters
Special Characters
+ > / [ \
! ; “ ] {
NOTES < * % }
: ^ , ~ #
- ( = _ |
? ) ‘ &
In addition to these characters, C++ also uses a combination of characters to
represent special conditions. Character combinations, for example, , and
are used to represent newline, backspace and horizontal tab, respectively.
Note: C++ is a case sensitive language, so C++ compiler treats the upper case and the lower
case characters differently.
A data type determines the type and the operations that can be performed on the
data. C++ provides various data types and each data type is represented differently
within the computer’s memory. The various data types provided by C++ are
(i) Built-in data types, (ii) Derived data types and (iii) User defined data types,
as shown in Figure 2.4.
Self-Instructional
42 Material
both of the data types. The various modifiers are short, long, signed and Structure of a C++ Program
int
Numbers without the fractional part represent integer data. In C++, the int data
type is used to store integers, such as 4, 42, 5233, –32, –745. Thus, it cannot
store numbers, such as 4.28, –62.533. The various integer data types with their
size and range are listed in Table 2.7.
Table 2.7 Integer Data Types
Type Size (in Bytes) Range
int 2 –32,768 to 32,767
signed int 2 –32,768 to 32,767
unsigned int 2 0 to 65,535
short int 2 –32,768 to 32,767
signed short int 2 –32,768 to 32,767
unsigned short int 2 0 to 65,535
long int 4 –2,147,483,648 to 2,147,483,647
signed long int 4 –2,147,483,648 to 2,147,483,647
Unsigned long int 4 0 to 4,294,967,295
Self-Instructional
Material 43
Structure of a C++ Program Floating-Point Data Type
A floating-point data type is used to store real numbers, such as 3.28, 64.755765,
8.01, -24.53. This data type includes float and double data types. The
NOTES various floating-point data types with their size and range are listed in Table 2.8.
Table 2.8 Floating-Point Data Types
Type Size (in Bytes) Range Digits of Precision
4 1.2*10-38 to 3.4*1038 7
8 2.2 * 10-308 to 1.8*10308 15
10 3.3 * 10-4932 to 1.2*104932 19
void
The void data type is used for specifying an empty parameter list to a function
and return type for a function. When void is used to specify an empty parameter
list, it indicates that the function does not take any arguments, and when it is used
as a return type for a function, it indicates that the function does not return any
value. For void, no memory is allocated and, hence, it cannot store anything.
As a result, void cannot be used to declare simple variables, however, it can be
used to declare generic pointers.
bool and wchar_t
The bool data type can hold only Boolean values that are either true or false
where true represents 1 and false represents 0. It requires only 1-bit of
storage, however, it is stored as an integer in the memory. Thus, it is also considered
as an integral data type. The bool data type is most commonly used for expressing
the results of logical operations performed on the data. It is also used as a return
type of a function indicating the success or the failure of the function.
In addition to char data type, C++ provides another data type
wchar_t,which is used to store 16- bit wide characters. Wide characters are
used to hold large character sets associated with some non-English languages.
Note: In C++, wchar_t is a built-in data type, while in C, it is defined in standard header
file stddef.h.
where,
<tag_name>: It is name of set of all enum constants. Name of tag must
be a valid identifier. This must be followed identifier naming rule.
<const_name>: It is name of constant which we want to make with the
help enum keyword. <const_name> also must be followed identifier naming
rule. It is convention to write <const_name> in the uppercase.
<value>: It is numeric number which we want to assign the
<const_name>.
Self-Instructional
Material 45
Structure of a C++ Program For example, consider this statement.
Though the enumerations are treated as integers internally in C++, the compiler
issues a warning, if an int value is assigned to an enum type. Consider these
statements, for example:
2.6 VARIABLES
A variable is an identifier that refers to the data item stored at a particular memory
location. This data item can be accessed in the program simply by using the variable
name. The value of a variable can be changed by assigning different values to it at
various places in a program.
2.6.1 Declaration of Variables
Variables must be declared in a program before they are used. The declaration of
a variable informs the compiler, the specific data type to which a variable is
associated and allocates sufficient memory for it. The syntax for declaring a variable
is as follows:
Self-Instructional
46 Material
Structure of a C++ Program
For example, a variable a of type int can be declared using this statement.
At the time of the variable declaration, more than one variable of the same data NOTES
type can be declared in a single statement, for example consider this statement.
Note that in C++, it is not necessary to declare the variables in the beginning of a
program as required in C. It can be declared at the place where it is used first.
2.6.2 Initialization of Variables
Declaration of variables allocates sufficient memory for variables. However, it does
not store any data in the variables. To store data in variables, the variables need to
be initialized at the time of declaration, for example consider this statement.
In this statement, a variable i of the integer type is declared and initialized with a
value of 10.
Note: If a variable is used prior to its initialization, undesirable results or garbage values are
produced.
Variables can either be initialized at the compile-time or at the runtime.
Initialization at the compile time using a constant is known as static initialization.
However, variables can also be initialized at the runtime using expressions.
Initialization of variables at the runtime is known as dynamic initialization.
To understand the concept of the static initialization and the dynamic
initialization, consider this example.
Program 2.5
A program to demonstrate the static and dynamic initialization.
Self-Instructional
Material 47
Structure of a C++ Program const Qualifier
When the qualifier const precedes a data type in the declaration of a variable,
it implies that the value of the variable cannot be changed throughout the program.
NOTES Consider this statement, for example:
The qualifier const with variable pie_val ensures that the program cannot
alter its value inadvertently. If any attempt to alter the value of pie_val is made
within a program, a compile-time error is generated. Moreover, if any data type is
not specified with the const qualifier, by default it is int. Consider these
statements, for example:
where,
data_type = Any valid C++ data type
& = Reference operator
refname = The name of the reference variable being declared
varname = The name of the variable whose reference is being declared
Program 2.6
A program to demonstrate the use of reference variable.
Self-Instructional
48 Material
The output of the program is: Structure of a C++ Program
NOTES
2.7 EXPRESSIONS
Data Types
char short int smallest
int
unsigned
NOTES
long int
unsigned long int
float
double
long double largest
Note: If one operand is long and the other is unsigned int, and if the value of the
unsigned int cannot be represented by a long, both operands are converted to
unsigned long.
The compiler performs type conversion of data items when an expression
consists of different types of data items. This process is known as implicit or
automatic type conversion. The rules followed by the compiler for implicit type
conversion is summarized in Table 2.10.
Table 2.10 Automatic or Implicit Type Conversion Rule Table
Operand1 Operand2 Result
char int int
int long long
int float float
int double double
int unsigned unsigned
long double double
double float double
Self-Instructional
Material 51
Structure of a C++ Program
NOTES
The variables a and f are type converted to long and double data type,
respectively. The process of type conversion leads to ‘data promotion’ or ‘demotion’
while assigning the computed result, if necessary. Figure 2.6 illustrates the automatic
type conversion for the following set of statements:
Typecasting
Typecasting refers to the type conversion that is performed explicitly using type
cast operator. In C++, typecasting can be performed by using two different forms
which are given here.
where,
data_type = Data type (also known as cast operator) to which the
expression is to be converted.
Note: The cast operator is considered as a unary operator and thus has the same precedence
as other unary operators.
To understand typecasting, consider this example.
In such cases, conversion can be done using the second form of typecasting (which
is basically C style typecasting) as shown here.
NOTES
2.7.2 Type Compatibility
Type compatibility checks whether or not two types can be treated as compatible
in a particular operation. The type coercion is used to converting one type to
another (either implicitly or explicitly) in order to obtain compatibility. For example,
a = b implies that a and b must be either be of compatible types or coercible
into compatible types. C++ uses name equivalence for classes and structural
equivalence for struct or typedef. The two types of type compatibility
known as structure type compatibility and name type compatibility are discussed
below:
Structure Type Compatibility
Two variables have compatible types only if their types have identical structures.
The requirements for compatibility between two structure, union or enumerated
types declared in separate source files are as follows:
x If one is declared with a tag, the other must also be declared with the same
tag.
x If both are completed types, their members must correspond exactly in
number, be declared with compatible types, and have matching names.
For enumerations, corresponding members must also have the same values. For
structures and unions, the following requirements must be met for type compatibility:
x Corresponding members must be declared in the same order (applies to
structures only).
x Corresponding bit fields must have the same widths.
Compatible structures and unions known as the two prime types of compatible
types are discussed below:
x Compatible Structures: Each structure definition creates a new structure
type that is neither the same as nor compatible with any other structure type
in the same source file. However, a type specifier that is a reference to a
previously defined structure type is the same type. The structure tag associates
the reference with the definition, and effectively acts as the type name. To
illustrate this, only the types of structures j and k are the same.
Self-Instructional
Material 53
Structure of a C++ Program x Compatible Unions: In C++, a union is a limited form of the class type. It
can contain access specifiers (public, protected, private),
member data and member functions including constructors and destructors.
It cannot contain virtual member functions or static data members. Default
NOTES access of members in a union is public. A union cannot be used as a base
class and cannot be derived from a base class. C++ places additional
limitations on the allowable data types for a union member. In C++, a union
member cannot be a class object that has a constructor, destructor, or
overloaded copy assignment operator, nor can it be of reference type. A
union member cannot be declared with the keyword static.
Compatibility between an enumerated type and the integer type that represents it
is controlled by compiler options and related programs. C++ treats enumerated
types as distinct from each other and from integer types. You must explicitly cast
an integer in order to use it as an enumeration value. Screen below represents the
message of type compatibility:
In this declaration, a new name integer is given to the data type int. This
new name now can be used to declare integer variables as shown here.
Self-Instructional
54 Material
Structure of a C++ Program
2.8 ANSWERS TO CHECK YOUR PROGRESS
QUESTIONS
2.9 SUMMARY
Self-Instructional
Material 57
Structure of a C++ Program 7. What are the various punctuators defined in C++?
8. What is an expression?
Long Answer Questions
NOTES
1. Explain the standard streams defined in the iostream header.
2. Describe why are cin,cout, cerr and clog called standard streams?
3. Explain the structure of a C++ program with the help of examples.
4. What do you understand by operators precedence? Explain.
5. Describe the significance of const qualifier.
6. What are expressions? Explain.
Self-Instructional
58 Material
Control Structures
AND FUNCTION
NOTES
Structure
3.0 Introduction
3.1 Objectives
3.2 Control Structures/Statements
3.2.1 Conditional Statements
3.2.2 Iteration Statements or Loops
3.2.3 Jump Statements
3.3 Functions in C++
3.3.1 Function Prototyping
3.3.2 Function Definition
3.4 Inline Functions
3.5 Function Overloading
3.6 Answers to Check Your Progress Questions
3.7 Summary
3.8 Key Words
3.9 Self Assessment Questions and Exercises
3.10 Further Readings
3.0 INTRODUCTION
In this unit you will learn about the control structures. To make a program more
flexible and efficient, the flow of execution can be altered using various control
statements. The control statement includes conditional statements (using if and
switch statements), iteration statements or loops (using for, while and
do-while loops), and jump statements (using break, continue and goto
statements). The statements that cause a set of statements to be executed repeatedly
either for a specific number of times or until some condition is satisfied are known
as iteration statements. Thus, as long as the condition evaluates to True, the set of
statement is executed. The break statement is extensively used in loops and
switch statements. You will also learn about functions and operator overloading.
Most of the practical and useful programs extend to thousands of lines of code
that make their maintenance and readability a complex task. To make these
programs easy-to-manage and easy-to-read efficiently, functions are used. Functions
are the building blocks of the structured programming approach. They are self-
contained and well defined named groups of statements that aim at accomplishing
a specific task or action in the program.
Self-Instructional
Material 59
Control Structures
and Function 3.1 OBJECTIVES
To make a program more flexible, control statements are used to alter the flow of
control of the program.
In C++, the control statements are broadly classified into three categories,
namely (i) Conditional statements, (ii) Iteration statements and (iii) Jump
statements. All these control statements are commonly used with the logical tests
or test conditions to alter the flow of control conditionally or unconditionally. To
alter the flow conditionally, a particular condition is evaluated to control the flow
of execution. On the other hand, to alter the flow unconditionally, no such condition
is evaluated.
3.2.1 Conditional Statements
Conditional statements, also known as selection statements, are used to make
decisions based on a given condition. If the condition evaluates to True, a set of
statements is executed, otherwise another set of statements is executed.
if Statement
The if statement selects and executes the statement(s) based on a given condition.
If the condition evaluates to True, then a given set of statement(s) is executed.
However, if the condition evaluates to , then the given set of statements is
skipped and the program control passes to the statement following the if statement.
The syntax of the if statement is as follows:
Self-Instructional
60 Material
if-else Statement Control Structures
and Function
The if-else statement causes one of the two possible statement(s) to execute
depending upon the outcome of condition.
The syntax of the if-else statements is as follows: NOTES
Here, the if-else statement comprises two parts, namely if and else. If
the condition is True, the if part is executed. However, if the condition is
False, the else part is executed.
Program 3.1
A code segment to determine greater of two numbers.
Self-Instructional
Material 61
Control Structures
and Function
NOTES (ii) The if-else statement is nested within the else part.
The syntax is as follows:
(iii) The if-else statement is nested within both the if and the else
parts.
The syntax is as follows:
Self-Instructional
62 Material
Program 3.2: Control Structures
and Function
A code segment to determine the largest of three numbers.
NOTES
if-else-if Ladder
The if-else-if ladder, also known as the if-else-if staircase, has
an if-else statement within the outermost else statement. The inner else
statement can further have other if-else statements.
The syntax of the if-else-if ladders is as follows:
Self-Instructional
Material 63
Control Structures Program 3.3
and Function
A program to determine whether a character is in the lower case or upper case.
NOTES
Self-Instructional
64 Material
Control Structures
and Function
NOTES
The C++ keywords case and default provide the list of alternatives. Note
that it is not necessary for every case label to specify a unique set of statements.
The same set of statements can be shared by multiple case labels.
The keyword default specifies the set of statements to be executed in
case no match is found. Note that there can be multiple case labels but there can
be only one default label.
The break statements in the switch block are optional. However, it is
used in the switch block to prevent a fall through. Fall through is a situation
that causes the execution of the remaining cases even after a match has been
found. In order to prevent this, break statements are used at the end of statements
specified by each case and default. This causes the control to immediately
break out of the switch block and execute the next statement.
Program 3.4
A code segment to demonstrate the use of switch statement.
Self-Instructional
66 Material
The output of this program is: Control Structures
and Function
This statement initializes two variables, namely i and j and updates them. Note
that for loop can have only one condition.
while Loop
The while loop is used to perform looping operations in situations, where the
number of iterations is not known in advance; that is, unlike the for loop, the
while loop is non-deterministic in nature.
The syntax of the while loop is as follows:
Self-Instructional
Material 67
Control Structures
and Function
NOTES
do-while Loop
As discussed earlier, in a while loop, the condition is evaluated at the beginning of
the loop and if the condition evaluates to False, the body of the loop is not
executed even once. However, if the body of the loop is to be executed at least
once, no matter whether the initial state of the condition is True or False, the
do-while loop is used. This loop places the condition to be evaluated at the
end of the loop.
The syntax of the do-while loops is given here.
Program 3.7
A program to calculate the sum of an Arithmetic Progression (AP).
Self-Instructional
68 Material
Control Structures
and Function
NOTES
Note that all the three loops (for, while and do-while) can be nested
within the body of another loop.
Note: In C++, it is possible to declare a variable within the conditional expression of an if or
switch or while or within the initialization of a for loop which is not permitted in C.
Self-Instructional
70 Material
goto Statement Control Structures
and Function
The goto statement can be used anywhere within a function or a loop. As the
name suggests, goto statements transfer the control from one part to another
part in a program which is specified by a label. Labels are user defined identifiers NOTES
followed by a colon that are prefixed to a statement to specify the destination of a
goto statement.
Program 3.9
A program to demonstrate the use of goto statement.
exit() Function
The exit()function is a standard library function that terminates the entire program
immediately and passes the control to the operating system. This function takes a
single parameter, that is, exit status of the program and returns the same status to
the operating system upon termination. The status can be either zero or non-zero
value where zero shows successful termination and non-zero shows unsuccessful
termination of the program.
Program 3.10
A program to demonstrate the use of exit( ).
Self-Instructional
Material 71
Control Structures
and Function
NOTES
Functions are building blocks of the programs. They make the programs more
modular and easy to read and manage. All C++ programs must contain the function
main(). The execution of the program starts from the function main(). A
C++ program can contain any number of functions according to the needs. Using
functions, programs are structured in a more modular way accessing all the potential
that structured programming can offer to us in C++. A function is a group of
statements that is executed when it is called from some point of the program
includes the following format:
Self-Instructional
74 Material
Control Structures
and Function
NOTES
}
In C++, the function definition consists of two parts, namely the function header
and the function body. The first line of the function definition that specifies the
return_type, function_name and parameter_list of the function is
known as the function header, and the sequence of statements that are executed
when the function is invoked is known as the function body.
Note: Function header must contain the same return type, function name and parameter list
in the same order as the function prototype. However, a function header is not terminated by
a semicolon as a function prototype is.
Note that the definition of the function can appear either before main() or after
it. In case, the function definition appears before main(), there is no need for
declaring the function as the function definition itself acts as the function declaration.
However, if function definition appears after main(), the function needs to be
declared explicitly in the program.
Program 3.11
A program code segment without function declaration.
#include<iostream>
using namespace std;
int func(int x,float y) //function definition
{
//function body
}
int main()
{
//body of main()
}
In this program, since func()is defined before main(), it need not to be declared.
Program 3.12
A program code segment with function declaration.
#include<iostream>
using namespace std;
int func(int,float); //function prototype
int main()
{
//body of main()
}
int func(int x, float y) //function definition
{
Self-Instructional
Material 75
Control Structures //body of the function
and Function
}
In this program, since func()is defined after func(), it needs to be declared
explicitly in the program.
NOTES
Note: The body of one function cannot include the definition of another function. In addition,
only one definition of a function is allowed, except in function overloading.
Invoking Functions
In order to use a function in different parts of a program, the function must be
called or invoked by another function. In C++, functions are called by specifying
the name of the function, followed by the parentheses. The parentheses may or
may not contain a list of arguments depending on the function definition.
The syntax for invoking a function is as follows:
function_name(arg1, arg2, . . ., argN);
where,
function_name = The name of the function
arg1, arg2,...,argN = The list of arguments
Note: A function call does not specify the return type and data types of the arguments.
The function that calls another function is known as the calling function and the
function that is being called is known as the called function. When a function is
called, the control immediately passes from the calling function to the called function.
The called function then executes its body after which the control returns to the
next statement in the calling function.
Program 3.13
A program to demonstrate the invoking of a function.
Self-Instructional
76 Material
Control Structures
and Function
In this program, the function disp() is invoked from the function main().
Thus, the function main() is the calling function and the function disp() is
NOTES
the called function.
Generally, the calling function passes information to the called function through
arguments. The argument(s) that appear in the function call are known as actual
arguments and the argument(s) that appear in the function definition are known
as formal arguments. The number of actual arguments, their order and type in
function call must match with that of formal arguments.
Program 3.14
A program to demonstrate the use of actual and formal argument.
In this program, the function sum() is invoked with two actual arguments, namely
a and b. The values of these arguments are passed to two formal arguments,
namely, x and y. Note that the number of actual arguments and their data types
are same as the formal arguments.
In C++, depending on the way arguments are passed, functions can be called
either by value or by reference.
Self-Instructional
Material 77
Control Structures
and Function 3.4 INLINE FUNCTIONS
Program 3.15
A program to demonstrate how inline function works.
In these statements, two functions named, func() are different as the number
of arguments passed are different. Now, consider these statements.
In these statements, two functions named, func() are different as the data
type of arguments passed is different. Now, consider these statements.
In these statements, two functions named, func() are different as the order of
the data type of the arguments passed is different.
The compiler follows these steps to perform comparison between the actual and
the formal arguments to find the best match (the most appropriate overloaded
function).
x Exact Match: If the number and type of the arguments exactly match the
number and type of parameters of any one of the overloaded functions then
that function is called.
x Match through Type Promotions: If an exact match is not found, the
compiler tries to promote the type of the argument to the type of the
parameter of an overloaded function. For example, if the argument is of
type char, the compiler promotes it to type int or to the equivalent
type unsigned int.
x Match through Standard Conversions: If a match is also not found after
performing type promotions, the compiler tries to convert type of the
argument to type of the parameter through standard conversion rules. For
example, if the argument is of type int, the compiler can convert it to type
float, double or long double.
x Match through User Defined Conversions: If a match is also not found
after performing standard type conversions, the compiler tries to convert
type of the argument to type of the parameter through the user defined
Self-Instructional
conversions.
80 Material
x Match through Ellipsis: If a match is not found after performing the previous Control Structures
and Function
steps, the compiler tries to find an ellipsis in the definition (or declaration) of
any of the overloaded functions.
Program 3.16
NOTES
A program to demonstrate the concept of function overloading.
Self-Instructional
Material 81
Control Structures
and Function
1. In C++, the control statements are broadly classified into three categories,
namely (i) Conditional statements, (ii) Iteration statements and (iii) ump
statements.
2. The switch statement selects a set of statements from the available sets of
statements. The switch statement tests the value of an expression in a
sequence and compares it with the list of integers or character constants.
3. A function declaration is also known as function prototype. Function
prototype provides a model or a blueprint for a function that informs the
C++ compiler about the return type, the function name, and the number
and data type of the arguments passed to the function.
4. An inline function is a function whose code is copied in place of each function
call. In other words, each call to inline function is replaced by its code.
5. Function overloading is a way to implement compile-time polymorphism
that allows multiple functions to share the same name with different parameters.
3.7 SUMMARY
x The control statements are broadly classified into three categories, namely
(i) Conditional statements, (ii) Iteration statements and (iii) Jump statements.
x Conditional statements, also known as selection statements, are used to
Self-Instructional make decisions based on a given condition. If the condition evaluates to
82 Material
True, a set of statements is executed, otherwise another set of statements is Control Structures
and Function
executed.
x The statements that cause a set of statements to be executed repeatedly
either for a specific number of times or until some condition is satisfied are
NOTES
known as iteration statements.
x Functions are building blocks of the programs. They make the programs
more modular and easier to read and manage. All C++ programs must
contain the function main ().
x An array represents a complete block of memory, an entire array cannot be
passed to a function. The array can be passed to the function to avoid
copying a big size of data.
x An inline function is a function whose code is copied in place of each function
call. Inline function is replaced by its code. Inline functions can be declared
by prefixing the keyword inline to the return type in the function prototype.
x Function overloading is a way to implement compile-time polymorphism
that allows multiple functions to share the same name with different parameters.
x Constructors are the most commonly overloaded functions and main () is
the only function that cannot be overloaded.
Self-Instructional
Material 83
Control Structures 4. What is recursive function?
and Function
5. How can a function accept a variable number of arguments?
6. What is recursion?
NOTES 7. What is function overloading?
8. Write one feature of function overriding.
9. What is an operator function?
Long Answer Questions
1. Explain the concept of function prototyping and function definition.
2. Describe how the functions are invoked?
3. Write a program to sort the elements using bubble sort.
4. Write a program to demonstrate the concept of command line arguments.
5. Write a program to demonstrate the concept of recursive function.
6. What is function overriding? Explain with the help of an example.
7. Write a program to demonstrate the concept of overloading a logical
operator.
8. Write a program to demonstrate the concept of operator overloading for
string manipulations.
9. Explain the concept of overloading using friend function with the help of
examples.
Self-Instructional
84 Material
Introduction to Class
BLOCK II
CLASSES AND OBJECTS
NOTES
UNIT 4 INTRODUCTION TO CLASS
Structure
4.0 Introduction
4.1 Objectives
4.2 Classes and Objects
4.2.1 Specifying a Class
4.2.2 Defining Member Functions
4.3 Making an Outside Function Inline
4.4 Nesting
4.4.1 Nesting of Member Functions
4.4.2 Nested Class
4.5 Arrays within a Class
4.6 Answers to Check Your Progress Questions
4.7 Summary
4.8 Key Words
4.9 Self Assessment Questions and Exercises
4.10 Further Readings
4.0 INTRODUCTION
In this unit, you will learn about Classes and Objects in C++. Class is a definition
of an object. Once the class is created, one or more objects can be created from
the class as objects are instance of the class. The C++ structures and classes are
identical in terms of their functionality, that is, all the OOP concepts, such as data
abstraction, encapsulation, inheritance and polymorphism, can be implemented in
both. Thus, they can be used interchangeably with some modifications. However,
to follow the conventions of object oriented programming, classes are generally
used to contain data and functions both while structures are generally used to
contain the data only. You will also learn that a class serves as a template that
provides a layout common to all of its instances known as objects, that is, a class
is only a logical abstraction that specifies what data and functions its objects will
have whereas the objects are the physical entities through which those data and
functions can be used in a program. Thus, objects are considered as the building
blocks of object oriented programming.
Self-Instructional
Material 85
Introduction to Class
4.1 OBJECTIVES
Class is a definition of an object. All class members are private. A class is a type
and an object of the class is a variable. In C++, the data and functions (procedures
to manipulate the data) are worked together as a self-contained unit called an
object. A class is an extended concept similar to that of structure in C programming
language; this class describes the data properties alone. In C++ programming
language, class describes both the properties (data) and behaviors (functions) of
objects. Classes are not objects but they are used to instantiate objects. Classes
contain data known as members and member functions. As a unit, the collection
of members and member functions is an object. Therefore, this unit of objects
makes up a class. In C programming language, a structure is specified with a
name. The C++ programming language extends this concept. A class is specified
with a name after the class keyword. Access specifiers are used to identify
access rights for the data and member functions of the class. The three main types
of access specifiers in C++ programming language are private, public
and protected. Generally, in class, all members (data) will be declared as
private and the member functions would be declared as public. Private
is the default access level. If no access specifiers are identified for members of a
class, the members are defaulted to private access. Once the class is created, one
or more objects can be created from the class as objects are instance of the class.
The concept of specifying a class and defining member function are discussed in
subsequent sections:
4.2.1 Specifying a Class
As you must be aware, a class is a user defined data type that binds data and the
functions that operate on the data together in a single unit. Like other user defined
data types, it also needs to be defined before using its objects in the program. A
class definition specifies a new data type that can be treated as a built-in data
type.
The syntax for defining a C++ class is as follows:
Self-Instructional
86 Material
Introduction to Class
NOTES
where,
C++ keywords
The name of the class
Variables (data) of the class
Functions of the class
Note: The semicolon used immediately after the closing curly brace in the class definition is
mandatory.
The variables and functions declared within the curly braces are collectively known
as members of the class. The variables declared in the class are known as data
members while the functions declared in the class are known as member
functions.
Note: Members of a class cannot be declared with the auto, extern and register
keywords. In addition, the data members cannot be initialized at the time of their declaration
in the class.
The keywords private, public and protected are known as
access specifiers (also known as visibility mode). Each member of a class is
associated with an access specifier. The access specifier of a member controls its
accessibility as well as determines the part of the program that can directly access
the member of the class. When a member is declared private, it can be accessed
only inside the class while a public member is accessible both inside and outside
the class. Protected members are accessible both inside the class in which they
are declared as well as inside the derived classes of the same class. Once an
access specifier has been used, it remains in effect until another access specifier is
encountered or the end of the class declaration is reached. An access specifier is
provided by writing the appropriate keyword (private, public or protected) followed
by a colon ‘:’. Note that the default access specifier of the members of a class is
private, that is, if no access specifier is provided in the class definition, the
access specifier is considered to be private.
Note: The private, public and protected access specifiers can appear in any order
in the class definition. In addition, a particular access specifier can appear more than once in
the class definition.
Program 4.1
A simple class definition. Self-Instructional
Material 87
Introduction to Class
NOTES
In this program, a class named book with two data members title and price
and two member functions getdata() and putdata() is created. As no
access specifier is provided for data members, they are private by default whereas
the member functions are declared as public. It implies that the data members are
accessible only through the member functions while the member functions can be
accessed anywhere in the program.
Generally, data members are declared as private and member functions are
declared as public. Declaring the data members as private hides them from
the rest of the program. This safeguards the data members and prevents any
accidental changes to them by other parts of the program, thereby, implementing
the concept of data hiding of object oriented programming. Similarly, specifying
the member functions as public provides an interface that is visible and accessible
to the other parts of the program.
Note that the member functions can be declared as private, however, it is
useful if the member functions are to be accessed only within other member functions
of the same class and not outside. In addition, all the members (data as well as
functions) of a class can be declared as private. However, such a class prevents
its access from the outside world and does not serve any purpose.
Note: The only difference between a C++ structure and a class is that the data and functions
in a structure are by default public whereas the data and functions in a class are by
default private.
Self-Instructional
88 Material
(outside the class) in the program. Introduction to Class
The definition of member function outside the class differs from the normal
function definition, as the function name in the function header is preceded by the
class name and the scope resolution operator (::). The scope resolution operator
NOTES
informs the compiler what class the member belongs to. The syntax for defining a
member function outside the class is:
Program 4.2
Definition of member function outside the class.
Note that the member functions of the class can directly access all the data members
and other member functions of the same class (private, public or
protected) by using their names. In addition, different classes can use the
same function name.
Inside the Class
A member function of a class can also be defined inside the class. However, when
a member function is defined inside the class, the class name and the scope resolution
operator are not specified in the function header. Moreover, the member functions
defined inside a class definition are by default inline functions.
Note: Member functions that are small in size and frequently used are best suited to be
defined inside the class.
Self-Instructional
Material 89
Introduction to Class Program 4.3
Definition of a member function inside a class.
NOTES
In this program, the member function putdata() is defined inside the class
book. Hence, putdata() is by default an inline function.
Note that the functions defined outside the class can be explicitly made inline by
prefixing the keyword inline before the return type of the function in the function
header. For example, consider the definition of the function getdata().
Self-Instructional
90 Material
Inline function is the optimization technique used by the compilers. One can simply Introduction to Class
prepend inline keyword to function prototype to make a function inline. Inline
function instruct compiler to insert complete body of the function wherever that
function got used in code. An inline function is a function that is actually changed
into the appropriate code by the compiler. Member functions defined outside the NOTES
class and normal functions need the inline keyword. The definition of deposit()
function must be included in one of the source files that create the program. The
member function is combined the definition with the rest of the program. You may
either define a member function inside its class definition or you may define it outside
if you have already declared but not defined the member function in the class
definition. A member function that is defined inside its class member list is called an
inline member function. Member functions containing a few lines of code are usually
declared inline. If you define a member function outside of its class definition, it
must appear in a namespace scope enclosing the class definition. You must also
qualify the member function name using the scope resolution (::) operator. Another
way to declare an inline member function is to either declare it in the class with the
inline keyword or define the function outside of its class or to define it outside
of the class declaration using the inline keyword. In the following example,
member function Y::f() is an inline member function:
Self-Instructional
Material 91
Introduction to Class The inline specifier does not affect the linkage of a member or non-member function
where linkage is external by default. Member functions of a local class must be
defined within their class definition. As a result, member functions of a local class
are implicitly inline functions. These inline member functions have no linkage.
NOTES One of the objectives of OOP is to separate the details of implementation
from the class definition. It is therefore good practice to define the member functions
outside the class. A member function is defined outside the class definition and
makes it inline by just using the qualifier inline in the header line of the function
definition as shown in following code:
Inline function is the optimization technique used by the compilers. One can simply
prepend inline keyword to function prototype to make a function inline. Inline
function instruct compiler to insert complete body of the function wherever that
function is used in the code. Following are the advantages of making an outside
function inline:
x It does not require function calling overhead.
x It also saves overhead of variables PUSH/POP on the stack while function
calling.
x It also saves overhead of return call from a function.
x It increases the locality of reference by utilizing instruction cache.
x After inlining the function, compiler can also apply intra-procedural
optimization, if specified.
4.4 NESTING
Like nested loops and nested structures, classes and the member functions can
also be nested. In this section you will learn about nested member functions and
nested classes.
Self-Instructional
92 Material
4.4.1 Nesting of Member Functions Introduction to Class
Self-Instructional
Material 93
Introduction to Class
NOTES
Note: A nested class defined inside a local class also becomes a local class of the enclosing
function.
The syntax for defining a member function of a nested class outside the enclosing
class is as follows:
Program 4.5
A program to define a nested class.
Self-Instructional
94 Material
Introduction to Class
NOTES
In this program, the class college contains the definition of another class
student. The class student declares a member function fees()which is
defined outside the enclosing class college. Note that the definition of
fees()is qualified with student (name of the nested class) and college
(name of the enclosing class). This is required because fees() belongs to the
class student which in turn belongs to the class college.
Some important points about nested classes and their enclosing classes must be
kept in mind. The points are as follows:
x The nested class cannot access the private members of its enclosing class
and vice versa.
x If a nested class is a private member of the enclosing class, its objects can
only be declared in the enclosing class.
In addition to built-in data types, a class can have array variables as its data
members. Moreover, a user can create an array that can have objects of a class as
its individual elements (array of objects). This section explains how arrays and
objects can be combined to form complex entities.
Arrays can be declared as the members of a class. They can be declared as
private, public or protected members of the class.
Program 4.6
A program to demonstrate the concept of arrays as class members.
Self-Instructional
Material 95
Introduction to Class
NOTES
Self-Instructional
96 Material
In this program, an array marks is declared as a private member of the class Introduction to Class
student for storing a student’s marks in five subjects. The member function
tot_marks()calculates the total marks of all the subjects and displays the
value.
Note: An array that is a data member of a class cannot be initialized at the time of its declaration NOTES
in the class.
Similar to other data members of a class, the memory space for an array is
allocated when an object of the class is declared. In addition, different objects of
the class have their own copy of the array. Note that the elements of the array
occupy contiguous memory locations along with other data members of the object.
For instance, when an object stu of the class student (defined in Example
4.6) is declared, the memory space is allocated for both rollno and marks
as shown in Figure 4.1.
4.7 SUMMARY
x Class: A user defined data type that binds data and the functions to operate
on the data together in a single unit.
x Data Members: The variables declared in the class.
x Member Functions: The variables and functions declared within the curly
braces.
x Inline Function: A function whose code is copied in place of each function
call
Self-Instructional
98 Material
2. Explain the definition of member functions outside and inside the class with Introduction to Class
Self-Instructional
Material 99
Memory Allocation
for Objects
UNIT 5 MEMORY ALLOCATION
FOR OBJECTS
NOTES
Structure
5.0 Introduction
5.1 Objectives
5.2 Creating Objects
5.2.1 Memory Allocation for Objects
5.2.2 Accessing Members of a Class
5.2.3 Static Data Members
5.2.4 Static Member Functions
5.3 Array of Objects
5.4 Objects as Function Arguments
5.5 Returning Objects from Function
5.6 Answers to Check Your Progress Questions
5.7 Summary
5.8 Key Words
5.9 Self Assessment Questions and Exercises
5.10 Further Readings
5.0 INTRODUCTION
In this unit, you will learn about the static member of class‚ array of objects and
friend functions. A class can have array variables as its data members. Therefore,
a user can create an array that can have objects of a class as its individual elements
(array of objects). The objects of a class can be passed as arguments to member
functions as well as non-member functions either by value or by reference. When
an object is passed by value, a copy of the actual object is created inside the
function. This copy of the object is destroyed when the function terminates. The
const qualifier is used with the variables of basic data types to prevent them from
being modified by the function. In a similar way, const qualifier can also be applied
to member functions, member function arguments and the objects of a class. A
non-member function that is made a ‘friend’ of a class is known as a friend function.
A friend function has access to all the private and protected members of a class of
which it is a ‘friend’. Friend functions are declared with the friend keyword
inside the class. The nested member function can be invoked directly without
using the dot operator. The static data members are useful in situations where
either a common item of information is to be shared among all the objects or the
number of objects actually in existence is to be determined.
Self-Instructional
100 Material
Memory Allocation
5.1 OBJECTIVES for Objects
Once a class is defined, it can be used to create variables of its type known as
objects. The relation between an object and a class is same as that of a variable
and its data type.
Note: Since an object is an instance of a class, the process of declaring an object of a class
is known as instantiation.
The syntax for declaring an object is as follows:
where,
The name of the class
A comma-separated list of objects
Program 5.1
Declaring objects of a class:
In this example, three objects namely, book1, book2 and book3 of the class
book have been created in main().
Note that the syntax for the declaration of objects of a particular class is
same as that for the declaration of variables of a built-in data type. To understand
this concept, consider these statements.
Self-Instructional
Material 101
Memory Allocation Like structures, objects of a class can also be declared at the time of defining the
for Objects
class as shown here.
NOTES
Hence, the objects of the class book (defined in Program 5.1) can also be declared
with the help of these statements.
Fig. 5.1 Memory Allocation for the Objects of the Class book
Note: Memory is allocated to each object of a class sufficient to hold all its data members.
Self-Instructional
102 Material
5.2.2 Accessing Members of a Class Memory Allocation
for Objects
As stated earlier, the members of a class can be directly accessed inside the class
using their names. However, accessing a member outside the class depends on its
access specifier. The access specifier not only determines the part of the program NOTES
where the member is accessible, but also how it is accessible in the program.
Accessing Public Members
The public members of a class can be accessed outside the class directly using the
object name and dot operator ‘.’ . The dot operator associates a member with
the specific object of the class.
The syntax for accessing a public data member outside the class is as follows:
Program 5.2
A code segment to demonstrate the concept of accessing public members of a
class.
Self-Instructional
Material 103
Memory Allocation In this program, a class number having three data members x, y and z is
for Objects
defined. The data member x is private by default whereas y and z are declared
as public. Hence, y and z can be accessed directly outside the class using the
object name and the dot operator. However, x being a private data member
NOTES cannot be accessed directly outside the class.
Accessing Private Members
The private members of a class are not accessible outside the class not even with
the object name. However, they can be accessed indirectly through the public
member functions of that class.
Program 5.3
A program to demonstrate the concept of accessing private members of a class.
In this program, the object book1 of class book is used to access the public
member function getdata() that provides an indirect access to private data
members title and price.
Program 5.4
A program to demonstrate the concept of classes and objects in C++.
Self-Instructional
104 Material
Memory Allocation
for Objects
NOTES
However, when the static data member is defined outside the class, the keyword
static is not required. The syntax for defining a static data member is as follows:
Generally, the static data members are initialized when they are defined. In case,
the static data member is not initialized to any value, the compiler automatically
initializes the static data member. If the static data member is of the type int,
float, double, or bool, the compiler initializes it with zero value. Similarly,
if the static data member is of the type char, the compiler initializes it with the null
character (‘\0’).
Consider this class definition.
Self-Instructional
106 Material
Memory Allocation
for Objects
Here, the static data member total is declared inside the class, and defined
outside the class definition and initialized with zero value.
NOTES
Note: Declaration of static data members without defining them or definition of static data
members without specifying the class name results in a link-time error.
Program 5.5
A program to demonstrate the usage and effect of static data members.
Self-Instructional
Material 107
Memory Allocation
for Objects
In this program, the variable total is declared as a static data member inside
the class and is initialized with zero value outside the class. Note that, since the
static variable total is being shared by all the objects, the show() function
displays the same value of total for all the objects. However, the value of the
other member variable (item_no) is different for different objects (refer Figure
5.2).
Self-Instructional
108 Material
Memory Allocation
for Objects
NOTES
Note: If the static member function is defined outside the class, then the keyword static
is specified only in its declaration and not in its definition.
A static member function can be accessed using either the class name and scope
resolution operator or object name and dot operator. However, the first approach
is generally used, as static members are considered to be a part of the class not of
any object of the class. Note that a static member function cannot be declared as
const. Moreover, there cannot be static and non-static version of the same
function.
Program 5.6
A program to demonstrate the usage and effect of static member functions.
Self-Instructional
Material 109
Memory Allocation
for Objects
NOTES
In this program, a static data member count and a static member function
show_count() are defined. The variable count calculates the total number
of objects created and show_count() displays the current value of count.
The value of count is incremented and assigned to serial each time an
object invokes the get_serial()function. Note that the keyword static
is not specified with the function header as the static member function
show_count() is defined outside the class.
Note: Accessing of non-static members (either data or functions) of a class inside a static
member function results in a compile-time error.
Self-Instructional
110 Material
Memory Allocation
5.3 ARRAY OF OBJECTS for Objects
Like array of other user-defined data types, an array of type class can also be
created. The array of type class contains the objects of the class as its individual NOTES
elements. Thus, an array of class type is also known as array of objects. An
array of objects is declared in the same way as an array of any built-in data type.
The syntax for declaring an array of objects is as follows:
Self-Instructional
Material 111
Memory Allocation
for Objects
NOTES
NOTES
Self-Instructional
Material 113
Memory Allocation
for Objects
NOTES
NOTES
Figure 5.4 shows accessing of member variables inside the sum_weight() function.
w3
kilogram
gram
w3.sum_weight(w1,w2)
w1 w2
w1.kilogram w2.kilogram
w1.gram w2.gram
Self-Instructional
Material 115
Memory Allocation
for Objects 5.5 RETURNING OBJECTS FROM FUNCTION
A function can also return objects either by value or by reference. When an object
NOTES is returned by value from a function, a temporary object is created within the
function, which holds the return value. This value is further assigned to another
object in the calling function. The syntax for defining a function that returns an
object by value is as follows:
Self-Instructional
116 Material
Memory Allocation
for Objects
NOTES
This program produces the same output as that of Program 5.8. The only difference
lies in the implementation of the sum_weight() function. As the return type
of function is (an object of class ), a temporary object
is created within the function for holding return values. These values are
accessed as temp.kilogram and by the function. When the control
returns to , the object temp is assigned to the object w3 in
Figure 5.5 represents accessing of member variables within the function and the
returning result from the temporary object.
temp.kilogram
temp.gram
w3=w1.sum_weight(w2)
w1 w2
kilogram w2.kilogram
gram w2.gram
However, a reference to the local object (object declared inside the function)
cannot be returned from the function since a reference to local data points to data
within the function. Hence, when the function terminates and local data is destroyed,
this reference points to nothing.
For example, consider the function (defined in Program
5.9) that is modified as shown in the following code segment:
Self-Instructional
Material 117
Memory Allocation
for Objects
NOTES
In this code segment, an attempt has been made to return the reference to an
object of type (that is temp). However, it is not possible as the object
is local to the function and a reference to this object
remains effective only within the function. Thus, returning a reference to
object outside the function generates a compile-time error.
5.7 SUMMARY
Self-Instructional
Material 119
Memory Allocation
for Objects 5.10 FURTHER READINGS
Self-Instructional
120 Material
Constructors and
DESTRUCTORS
NOTES
Structure
6.0 Introduction
6.1 Objectives
6.2 Constructors and Destructors: An Introduction
6.2.1 Constructors
6.2.2 Parameterized Constructors
6.2.3 Multiple Constructors with Default Arguments
6.3 Copy Constructor
6.4 Dynamic Constructor
6.5 Destructors
6.6 Invoking Constructors and Destructors
6.6.1 Dynamic Initialization of Objects
6.6.2 Constructing Two-Dimensional Arrays
6.7 Answers to Check Your Progress Questions
6.8 Summary
6.9 Key Words
6.10 Self Assessment Questions and Exercises
6.11 Further Readings
6.0 INTRODUCTION
In this unit, you will learn about constructors and destructors. In C++, classes are
the logical entities that specify what data and functions their objects will have, and
the objects are the physical entities. Therefore, memory is allocated to the objects
and not to the classes. To work with objects containing valid values, they need to
be initialized. For this, C++ provides constructor function that automatically initializes
objects when they are created. Similarly, memory allocated to objects must be
released when a program is terminated which is accomplished by another function
called destructor. A copy constructor is a constructor that initializes a new object
of a class with the values of an existing object of the same class.
6.1 OBJECTIVES
NOTES In addition to all of the member functions you will create for your objects, there
are two special kinds of functions that you should create for every object. These
functions are called constructors and destructors. The concept of constructors
and destructors are discussed in detail in subsequent sections:
6.2.1 Constructors
A constructor is a special member function that constructs a storage area for the
data members of an object by allocating and initializing the memory for them.
Hence, it makes the object functional by converting an object with the unused
(uninitialized) memory into a usable (initialized) object. It is special as it has the
same name as that of the class and is automatically invoked whenever an object of
the class is created. Constructors are called every time you create an object and
destructors are called every time you destroy an object. The constructor is a
function whose name is the same as the object and with no return type (void is
also not included).
Unlike other member functions, a constructor does not have any return
type (not even void); this is, because the constructor is invoked automatically
by the system and, hence, no program is defined for it to return anything. The
name and the absence of a return type help a compiler to distinguish a constructor
from the other member functions of the class. Note that a constructor must be
declared as public otherwise the objects of the class cannot be instantiated.
Like other member functions of the class, a constructor can also be defined either
inside or outside the class definition. The syntax to define a constructor (inside the
class) is as follows:
where,
parameter_list is optional.
Note: Inside the class, a constructor is treated as an inline function.
Self-Instructional
122 Material
The syntax to define the constructor outside the class is as follows: Constructors and
Destructors
NOTES
where,
parameter_list is optional.
Calling Constructors
Once a constructor is defined, it can be called implicitly as well as explicitly. If the
name of the constructor is not used in the object declaration, the call is known as
an implicit call to the constructor. On the other hand, if the name of the constructor
is used in the object declaration, the call is known as an explicit call to the
constructor.
Program 6.1
A code segment to demonstrate the calling of constructor implicitly and explicitly.
Self-Instructional
Material 123
Constructors and
Destructors
NOTES
In this program, two objects, namely, disp and disp1 of the class display
are declared and initialized. The object disp is initialized by implicitly calling the
constructor, whereas disp1 is initialized by explicitly calling the constructor, that
is, by using the constructor name, display().
Note: A constructor and other member functions of the same class can call each other.
Default Constructors
Whenever a class is defined without constructor definition, the compiler provides
a default constructor to construct the objects of a class. This default constructor
initializes all the data members with garbage values. However, to initialize the data
members with valid values the default constructor needs to be defined explicitly.
In such cases, the default constructor provided by the compiler is overridden.
6.2.2 Parameterized Constructors
When different objects need to be initialized with different values, a parameterized
constructor can be defined. A parameterized constructor is a constructor that
accepts one or more parameters at the time of declaration of objects and initializes
the data members of the objects with these parameters.
Program 6.2
A program to demonstrate the concept of parameterized constructor.
Self-Instructional
124 Material
Constructors and
Destructors
NOTES
Self-Instructional
126 Material
In this program, the constructor count()with one parameter initializes the object Constructors and
Destructors
c using the assignment operator ‘=’. Note that in the statement count c = 1,
1 is automatically assigned to x. In this initialization, the conversion from the type
of the parameter, int to the type of the class, count is automatically created.
Such a constructor is known as an implicit constructor. However, automatic NOTES
conversion can be prevented by declaring the constructor with the keyword
explicit. For example, the constructor in Program 6.3 can be written as
follows:
Such a constructor is known as an explicit constructor. Now, all the class type
values must be assigned to the objects of the class. Thus, the statement count
c = 1 gives a compile-time error. An explicit constructor can be invoked either
through the normal constructor syntax, count c(1) or by converting the
parameter to the class type using the statement, count c = count(1).
Note: A constructor of a class cannot accept object of the same class as parameter. However,
it can accept a reference of the object and such constructor is known as copy constructor.
Self-Instructional
Material 127
Constructors and
Destructors
NOTES
As you have learned earlier, the objects of a class can be initialized either with
same values using default constructor or with different values using parameterized
constructor. However, a new object of a class can also be initialized with an existing
object of the same class. For this, the compiler calls another constructor, known
as the copy constructor. A copy constructor is a constructor that initializes a new
object of a class with the values of an existing object of the same class. In addition
to this, a copy constructor is called in various situations given here.
x When an object is passed by value to a function, the copy constructor is
called instead of a normal constructor. This is because the copy constructor
initializes new object with the current state (or value) of an existing object
and not with the initial state of the existing object. Whereas if the normal
constructor is called, it initializes some aspects of an object and alters the
contents of the object.
x When an object is returned from a function, a temporary object is
automatically created by a copy constructor to store the return value of a
function.
The syntax to define a copy constructor is as follows:
Self-Instructional
Material 129
Constructors and
Destructors
Self-Instructional
130 Material
Constructors and
Destructors
NOTES
In this program, the copy constructor is called when the new object p2 is declared
and initialized with the existing object p1. The copy constructor initializes p2 by
copying the values of x and y of the object p1 to x and y of the object p2. This
implies that p2 is an identical copy of p1. Note that the statement point
p2(p1)can also be written as given here.
Self-Instructional
Material 131
Constructors and
Destructors
Note: The initialization of an object with another object using the copy constructor is known
as copy initialization.
If a copy constructor is not provided explicitly, the compiler provides a
NOTES
default copy constructor that makes a member-wise copy (or shallow copy) of
the existing object. If the class does not have pointer variables, there is no need to
define the copy constructor explicitly. However, if a class contains a pointer and
the copy constructor is not explicitly provided, the compiler calls the default copy
constructor. The default copy constructor copies only the length and the address
of an existing object into the new object and not the actual data (or characters).
This is called the shallow copy which is shown in Figure 6.1.
In this figure, the new object uses the same memory, which is used by the existing
object instead of allocating new memory to it. As a result, the changes made in the
new object modify the contents of the existing object. Moreover, after destroying
any single object, the other object will be left with a dangling pointer. Hence, in
such situations, a copy constructor must be explicitly defined that performs the
deep copy of the object by copying the length, actual data and address of the
object as shown in Figure 6.2.
The objects of a class, so far, have been initialized at the compile-time using
constructors. However, the object’s memory can also be constructed at the runtime
with the help of a dynamic constructor. A dynamic constructor is a constructor
Self-Instructional
132 Material
that allocates memory to the objects at the time of their construction using the Constructors and
Destructors
new operator. Moreover, it enables the objects of different sizes to be allocated
the required amount of memory and hence, saves the memory space.
To understand the concept of dynamic constructors, consider this program.
NOTES
Program 6.6: A program to demonstrate a dynamic constructor.
Self-Instructional
Material 133
Constructors and
Destructors
NOTES
In this program, obj1 invokes the default constructor and this constructor
allocates memory to character pointer name using new operator. Similarly, obj2
invokes the parameterized constructor that accepts character pointer as an
argument, calculates its length and then dynamically allocates the required memory
(that is, length and an additional space for the null-terminated character ‘\0’) for
name. The object obj1 calls the member function rev() and passes obj2
as an argument. The member function rev()calculates the length of the string of
obj2, reverses and stores it in name of object obj1.
6.5 DESTRUCTORS
Once an object is declared, the memory space is allocated to the data members.
In addition, during the execution of the program, the object may use other resources,
such as files and so on. These resources and the memory allocated to objects
must be released when an object is destroyed (or goes out of scope). This is
accomplished by another special member function called destructor that is
automatically invoked to release all the resources and memory that an object
acquires during its lifetime. In this way, a destructor releases the resources and
memory at runtime to clean up the unused storage area.
Like a constructor, a destructor is also special as it has the same name as
that of the class of which it is a member but with a tilde (~) prefixed to its name. A
tilde (~) is a C++ complement operator which reminds that a destructor is a
complement of the constructor (creation). A destructor neither accepts any
parameter nor has a return type (not even void). A destructor cannot be
overloaded, that is, there can only be one destructor in a class. Hence, a single
destructor is used to destroy all the objects of a class created either using default,
parameterized or copy constructor.
Note: Like a constructor, the destructor can be called within any other member functions.
Similarly, other member functions can be called within a destructor.
The syntax to define a destructor of a class is as follows:
Self-Instructional
134 Material
Constructors and
Destructors
NOTES
Note: Destructor can also be defined either inside or outside the class. However, it should be
defined in the public section of the class to avoid the compile-time error.
A destructor is invoked implicitly by the compiler when an object goes out
of scope. However, if the object is created dynamically, it is difficult for the compiler
to know whether the pointer points to something possessed by the object and that
also has to be deleted along with the object or something independent of the
object. Hence, the destructor must be explicitly provided.
To understand the concept of destructor, consider Program 6.2. In this program,
the destructor for the class library can be specified as shown here:
Self-Instructional
Material 135
Constructors and
Destructors
NOTES
In this program, since two objects, namely lib1 and lib2 were created, the
destructor is called twice.
The constructor and the destructor of a class are automatically invoked when the
memory is allocated and de-allocated to an object, respectively. Moreover, when
multiple objects of a class are created, the constructor for each object is called in
the order in which the objects are declared. However, the destructor for each
object is called in the reverse order of the constructors, that is, in the reverse
order of the object creation.
Note that for the objects with local scope, the constructor is called when
their declaration is encountered in the respective block or function, while the
destructor is called when the block or function terminates. For objects with global
scope, the constructor is called only once when their declaration is encountered
(generally, before main()) in the program and the destructor is called when the
program terminates.
6.6.1 Dynamic Initialization of Objects
Parameterized constructors can also be used to dynamically initialize the objects
of a class. That is, the parameterized constructor can initialize the object with the
values provided by the user at runtime. Moreover, by using multiple constructors
in a class, different formats of initialization can be provided.
To understand the concept of dynamic initialization of objects, consider this
program.
Program 6.7: A program to demonstrate dynamic initialization of objects.
Self-Instructional
136 Material
Constructors and
Destructors
NOTES
Self-Instructional
Material 137
Constructors and The output of the program is:
Destructors
NOTES
In this program, the values of p, t, d1 and d2 are provided by the user at runtime and
thus, the data members of the class are initialized dynamically. Since the constructor
item()is overloaded, it provides different formats of initialization, that is, item
i1(p, t), item i2(p, t, d1)and item i3(p, t, d2). Both the statements
item i1(p, t)and item i2(p, t, d1) invoke first constructor and the state-
ment item i3(p, t, d2)invokes second constructor.
6.6.2 Constructing Two-Dimensional Arrays
Like one-dimensional arrays, two-dimensional arrays can also be declared as
members of a class. They can be declared as private, public or protected members
of the class. Moreover, they can be initialized at the run-time.
Program 6.8: A program to demonstrate the initialization of the two-dimensional
array at run-time
Self-Instructional
138 Material
Constructors and
Destructors
NOTES
Self-Instructional
Material 139
Constructors and
Destructors 6.7 ANSWERS TO CHECK YOUR PROGRESS
QUESTIONS
6.8 SUMMARY
Self-Instructional
140 Material
x Dynamic Constructor: It is a constructor that allocates memory to the Constructors and
Destructors
objects at the time of their construction using the new operator.
x Copy Constructor: It is a constructor that initializes a new object of a
class with the values of an existing object of the same class.
NOTES
Self-Instructional
Material 141
Inheritance
BLOCK III
INHERITANCE, POLYMORPHISM AND POINTERS
NOTES
UNIT 7 INHERITANCE
Structure
7.0 Introduction
7.1 Objectives
7.2 Inheritance
7.2.1 Single Inheritance
7.2.2 Multilevel Inheritance
7.2.3 Multiple Inheritance
7.2.4 Hierarchical Inheritance
7.2.5 Hybrid Inheritance
7.2.6 Defining Derived Classes
7.2.7 Making a Private Member Inheritable
7.3 Virtual Base Classes
7.4 Abstract Classes
7.4.1 Order of Calling of Constructor and Destructor
7.4.2 Parameterized Constructors
7.5 Member Classes: Nesting of Classes
7.5.1 Containership versus Inheritance
7.6 Answers to Check Your Progress Questions
7.7 Summary
7.8 Key Words
7.9 Self Assessment Questions and Exercises
7.10 Further Readings
7.0 INTRODUCTION
In this unit, you will learn about the concept of inheritance, virtual base classes and
abstract classes. In Object Oriented Programming or OOP, inheritance is a way
to reuse code of existing objects, establish a subtype from an existing object or
both depending upon programming language support. A super class, base class or
parent class is a class from which other classes have been derived. The classes
that are derived from a super class are known as subclasses or derived classes or
child classes. A super class allows for a generic interface to include specialized
functionality through the use of virtual functions. A subclass is a class that inherits
some properties from its super class.
7.1 OBJECTIVES
In inheritance, the class that is inherited by the new class is called the base class or
superclass or parent class. The class that inherits the members of the old class is
called the derived class or sub class or child class. Figure 7.1, for example,
shows four classes, named animal, carnivore, herbivore and
omnivore. The class animal is a base class inherited by the derived classes
carnivore, herbivore and omnivore. The derived classes
carnivore, herbivore and omnivore inherit all the members (properties
and functionality) of the base class animal.
In addition to the base class members, the derived class also contains its own
members. It implies that the derived class extends the base class as shown in
Figure 7.2.
Self-Instructional
Material 143
Inheritance 7.2.1 Single Inheritance
When a derived class inherits from a single base class, it is referred to as single
inheritance. In single inheritance, the derived class inherits all the members of its
NOTES base class and can directly access the public and protected members of the base
class. Figure 7.3 shows single inheritance in which derived class triangle is inherited
from the single base class polygon.
Self-Instructional
144 Material
Inheritance
NOTES
The syntax to define the derived class that implements multiple inheritance is as
follows:
Program 7.1
A program to demonstrate multiple inheritance.
Self-Instructional
Material 145
Inheritance
NOTES
Self-Instructional
146 Material
Inheritance
NOTES
In this program, the class owner simultaneously inherits two classes, namely
person and company. This implies that person and company are the
base classes of owner.
7.2.4 Hierarchical Inheritance
Hierarchical inheritance is a type of inheritance in which more than one class is
derived from a single base class. In hierarchical inheritance, a base class provides
members that are common to all of its derived classes. Figure 7.6, for example,
shows hierarchical inheritance in which two classes graduate and undergraduate
are derived from single base class student.
In hierarchical inheritance, each of the derived class inherits all the members of its
base class. In addition, all the derived classes can directly access the public and
protected members of the base class. However, one derived class cannot access
the members of another derived class.
The syntax to implement hierarchical inheritance (with two derived classes) is as
follows:
Self-Instructional
Material 147
Inheritance
NOTES
Program 7.2
A program to demonstrate hybrid inheritance.
Self-Instructional
148 Material
Inheritance
NOTES
Self-Instructional
Material 149
Inheritance
NOTES
In this program, the derived class bill inherits the base class sell which in
turn is derived from the base class item. Hence, multilevel inheritance is formed.
The class bill inherits two base classes discount and sell forming the
multiple inheritance. The multiple and multilevel inheritance, in this program, together
form hybrid inheritance.
7.2.6 Defining Derived Classes
Inheritance is implemented while defining the derived class. The name of the base
class is specified in the derived class definition. Since the derived class is non-
existent, when a base class is defined, the inheritance is implemented only at the
time of derived class definition. The syntax to define a derived class is as follows:
Self-Instructional
150 Material
Inheritance
where,
NOTES
class = C++ keyword
derived_class = The name of the derived class
: = Colon—indicates that derived_class is inherited from base_class
access_specifier = The access specifier of the base class—can be any
of the three keywords, private, public or protected
base_class = The name of the base class
Program 7.3
A program code segment to demonstrate the concept of defining a derived class.
In this program, two classes, namely polygon and triangle are defined.
In the definition of the class triangle, the colon indicates that triangle
inherits polygon. This implies, triangle is the derived class and polygon
is the base class. The keyword public is the access specifier of the base class
polygon.
7.2.7 Making a Private Member Inheritable
Sometimes, private members of a base class need to be accessed inside a derived
class but not by other classes and functions in the program. In such situations, the
private member can be made as public. However, making a data member as
public makes it accessible outside both the base class and the derived class. In
C++, this problem can be solved by declaring the members of the base class as
protected members. The protected members of a base class can be directly
accessed (without any objects) inside a derived class.
Self-Instructional
Material 151
Inheritance
7.3 VIRTUAL BASE CLASSES
Note: The position of the virtual keyword and the access specifier
of the base class can be interchanged. This implies that the syntax class
derived_class : access_specifier virtual base_class
{..}; is also valid.
Program 7.4: A program to demonstrate the concept of virtual base class
Self-Instructional
152 Material
Inheritance
NOTES
Self-Instructional
Material 153
Inheritance
NOTES
In this program, the class person is specified as a virtual base class while
defining employee and student. This implies that only one copy of data
members and member functions exists for both employee and student. As
a result, when object a1 accesses the members of indirect base class person,
no ambiguity arises.
Self-Instructional
154 Material
Inheritance
A class that contains at least one pure virtual function is known as an abstract
class or abstract base class. An abstract class is different from a polymorphic
class. The objects of an abstract class cannot be created, as at least one of its
members (that is pure virtual function) lacks implementation. This implies that
abstract classes can only be used to act as a base class for other classes and not
for instantiation. In addition, an abstract class cannot be used as an argument or
the return type of a function. However, a pointer to an abstract class can be made.
Moreover, an abstract class can be derived from a non-abstract class by overriding
its non-pure virtual function with a pure virtual function.
Note: A class derived from an abstract class remains abstract unless each
pure virtual function is overridden in the derived class.
Constructors in derived classes
As discussed earlier, a constructor is a special member function of a class that
allows the object to be initialized with the valid values at the time of object
declaration. A constructor is required in inheritance to initialize the members of the
base class through derived class. The derived class defines its own constructor in
order to initialize its new members. However, to initialize the members inherited
from the base class, the base class constructor is called. After the constructors are
called, the destructors are also called to destroy the objects. However, constructors
and destructors are called in a particular order.
Note: A derived class does not inherit the constructor and the destructor of
its base class. However, constructors and destructors of the base class are
explicitly called inside the derived class.
7.4.1 Order of Calling of Constructor and Destructor
When an object of the derived class is declared, the constructor of the base class
is called first and then the constructor of the derived class is called. The constructor
of the base class is called first because the base class members need to be initialized
first as the derived class initialization depends on the base class initialization. In
other words, the derived class uses base class members for its initialization.
However, when an object of the derived class is destroyed, destructors are
called in the reverse order. That is, the destructor of the derived class is called first
and then the destructor of the base class. Destructors are executed in the reverse
Self-Instructional
Material 155
Inheritance order as base class is a foundation for the derived class; therefore, destruction of
the base class object implies destruction of the derived class object. Hence, the
derived class destructor is called before the base class destructor.
Program 7.5: A program to demonstrate the order in which constructors and
NOTES
destructors are called in inheritance
Self-Instructional
156 Material
Inheritance
In this program, the derived class table inherits the base class wood.
NOTES
When the object t1 of the class table is declared in main(), constructor of
wood is called first and then the constructor of table is called. However, when
t1 is destroyed (when main()terminates), the destructor of table is called
first and then the destructor for wood.
Note: The public and the protected members of the base class can be
directly initialized using assignment statements in the body of the derived class
constructor.
In case of multiple inheritance, the base class constructors are called in the
order in which the base classes are specified in the derived class definition, that is,
from left to right. However, when an object of the derived class is destroyed, the
derived class destructor is called before any of the base class destructors is called.
The base class destructors are called in the reverse order of calling the base class
constructors, that is, from right to left.
Program 7.6: A program to demonstrate the order of constructors and destructors
in multiple inheritance
Self-Instructional
Material 157
Inheritance
NOTES
In this program, the class owner inherits the base classes bank and
person. When the object o1 of the class owner is declared in main(), the
constructors of bank and person are called before the constructor of owner.
Note that the constructor of bank is called first and then the constructor of
person is called (left to right). However, when o1 is destroyed, the destructors
are called in the reverse order of calling the constructors. This implies that the
destructor of owner is called first, then the destructor of person is called and
finally, the destructor of bank is called (right to left).
7.4.2 Parameterized Constructors
Parameterized constructors are used to dynamically initialize the object of the
class. The parameterized constructors of the base class can be called by providing
the values through the derived class constructor. This is accomplished by explicitly
calling the parameterized constructor of the base class in the header of the derived
class constructor. The arguments of the parameterized constructor can be provided
through the arguments of the derived class constructor. The syntax for defining a
derived class constructor that explicitly calls one or more base class constructor is
as follows:
Self-Instructional
158 Material
Here, base_class1(parameter_list1), Inheritance
Self-Instructional
Material 159
Inheritance
NOTES
In this program, when the object c1 of the class ccc is declared, the
constructor of c1 explicitly calls the constructors of aaa and bbb and passes
the appropriate arguments to them. Note that the constructor of bbb is called
before the constructor of aaa and then the constructor of ccc is called. When
c1 is destroyed, the destructors are called in the reverse order of constructors.
This implies that first the destructor of ccc is called, then the destructor of aaa
and finally, the destructor of bbb is called.
Note: If a base class has a parameterized constructor, it is mandatory for
the derived class to define a constructor and pass the arguments for the base
class constructor.
When a class has an object of another class as its member it is known as nesting
of classes or containership. Containership (or containment or aggregation or
composition), like inheritance, enables the implementation of a logical relationship
between classes. The class (enclosing class) that contains an object of another
class has access only to the public members of that class. The private and protected
members of the contained class are not accessible to the enclosing class.
Self-Instructional
160 Material
Program 7.8: A program to demonstrate the nesting of classes Inheritance
NOTES
Self-Instructional
Material 161
Inheritance
NOTES
Self-Instructional
162 Material
Inheritance
NOTES
Containership Inheritance
The object of one class is used as a member in The object of one class inherits the property
another class. of another class.
Does not support the concept of reusability. Supports the concept of reusability.
Does not provide additional features to the Provides additional features to the existing
existing class. class.
Represents ‘has-a’ relationship. Represents ‘is-a-kind-of’ relationship.
The private and protected members of the The derived class can access the protected
inner class are not accessible to the enclosing members of the base class.
class.
NOTES
7.7 SUMMARY
x The class that is inherited by the new class is called the base class or
superclass or parent class.
x Hierarchical inheritance is a type of inheritance in which more than one
class is derived from a single base class.
x The derived class is non-existent, when a base class is defined, the inheritance
is implemented only at the time of derived class definition.
x Virtual base class is an indirect base class declared using the keyword virtual
in order to prevent its duplication.
x A class that contains at least one pure virtual function is known as an abstract
class or abstract base class.
x The parameterized constructors of the base class can be called by providing
the values through the derived class constructor.
x Derived Class: It is the class that inherits the members of the old class or
base class.
x Hierarchical Inheritance: It is a type of inheritance in which more than
one class is derived from a single base class.
x Abstract Class: It a class that contains at least one pure virtual function.
Self-Instructional
164 Material
3. Explain the concept of virtual base classes. Inheritance
Self-Instructional
Material 165
Pointers, Virtual Functions
and Polymorphism
UNIT 8 POINTERS, VIRTUAL
FUNCTIONS AND
NOTES
POLYMORPHISM
Structure
8.0 Introduction
8.1 Objectives
8.2 Pointers and Polymorphism
8.2.1 Pointer Declaration and Initialization
8.2.2 Pointers to Objects
8.2.3 this Pointer
8.2.4 Pointers to Derived Classes
8.2.5 Compile-Time Polymorphism
8.2.6 Runtime Polymorphism
8.3 Virtual Functions
8.3.1 Virtual Member Function Access
8.3.2 Virtual Function Call Mechanism
8.3.3 Late Binding
8.4 Answers to Check Your Progress Questions
8.5 Summary
8.6 Key Words
8.7 Self Assessment Questions and Exercises
8.8 Further Readings
8.0 INTRODUCTION
In this unit, you will learn about the pointers. A pointer ‘points to’ and hence the
name ‘pointer’ a particular location in the memory. In addition, the memory can
be allocated and de-allocated to the variables at runtime using pointers. This unit
explains how pointers and virtual functions help in implementing run-time
polymorphism, thereby achieving dynamic binding. In C++, polymorphism can be
achieved either at compile-time or at run-time. At compile-time, polymorphism is
implemented using operator overloading and function overloading. However, at
run-time, it is implemented using virtual functions.
8.1 OBJECTIVES
A pointer is a variable that contains the address (not the value) of another variable
or a literal. In other words, a pointer ‘points to’ (hence, the name ‘pointer’) a
particular location in the memory. In addition, the memory can be allocated and
de-allocated to the variables at runtime using pointers.
By default, C++ matches a function call with the correct function definition
at compile time. This is called static binding. You can specify that the compiler
match a function call with the correct function definition at runtime; this is called
dynamic binding. You declare a function with the keyword virtual if you
want the compiler to use dynamic binding for that specific function. To implement
virtual functions, C++ uses a special form of late binding known as the virtual
table. Polymorphism is a powerful feature of the object oriented programming
language C++. A single operator + works differently in different data types, such
as integer, float or strings referring the concept of polymorphism. The concept of
overloading is also a branch of polymorphism. When the exiting operator or function
operates on new data type it is overloaded. This feature of polymorphism leads to
the concept of virtual methods. Polymorphism refers to the ability to call different
functions by using only one type of function call. Suppose a programmer wants to
code vehicles of different shapes, such as circles, squares, rectangles, etc. One
way to define each of these classes is to have a member function for each that
makes vehicles of each shape. Another convenient approach the programmer can
take is to define a base class named Shape and then create an instance of that
class. The programmer can have array that hold pointers to all different objects of
the vehicle followed by a simple loop structure to make the vehicle, as per the
shape desired, by inserting pointers into the defined array. This approach leads to
different functions executed by the same function call. Polymorphism is used to
give different meanings to the same concept. This is the basis for Virtual function
implementation. The basics of pointer declaration and initialization, pointers to
objects, this pointer, pointers to derived class, compile-time and runtime
polymorphism are discussed in subsequent sections.
8.2.1 Pointer Declaration and Initialization
Like other variables, a pointer variable must be declared before it is used in the
program. The declaration of pointers is similar to that of an ordinary variable, that
is, by specifying the data type and the name of variable. However, the only
difference is that the data type of a pointer is followed by an asterisk ‘*’. The
syntax for declaring a pointer variable is as follows:
Self-Instructional
Material 167
Pointers, Virtual Functions The data type of a pointer variable (also known as the base type) informs the
and Polymorphism
compiler about the type of variables the pointer can point to. To understand pointer
declaration, consider the following statements:
NOTES
Note: A space can be put either before or after the asterisk. Hence, both the statements,
int* iptr and int *iptr are valid.
Once a pointer variable is declared, it needs to be initialized with the memory
address of a variable of an appropriate data type (similar to the base type). The
address of a variable (declared earlier) can be obtained by prefixing its name with
the pointer operator named address-of operator. The address-of (&) operator
also called reference operator is a unary operator that returns the address of a
variable stored in the memory. For example, consider the following statements:
In these statements, a pointer variable ptr of type int is declared and initialized
with the address of variable number of type int (Refer Figure 8.1).
Note that ptr can be declared and initialized at the same time using the
following statement:
In C++, the reference operator (&) is used for two distinct purposes. When
used as a prefix to the name of a variable, it returns the address of variable and
when used as a suffix to the data type of a variable, it denotes a reference to that
variable.
Note: If the pointer is initialized with the address of a variable that is not declared earlier, the
compiler generates an error.
Self-Instructional
168 Material
8.2.2 Pointers to Objects Pointers, Virtual Functions
and Polymorphism
In addition to pointer to class members, pointer to the objects of a class can be
created. A pointer to an object of a class is known as object pointer. Object
pointers can be declared in the same way as other pointers are declared. The NOTES
syntax for declaring an object pointer is as follows:
Note that like structure pointers, object pointers can also be declared either with
the class definition or later in the program.
Program 8.1
A code segment to demonstrate pointer to data member.
Note: A pointer to the data member of a class does not contain the absolute address of the
member; rather, it contains an offset from the starting address of an object of the same class
at which that member is stored.
Self-Instructional
Material 169
Pointers, Virtual Functions For example, a pointer eptr to an object of the class emp (as defined in
and Polymorphism
Program 8.1) can be declared using either of the following ways:
NOTES
After declaration of the object pointer of a class, it needs to be initialized with the
address of any object of the same class. For example, the object pointer eptr
can be initialized with the address of object e of class emp using the following
statements:
In order to access the public members of the class emp with object pointer eptr,
the ‘->’ operator is used instead of the ‘.’ operator. For example, consider the
following statements:
In some cases, the number of objects to be created is not known until runtime. In
such cases, the objects of a class need to be created at runtime with the help of
pointer and the new operator. The new operator returns a pointer to an unnamed
object. Similarly, dynamically created objects can be deleted using the delete
operator. For example, consider the following statements:
Note: An array of objects can also be created using object pointers and memory can be
allocated to each object at runtime using the new operator. For example, the statement emp
*eptr=new emp[5] creates an array of 5 objects of the class emp.
Self-Instructional
170 Material
Program 8.2 Pointers, Virtual Functions
and Polymorphism
A program to demonstrate pointer to class object.
NOTES
In this program, two member pointers ptr and fptr pointing to emp_no
and sal_increment(), respectively, are declared. In main(), these
pointers are accessed by the object e using the ‘.*’ operator.
Note: A pointer to the private members (data or functions) of a class can be declared either
inside the class or within the friend function of that class but not in main()or in another
non-member functions.
A pointer eptr pointing to the object of the class emp is declared and
memory is allocated to the object at runtime using the new operator. Note that
the ‘->’ operator is used with the object pointer eptr to access the data member
sal. However, the ‘->*’ operator is used with eptr to access the pointers
Self-Instructional
Material 171
Pointers, Virtual Functions ptr and fptr pointing to class members emp_no and sal_increment(),
and Polymorphism
respectively.
Note: Like an object reference, object pointer can also be passed as an argument to a
function. This prevents the copying of entire object within the called function.
NOTES
8.2.3 this Pointer
The this pointer is a special pointer that contains the address of an object of a
class currently calling the member function of the class. Whenever an object of the
class calls any of its non-static member function, the address of the object (this
pointer) is passed as an implicit argument (or as a hidden argument) to it and is
available as a local variable within its body.
Note: Static member functions and the friend functions of a class cannot make use of the
this pointer.
The data members of the calling object can be accessed within the member
functions either directly using their names or indirectly using the ‘->’ operator
with the this pointer. In addition, the this pointer can be used to return the
object pointed to by it to the calling program.
Program 8.3
A program to demonstrate the this pointer.
Self-Instructional
172 Material
Pointers, Virtual Functions
and Polymorphism
NOTES
In this program, two objects e1 and e2 of type emp are created and the employee
with higher salary is displayed. Note that the statement cout<<this displays
the address of the calling object whereas the statement return(*this) returns
the contents at the address contained in this pointer, that is, the contents of the
calling object.
Note: The contents of the this pointer, that is, the memory location to which it points,
cannot be changed.
NOTES
Self-Instructional
174 Material
Pointers, Virtual Functions
and Polymorphism
NOTES
NOTES
Default operator’s works fine for built-in data types. However to use them on
user defined data types user needs to implement their own operators to operate
on user defined object types.
8.2.6 Runtime Polymorphism
Runtime polymorphism can be achieved using virtual functions. In virtual function
mechanism, any derived class function can be called using Base class pointer.
Function declared inside that particular class will be called of which object is
assigned to base class pointer.
Program 8.5
A program to demonstrate runtime polymorphism which is implemented with
inheritance and virtual functions.
Self-Instructional
176 Material
Pointers, Virtual Functions
and Polymorphism
NOTES
Virtual functions are one of the attributes of C++ that support run-time
polymorphism. A virtual function is a member function that is declared inside the
base class and its functionality can be overridden in the derived classes. When the
base class containing virtual function is inherited, the derived classes may implement
their own versions of that function. The entire function of the base class can be
Self-Instructional
Material 177
Pointers, Virtual Functions replaced by a set of new implementation in the derived class. This implies that the
and Polymorphism
base class provides a common interface and this interface can be implemented in
different ways in different derived classes. A member function can be made virtual
by prefixing its declaration with the keyword virtual in the base class. For
NOTES example, consider the following base class definition:
In addition, when a derived class that has inherited a virtual function is itself
used as a base class for another derived class, the virtual function can still be
overridden. This implies that a virtual function always remains virtual irrespective
of the number of times it is inherited.
8.3.1 Virtual Member Function Access
A virtual member function must be accessed using a pointer of base class type and
not of derived class type. However, if the function is not declared virtual and
the pointer of base class is made to point to the derived class, the function of the
base class is always executed. That is, the compiler selects a function based on
the type of pointer instead of its contents. However, if the function is declared
Self-Instructional
178 Material
virtual in the base class, the compiler selects which version of the function is Pointers, Virtual Functions
and Polymorphism
to be executed depending on the contents of the pointer. For example, consider
the following statements:
NOTES
If a virtual function is not redefined in the derived class, a call to that function
uses the function implementation defined in the base class. Moreover, like a non-
virtual member function, a virtual member function can be accessed directly in the
derived class using the scope resolution operator (::). However, in this case, the
virtual function mechanism is suppressed and the base class implementation of the
function is called.
Virtual functions permit the use of the same function call to execute the
member functions of different derived classes provided all these classes have been
derived from the same base class. Moreover, the desired function has been declared
virtual in the base class.
Program 8.6: A program to demonstrate the virtual functions
Self-Instructional
Material 179
Pointers, Virtual Functions
and Polymorphism
NOTES
Self-Instructional
180 Material
Pointers, Virtual Functions
and Polymorphism
NOTES
At the time when a virtual function is called by an object, the vptr of that
object provides the base address of the v-table for that class, which in turn provides
Self-Instructional
182 Material
the address of the function called by the object. This is how a virtual function call Pointers, Virtual Functions
and Polymorphism
is resolved at run-time and dynamic binding is achieved.
Note: Virtual tables are class-specific. There exists only one v-table for a
class irrespective of the number of virtual functions it contains.
NOTES
8.3.3 Late Binding
In case of virtual function, the compiler does not know in advance which class the
pointer of base class will point to and which version of the function will be called.
Therefore, the decision to select the function is deferred until run-time. At run-
time, the compiler selects which version of the function is to be executed depending
on the contents of the pointer. Since the function call is resolved at run-time, virtual
functions help in employing late binding or dynamic binding (that is, choosing a
function at run-time).
Pure Virtual Function
As stated earlier, if a derived class does not redefine a virtual function, the base
class implementation of virtual function is invoked. However, in some cases, either
no meaningful definition of the virtual function exists in the base class or each
derived class is required to define its own version of the virtual function. To handle
such cases, C++ provides pure virtual functions.
A virtual function that has no definition within the base class is known as
pure virtual function. A virtual function can be made pure by appending the pure
specifier ‘=0’ to its declaration in the base class. The syntax for declaring a pure
virtual function is as follows:
Self-Instructional
Material 183
Pointers, Virtual Functions
and Polymorphism
Check Your Progress
1. What is pointer?
NOTES 2. Define this pointer.
3. What is virtual function?
1. A pointer is a variable that contains the address (not the value) of another
variable or a literal.
2. The this pointer is a special pointer that contains the address of an object
of a class currently calling the member function of the class.
3. A virtual function is a member function that is declared inside the base class
and its functionality can be overridden in the derived classes.
8.5 SUMMARY
Self-Instructional
Material 185
Managing Console I/O
Operations
UNIT 9 MANAGING CONSOLE I/O
OPERATIONS
NOTES
Structure
9.0 Introduction
9.1 Objectives
9.2 Basic Concept of Streams
9.2.1 Stream Classes
9.2.2 Managing Console I/O Operations
9.2.3 C++ Console I/O Headers
9.3 Types of I/O Operations
9.3.1 Formatted I/O Operations
9.3.2 Unformatted I/O Operations
9.4 Overloading << and >> Operators for Objects
9.5 Answers to Check Your Progress Questions
9.6 Summary
9.7 Key Words
9.8 Self Assessment Questions and Exercises
9.9 Further Readings
9.0 INTRODUCTION
In this unit, you will learn about the basic concepts of streams and stream classes
related to console I/O operations. It also discusses standard streams used in every
C++ program. A program is a set of instructions that facilitates problem solving.
Every program transforms input into desired output. An input is given to a program
through standard input device, files, sensors, other programs, etc. Similarly the
output from the program is sent to standard output device, files, actuators (sending
signals to some equipment) and other programs. Since C++ is a superset of C, it
supports C-based Input/Output system. C-based I/O is powerful, extensive and
flexible; however, it does not support user-defined data types such as classes. To
handle such requirements, the C++ I/O system is used. The C++ I/O-based system
operates through streams. Streams help to handle console I/O and file I/O
operations.
9.1 OBJECTIVES
Self-Instructional
Material 187
Managing Console I/O
Operations
NOTES
Self-Instructional
Material 189
Managing Console I/O x cerr: standard error output—the standard destination for the error
Operations
messages
x clog: buffered version of cerr
NOTES Note: The stream objects cin, cout and cerr are similar to the streams stdin,
stdout and stderr, respectively in C.
9.2.3 C++ console I/O headers
To perform the console input/output operations, C++ headers are used in a
program. The console headers used in the program are listed in Table 9.2
Table 9.2 Console I/O Header Files
Self-Instructional
190 Material
treated by the compiler as Managing Console I/O
Operations
where,
NOTES
The prototype for using the extraction operator to read multiple values is as
follows:
Self-Instructional
Material 191
Managing Console I/O In this statement, the operator>>(i) function returns a reference to
Operations
the stream object, that is, cin and this returned value is used to call the next
operator function operator>>(j).
The characters extracted using an input operator can be displayed using the
NOTES
insertion operator(<<). The insertion operator (<<), also known as output
operator, is used to insert the characters into the stream. It works on two operands,
namely, stream object on its left and an expression on its right. The insertion operator
can also use manipulators (discussed later in the unit) to display the formatted
output. The prototype of the insertion operator to output data values is as follows:
where,
identifier of the
For example, consider the following statement:
treated by compiler as
where,
ostream = output stream
Self-Instructional
192 Material
Note that a pointer to other data types is written to the stream as an address. Managing Console I/O
Operations
However, because of these functions, a variable of type const char* when
sent to an output stream writes a string instead of the address stored in the pointer
variable. However, if the address in the pointer is to be displayed rather than the
string, it should be explicitly cast to void*. NOTES
Program 9.1: A program to typecast char * pointer to display the address of
the first character in the string
In this program, *pStr is a pointer of char type that displays the first
character of the null-terminated string. The pointer variable pStr displays the
string instead of the address. To display the address of the first character of the
string in the pointer p S t r , it is typecasted to v o i d * using the
static_cast<void*>(pStr) statement.
Formatting using ios class functions and flags
The data values can be formatted using ios class functions and flags. To format
the data values, the ios class defines some member functions that are inherited
by its derived classes. Like other member functions, these member functions are
also invoked using the object name and the dot operator. The standard output
stream object cout can be used to invoke these functions. The functions used to
format the data are listed in Table 9.3.
Self-Instructional
Material 193
Managing Console I/O Table 9.3 ios Class Functions
Operations
Function Description
width() changes the field width
NOTES precision() specifies floating point decimal precision
fill() defines the character, which is to used to fill the
unused space of the field
setf() stands for set flags—flags affect the way the
characters are interpreted and displayed
unsetf() clears the flags already set
width() function: The output stream displays the data value of a field.
The data value displayed occupies the space required by the field. However, the
width() function can be used to change field width. The prototype of the
width() function is as follows:
The width() function specifies the field width n and returns the previous
width of the field. The width size is usually specified before each output; otherwise,
the default width of the field is used. If the data value occupies lesser space than
the width specified using the width() function, the unused space is filled with
spaces and the data value is also right justified. However, if the data value occupies
more space than the width specified using the width() function, the field will
overrun and the data values are not truncated and also left justified. For example,
consider the following statements:
Self-Instructional
194 Material
The output of these statements is Managing Console I/O
Operations
NOTES
In these statements, though the field width is set to 2, the value of variable x
occupies 4 spaces as the value of x is not truncated. Note that the value of x is left
justified.
Note: The setting specified by width() is retained until the next output statement. Therefore,
the field width should be specified for each data item separately.
fill() function: While displaying the data values if the allotted width is
unused, it is filled with white spaces by default. However, such unused positions
can be filled with a specified character using the fill() function. This is called
padding. The fill() function remains in effect until it is reset. The prototype of
the fill() function is as follows:
char fill(char ch);
For example, consider the following statements:
The precision is set to n digits for the floating-point data values and the
previous precision value is returned. Note that the trailing zeros after the decimal
point are truncated. In order to display the trailing zeros, the showpoint flag
can be used, which is explained later in this unit. For example, consider the following
statements:
Self-Instructional
Material 195
Managing Console I/O The output of these statements is
Operations
NOTES
In these statements, precision() enables to set the precision of the
data value to 4. Note that unlike the width() function, the precision()
function remains in effect until it is reset.
Program 9.2: A program showing the use of fill(), width() and
precision() functions
Self-Instructional
196 Material
Managing Console I/O
Operations
NOTES
NOTES boolalpha boolean values are input/output using the keywords true and
false
fixed displays floating-point value in normal notation
scientific displays floating-point value in scientific notation
dec displays numeric values in decimal form
hex displays numeric values in hexadecimal form
oct displays the numeric values in octal form
internal inserts the space between the sign and the base character in
case the numeric values are padded
showbase shows the base of numeric values
showpoint displays decimal or trailing zeros
showpos displays plus sign before the positive numbers
skipws ignores white spaces while reading from the stream
flush flushes the buffer after insertion
left left justifies the output
right right justifies the output
Note that oct, dec and hex are collectively referred to as basefield.
The flags left, right and internal are collectively referred to as
adjustfield. The scientific and fixed fields are collectively referred
to as floatfield.
where,
The function returns the previous setting of the flag and turns on the new
settings of a flag. For example, consider the following statements:
Self-Instructional
198 Material
In these statements, the width() function sets the field width to 15. Managing Console I/O
Operations
Thus, the width for the text Rachna Sharma is set to 15. The text is right-
aligned and the unused space is filled with character (*) using the fill()function.
However, setf(ios::left) enables to change the text alignment to the
left. NOTES
The flags set by the setf() function can also be cleared using the
unsetf() function. The prototype of unsetf() function is as follows:
The function turns off the flags specified by arg2 and turns on the flags
specified by arg1. In case arg1 contains other flags, then flags specified by
arg2 are affected. The setf() with two arguments is used while setting the
number base, justification and float field. For example, consider the following
statements:
In these statements, three flags, namely, dec, oct, hex are set on. These
flags display integer x in decimal, octal and hexadecimal numbers. To unset these
flags and set only oct flag, the following statements are used:
Self-Instructional
Material 199
Managing Console I/O Note that the unsetf() statements can also be combined using the |
Operations
operator.
NOTES
A single unsetf() statement is used to clear all the flags. The | operator
enables to combine dec, oct and hex flags in a single unsetf() statement.
The setf() function then turns on oct flag. Instead of using unsetf() and
setf() functions, the shorthand notation of setf() can be used. For example,
consider the following statement:
As stated earlier, the flags dec, oct and hex belong to group
basefield and hence, this statement can be written as follows:
Self-Instructional
200 Material
Managing Console I/O
Operations
NOTES
In this program, setf() is used to set the various flags such as showpos,
showpoint, left and internal. The showpos displays leading plus
sign for the data values. The flag showpoint causes decimal point and trailing
zeros to be displayed for all floating-point output. The flag left is used to align
the field princ to the left. The fields rate and time are right-aligned. The
flags set for field si is internal, ios::adjustfield. Therefore,
the space is inserted between sign (+) and the base of field si.
One of the important flags set by the setf() function is showpoint.
The flag showpoint enables to display the zeros after decimal point. Note
that zeros after decimal points are truncated while using precision(). For
example, consider the following statements:
Self-Instructional
Material 201
Managing Console I/O
Operations
Note that manipulators can also be concatenated, which implies that several
manipulators can be used in a single cout statement. The different manipulators
are explained here.
setprecision(int n) function: setprecision(int n)
is used to set the number of digits to be printed for the floating-point data values.
It has two forms, namely, fixed and scientific. Fixed enables to display floating-
point number in the fixed notation. Scientific enables to display floating-point
numbers in the scientific notation. For example, consider the following statements:
Self-Instructional
202 Material
Managing Console I/O
Operations
In these statements, setw(10) changes the width for the data value to 10. The
numbers are, by default, right-aligned filled with white spaces on the left.
setfill(char ch) function: The setfill()function fills the
unused space of field width with specified characters. For example, consider the
following statements:
Self-Instructional
Material 203
Managing Console I/O The output of these statements is
Operations
Self-Instructional
204 Material
Managing Console I/O
Operations
NOTES
In this program, setfill(), setw(), setprecision(),
setiosflags(), resetiosflags() and endl manipulators are used.
The manipulator setiosflags(ios::left) is used to left-align the field,
which is reset using resetiosflags(ios::left). Therefore, the fields
Number and Inverse are left-aligned, whereas Cumulative sum is
right-aligned.
Difference between ios class functions and manipulators
There is a difference between the ios class member functions and manipulators.
The ios class functions return a reference of previous format state, whereas
manipulators do not return any. For example, consider the following statements:
In these statements, the fill() member function returns the previous fill
character ‘*’ and sets ‘#’ as the new fill character. However, manipulator
setfill() does not return anything.
User-defined manipulators
User-defined manipulators or custom manipulators are created by the programmers.
These manipulators facilitate to combine several I/O operations. User-defined
manipulators are also required when the I/O operations are to be performed on a
non-standard device. They are categorized into the ones accepting arguments and
others that do not. The prototype to create a stream manipulator is as follows:
Self-Instructional
Material 205
Managing Console I/O
Operations
NOTES
}
where,
Self-Instructional
206 Material
In this program, the manipulators NumOct and NumHex are created. Managing Console I/O
Operations
NumOct converts a decimal number to an octal number and NumHex converts
a decimal number into a hexadecimal number. Note that the showbase flag
enables to display the base octal number (0) and hexadecimal numbers (0x).
NOTES
Note that the custom manipulators are output manipulators; however, input
manipulators can also be created. The prototype to create a user-defined input
manipulator is as follows:
The input manipulator gets a reference to the stream for which it is called.
The reference to the stream in turn is returned by the manipulator.
Program 9.6: A program showing user-defined input manipulators
Self-Instructional
Material 207
Managing Console I/O
Operations
NOTES
Self-Instructional
208 Material
Managing Console I/O
Operations
NOTES
A
In this program, the cin.get() function extracts the character A from the
stream and returns its integer value; however, when assigned to char ch, it is
implicitly typecasted into a character. Hence, the statement cout<<ch displays
the character A. Program 9.7 can be rewritten as shown in Program 9.8 to
display the integer value of character.
Program 9.8: A program showing the return type of get() function
This function returns a reference to the stream object to facilitate the calling
of this function from other member functions.
Note that the character read using the get() function is displayed using
the extraction operator (in Programs 9.7 and 9.8). However, it can also be
displayed using the put() function. put() is a member function of the ostream
Self-Instructional
Material 209
Managing Console I/O class that inserts the single character into the stream and returns the reference to
Operations
that stream object. The prototype to display a single character using the put()
function is as follows:
NOTES
Program 9.9: A program to accept and display a character using get() and
put() functions
In this program, cin.get(ch) reads the single character from the stream and
put(ch) displays the character. Note that the newline character is the terminating
character and is left in the stream. This character can also be displayed using the
cout statement. For example, consider the following statements:
Self-Instructional
210 Material
Managing Console I/O
Operations
The cout statement does not display any character on the screen, rather it
moves the cursor to the next line.
NOTES
getline() function: The getline() function is also a member
function of the istream class that reads the character until a specified number of
characters are read or a newline character or end-of-file is encountered. Unlike
the get()function which leaves the terminating character (delimiter) in the stream,
the getline() function removes the delimiter from the stream in order to
facilitate reading of the next character. The prototypes of getline() function
are as follows:
Self-Instructional
212 Material
Managing Console I/O
Operations
In this program, the read() function is used to extract the characters NOTES
from the stream and the write() function is used to insert characters into the
stream. The gcount() function is used to count the number of characters in the
last input.
Note that write() does not stop displaying the characters automatically
when the null character is encountered. If streamsize is greater than the
number of characters read, then it displays garbage values. For example, consider
the following statements:
Self-Instructional
Material 213
Managing Console I/O Similarly, the syntax for overloading the << operator is as follows:
Operations
Program 9.12: A program to demonstrate overloading of the << and >> operators
NOTES for objects
Self-Instructional
214 Material
Managing Console I/O
Operations
}
The output of the program is NOTES
9.6 SUMMARY
x A program written in C++ supports two types of I/O (Input/Output) systems,
namely, C-based I/O system and C++ I/O system. C-based I/O is powerful,
extensive and flexible; however, it does not support user-defined data types
such as classes. It is provided in C++ to facilitate compatibility. C++ I/O-
based system operates through streams. The C++ I/O system is capable of
working with a variety of devices such as terminals, disks, tape drives, etc.
The common interface independent of any of these physical devices being
used is known as streams.
x A stream refers to the flow of data in the form of a sequence of bytes. A
stream is an interface that acts as the source and destination for the input
and output data, respectively.
Self-Instructional
Material 215
Managing Console I/O x Streams that help to consume data from various sources, namely, keyboard,
Operations
mouse, storage devices, etc. in order to supply it to the program are called
input streams. Streams also receive data from the program and direct it to
the physical devices or other programs. Such streams are called output
NOTES streams.
x The C++ I/O library comprises a hierarchy of classes used to define various
streams that help to handle the console I/O and file I/O operations. Such
classes are known as stream classes. Streams facilitate the data to be passed
in and out of a medium such as the console or a file.
x The stream class istream defines the behaviour of the extraction
operator (>>), which is used to extract data from various sources
such as keyboard. The istream supports reading the basic types of
data from various input streams. The stream class ostream, which defines
the insertion operator(<<) is used to direct the output to
various destinations such as screen.
x Streams enable to perform two types of I/O operations, namely, formatted
I/O and unformatted I/O. The I/O operations in which character translation
occurs is called formatted I/O operations. The extraction(<<) and
insertion(>>) operators handle I/O formatting implicitly.
x The data values can also be formatted (using ios class format functions,
special functions called manipulators and user defined manipulators)
explicitly. The extraction operator (>>) also interpreted as
operator>>() function is used to extract the characters from the stream.
x The extraction operator is also called the input operator. The
operator>>() function formats the data input through an input stream,
which implies that it extracts characters from the stream and assigns to the
second operand after ignoring all white spaces as operator>>() cannot
read white spaces.
x The Insertion operator (<<) also known as output operator
is used to insert the characters into the stream. The insertion operator is
also used to display a character and null-terminated string.
x Unformatted I/O operations are the functions that do not exclude white
spaces. The white space characters are also read and stored. It implies that
no character interpretation takes place.
(b) #include<iostream>
NOTES
Self-Instructional
218 Material
Introduction to Files
BLOCK IV
WORKING WITH FILES
NOTES
UNIT 10 INTRODUCTION TO FILES
Structure
10.0 Introduction
10.1 Objectives
10.2 File Streams
10.2.1 Classes for File Stream Operations
10.3 Opening and Closing a File
10.3.1 Opening a File using the Constructor
10.3.2 Opening a File using the open() Function
10.3.3 File Modes
10.3.4 Closing a File
10.4 Detecting End-of-file
10.5 Answers to Check Your Progress Questions
10.6 Summary
10.7 Key Words
10.8 Self Assessment Questions and Exercises
10.9 Further Readings
10.0 INTRODUCTION
In the previous unit, you learnt about console I/O operations. This unit discusses
various file streams classes and the other features related to files like handling
errors encountered during the file input–output operations and command-line
arguments. Most of the real-life applications require a large amount of input and
output data to be handled that is difficult to manage using the commonly used
console input/output (I/O) devices like keyboard and screen. Moreover, the output
obtained using the console I/O operation is not permanent and is lost as soon as
the program terminates. This necessitates the requirement of some devices, such
as a hard disk, magnetic tape or a floppy disk, to store voluminous data
permanently. Data is stored in these devices in the form of files (also known as
disk files).
A file is a collection of related data stored on some storage device. Data
stored in a data file is permanent and can easily be accessed as and when required.
Moreover, data stored in a file by one program can be accessed or modified by
various programs according to their requirements.
In C++, the functionality provided by the standard library for file I/O
operations, like console I/O, also involve the use of streams.
Self-Instructional
Material 219
Introduction to Files
10.1 OBJECTIVES
A file stream refers to the flow of data between a program and files. Depending
on the flow of data from a file or to a file, a stream can be classified into two types
(as shown in Figure 10.1).
x Input stream: It reads the data from the file and supplies it to the program.
x Output stream: It receives data from the program and writes it to the file.
There are two modes by which data can be transferred to and from streams:
text mode and binary mode. A file, which is opened in the text mode, is known
as text file, whereas a file opened in the binary mode is known as binary file.
The main aspects where a text file and a binary file differ from one another are as
follows:
x Storage of numbers: A text file stores data as a sequence of characters
while the binary file stores data as a sequence of bytes. For example, if a
number, say 12345, is stored in the text format, it occupies five bytes of
memory. However, if it is stored in the binary format, it takes two bytes of
memory (as shown in Figure 10.2). Hence, binary files occupy less memory.
Moreover, since data is stored in the same format as in the internal memory,
saving and accessing the data from binary files is faster than text files.
Self-Instructional
220 Material
x Handling newline character: In text files, some character translations Introduction to Files
take place while data is being read from or written to the file. For example,
newline character is expanded into carriage return/line feed
combination before being written to the disk. Hence, there is a possibility
that the number of characters written (or read) may not be the same as NOTES
that in the file. While in binary files, no such character translation takes
place. Thus, the number of bytes read (or written) is same as that in the
file.
x Representation of end of file: In text files, a special character whose
ASCII value is 26 represents the end of file. While in binary files, there is
no such special character to detect the end of file. The end of file is
determined by keeping track of the number of characters present in the
file.
Self-Instructional
Material 221
Introduction to Files
NOTES
Self-Instructional
222 Material
Introduction to Files
10.3 OPENING AND CLOSING A FILE
where,
= the name of the stream class whose object is to be
created
= the object name, which can be any valid identifier
= the name of the file to be opened
For example, a file named can be opened for input using
constructor as shown in the following statement:
A single file can also be opened for both reading and writing with the help of
the following statement:
Note: When a file is opened as an output file, the operating system either
creates a new file (if the file does not exist) or overwrites the contents of the
file (if the file already exists).
Self-Instructional
Material 223
Introduction to Files The constructor of a stream class can link only a single file to a stream.
Thus, in a program using multiple files, a separate stream for each file is required.
For example, consider the following statements:
NOTES
Hence, opening file using constructor is useful when only one file is to be
used with the stream. However, to manage multiple files using one stream (as
required in case of sequential processing of files), the method is used.
10.3.2 Opening a File using the open() Function
The function , which is a member function of the
class, has the same parameter as the constructor of the stream class. However,
unlike constructors, the creation of stream object and its linking with a particular
file using the function are performed in separate statements. The syntax
for opening a file using the function is as follows:
This function checks the value of the associated stream and returns true if
the stream is linked to open file; otherwise, it returns false.
Self-Instructional
224 Material
10.3.3 File Modes Introduction to Files
The file has been opened so far by specifying only one argument (that is, file name)
in both the constructor and functions. However, another argument that
specifies the file mode can also be included in both the functions. The file mode NOTES
describes how a file is to be used, that is, to read from it, to write to it, to append
to it and so on. The general form of the function with two arguments is
as follows:
where,
= an enumeration defined in the class that specifies how a file
is opened.
The various modes that a file can have are listed in Table 10.1.
Table 10.1 File Modes for Opening a File
Mode Description
ios::in opens a file for reading
ios::out opens a file for writing
ios::trunc deletes the contents of the file if it already exists, that
is, truncates the file to zero length
ios::app appends the data at the end of the file only
ios::ate moves to the end of file on opening, however permits
addition as well as modification of data anywhere in
the file
ios::binary opens the file in the binary mode
ios::nocreate open fails if the file does not exist—does not create a
new file
ios::noreplace open fails if the file already exists—does not replace
the existing file with a new one
Two or more file modes can be combined using the bitwise OR operator
( ) between them shown as follows:
where, class.
The prototype of both the constructor and functions contain default
mode for each type of stream. The default mode for the class is
, for class is and for class is
. Thus, in the absence of this argument, the default value
is provided. For example, consider the following statements:
Equivalent statements
Self-Instructional
Material 225
Introduction to Files where, is an object of class.
Note: Depending on the compiler, the function may or may not provide the default
mode for class. Hence, it needs to be specified explicitly.
The following points must always be kept in mind while opening a file:
NOTES
x A file name can include a path specifier. However, if the path is not
specified, the compiler assumes the file to be present in the current
directory.
x Opening a file in the mode also opens it in the
mode. Hence, an object of the class is directly opened in the
mode by default.
x In both and modes, a file is created by the
specified name, if it does not exist.
x The mode can be used with the files capable for output only.
x By default, all the files are opened in the text mode. Hence, to open a file
in the binary mode, the file mode must be specified
shown as follows:
For example, a stream object, say , can be closed with the help
of the following statement:
Note that closing a file only disconnects the file from the stream that is
linked to it. However, the stream object still exists and can be used again for
associating with the same or another file. For example, consider the following
statements:
Self-Instructional
226 Material
Note: If a single stream is used with multiple files using the function, the file Introduction to Files
needs to be closed explicitly.
Here, the function returns zero as long as the end of file is not
reached. As soon as the end of file is reached, it evaluates to a non-zero value and
the loop terminates.
The end-of-file condition can also be detected by testing the stream object
directly shown as follows:
In this loop, the value of file stream object is tested for any error condition
including the end-of-file condition. As soon as the end of file is reached or any
other error occurs, object returns zero and the loop terminates.
Note that the stream object returns a pointer value. However, returning
address is of no importance except that the value can be tested for a zero or non-
zero value.
10.6 SUMMARY
x A file stream refers to the flow of data between a program and files.
x When a file is opened using the constructor of a stream class, the file name
is passed to it as an argument. The constructor initializes the stream object
with the file name passed to it.
x A file name can include a path specifier. However, if the path is not specified,
the compiler assumes the file to be present in the current directory.
x When a stream object goes out of scope, the destructor of the object is
invoked implicitly, which closes the associated file automatically.
x A file, which is opened in the text mode, is known as text file, whereas a file
opened in the binary mode is known as binary file.
x Data stored in a data file is permanent and can easily be accessed as and
when required.
Self-Instructional
228 Material
Long Answer Questions Introduction to Files
1. Describe the various modes by which data can be transferred to and from
streams.
2. How is the end of file represented in text and binary files? NOTES
3. Explain the stream classes commonly used for disk I/O operations.
4. What is the difference between opening a file using constructor function and
open() function. Which method is preferred to handle multiple files using
one stream and why?
5. What do the modes ios::nocreate and ios::noreplace ensure when they are
used for opening files?
6. What is the difference between the ios::ate and ios::app mode?
Self-Instructional
Material 229
File Pointers and their
Manipulations
UNIT 11 FILE POINTERS AND
THEIR MANIPULATIONS
NOTES
Structure
11.0 Introduction
11.1 Objectives
11.2 File Input/Output with Stream Class
11.2.1 Sequential Input and Output Operations
11.3 File Pointers and their Manipulations
11.3.1 Specifying the Position
11.3.2 Specifying the Offset
11.4 Updating a File: Random Access
11.5 Error Handling During file Operations
11.6 Command-line Arguments
11.7 Answers to Check Your Progress Questions
11.8 Summary
11.9 Key Words
11.10 Self Assessment Questions and Exercises
11.11 Further Readings
11.0 INTRODUCTION
In this unit, you will learn about the file pointer and their manipulators. In C++,
every file is associated with two file pointers, namely, get pointer (input pointer)
and put pointer (output pointer). These file pointers are not the usual C++ pointers
as the name implies. They simply represent integer values that specify the current
position (byte number) in the file from where writing and reading will start. The get
pointer specifies the position from where the next read operation will start and the
put pointer specifies the position from where the next write operation will start.
11.1 OBJECTIVES
Self-Instructional
230 Material
File Pointers and their
11.2 FILE INPUT/OUTPUT WITH STREAM CLASS Manipulations
Once a file is opened, it can be used for reading or writing text as well as raw
(binary) data through various I/O operations provided by the stream classes. As NOTES
the stream classes are device-independent, the same I/O operations, formatted as
well as unformatted I/O used with console I/O, can be used with files.
In the formatted I/O operations, various types of data can be read from or
written to the stream using the insertion and extraction operators. Reading and
writing through the formatted I/O operations is easy to implement and appropriate
in case of text files as data is converted to a character representation. However, to
handle a large amount of data, the unformatted I/O operations like , ,
, and functions are used. The functions
and are used to write and read, respectively, a single character at a time
from stream. The function can read multiple characters (string)
from stream The functions and can read and write the
entire structure (array, structure variable or a class object), respectively, in one I/
O operation.
11.2.1 Sequential Input and Output Operations
In this section, we will discuss how a file can be read or write sequentially using the
formatted and unformatted I/O operations.
Formatted I/O: using and
The ) and the ) have been used
with the standard stream objects and , respectively, in earlier units.
However, these operators and are overloaded in the classes
and , respectively, to work in the same way with file stream objects.
The only difference is that instead of using and , a stream object
linked to a file is used.
Note that the operators and can be used in the text as well as binary
mode. However, generally they are used in the text mode to ensure that the data is
displayed correctly.
Program 11.1: A program to demonstrate writing data to a file using the extraction
operator
Self-Instructional
Material 231
File Pointers and their
Manipulations
NOTES
Self-Instructional
232 Material
File Pointers and their
Manipulations
NOTES
Self-Instructional
Material 233
File Pointers and their Program 11.3: A program to demonstrate the use of
Manipulations
NOTES
This function reads characters from the input stream and puts them in an array
pointed to by until either characters have been read, the character
specified by is found or the end of file is encountered. When the
character is encountered in the input stream, it is extracted; however, it is not put
into .
Program 11.4: A program to demonstrate the use of
Self-Instructional
Material 235
File Pointers and their
Manipulations
NOTES
where,
= a type defined as a form of integer to hold the
largest number of characters that can be transferred in
one I/O operation
Self-Instructional
236 Material
The functions read and write specified number File Pointers and their
Manipulations
of characters (say, ) from or to the character array pointed to by ,
respectively. However, to read and write from an array that is not of type ,
it must be type cast to pointer to inside the calls to and
as shown in Program 11.5. NOTES
The number of characters that have been read by the last binary input
operation can be determined by using the function . The prototype
of is as follows:
Note: The data written to a file using write() can only be read accurately
using read().
Program 11.5: A program to demonstrate writing and reading an object to a file
using and , respectively
Self-Instructional
Material 237
File Pointers and their
Manipulations
NOTES
In this program, the data of class is written to and read from the file
using the and functions, respectively.
These functions take two arguments: the address of the object and the
size of the object in bytes. The size of object is determined using the
operator and the address of the object is type cast to pointer to char in both the
and functions.
When two different programs are used for writing and reading object to a
file using functions and , respectively, the data must be of
the same format, that is, the type and order of the data members must be the same
to make them work accurately. However, any inconsistency in the member functions
has no effect on the working of a program, as the member functions are not written
to the file along with data of object.
Note that any file, whether it contains formatted text or binary data, can be
opened in either the text or binary mode. However, if binary operations are
performed on a file, it must be opened in the binary mode to prevent the occurrence
of character translations, which may negate the purpose of binary file operations.
I/O with multiple objects
In earlier discussion, the functions and were used to read
and write an object, respectively. However, using these functions, as many as
objects can be read or written.
Program 11.6: A program to demonstrate writing and reading multiple objects to
a file using , respectively
Self-Instructional
238 Material
File Pointers and their
Manipulations
NOTES
Self-Instructional
Material 239
File Pointers and their
Manipulations
Self-Instructional
240 Material
File Pointers and their
11.3 FILE POINTERS AND THEIR MANIPULATIONS Manipulations
In C++, every file is associated with two file pointers, namely, get pointer (input
pointer) and put pointer (output pointer). These file pointers are not the usual C++ NOTES
pointers as the name implies. They simply represent integer values that specify the
current position (byte number) in the file from where writing and reading will start.
The get pointer specifies the position from where the next read operation
will start and the put pointer specifies the position from where the next write
operation will start. When the file is opened in the input mode, the get pointer is
placed at the beginning of the file. Similarly, when the file is opened in the output
mode, the existing data is deleted and the put pointer is placed at the beginning of
the file. However, if an existing file is opened in the append mode using
mode specifier, the put pointer is moved to the end of the file so that writing can
start after the end of the existing data. The default position of the file pointers is
shown in Figure 11.1.
input mode F I L E P O I N T E R S
get pointer
output mode
F i L E P O I N T E R S
put pointer
append mode F I L E P O I N T E R S
put pointer
Note that each time a read or write operation is performed, the appropriate
pointer is automatically advanced sequentially in the file. However, in some cases
like adding a record between the existing records or modifying the existing records,
a file is required to be read from or written to any other position rather than its
default position. In such cases, the file pointers must be moved to the desired
location explicitly by the programmer. This section discusses how file pointers are
manipulated to move to the desired position in a file.
11.3.1 Specifying the Position
The manipulation of the pointers can be accomplished through the functions, namely,
, , and provided by the file stream
classes. The functions and belong to the
class, whereas the functions and belong to the
class. The description of these functions is given in Table 11.1.
Self-Instructional
Material 241
File Pointers and their Table 11.1 Functions to Manipulate File Pointers
Manipulations
Functions Prototype Purpose
tellg() pos_type tellg() returns the current position of the
get pointer
NOTES
tellp() pos_type tellp() returns the current position of the
put pointer
seekg() ifstream& moves the get pointer to the
seekg(pos_type pos) specified location pos from the
beginning of the file where pos
is a positive integer value
seekp() ofstream moves the put pointer to the
&seekp(pos_type pos) specified location pos from the
beginning of the file where pos
is a positive integer value
Here, the first statement moves the put pointer to the end of the file as
is opened in the append mode. The second statement returns the
number of bytes in the file.
To understand the concept of the function , consider the following
statements:
The second statement sets the get pointer at the byte number 5, that is
th
the 6 byte in the file. Note that the bytes in a file are numbered from zero as
shown in Figure 11.2.
Value Description
ios::beg offset is relative to the first character in the file or
the beginning of the file
ios::cur offset is relative to the current position of file
pointer
ios::end offset is relative to the last character in the file or
end of the file
The offset value relative to the positions (mentioned in Table 11.2) can be
set by using the overloaded version of or that accepts
two arguments as shown in the following prototypes:
where,
NOTES
This statement moves the get pointer to byte number 5 from the beginning
of the file and reads data from that position into where is a variable
on the contents of the file.
Similarly, the function can be used to move the put pointer where
the next write operation is to be performed. However, the write operation will
overwrite the data starting from that position.
Note: The offset value in and must be positive relative to
and negative relative to .
Randomly accessing a file means directly reaching the desired record/object in the
file. To access an object in a file directly, the put pointer is placed at the beginning
of the object by skipping number of
bytes from the beginning of the file. Once the put pointer is placed at the appropriate
object number, the object can be modified. Note that an object can be accessed
directly only if the file consists of similar objects, that is, objects of equal size. The
size of each object can be determined using the operator shown as
follows:.
where, provides the byte number of the first byte of the nth object
and the file pointer can be moved to this position (byte number) by using functions
or as discussed earlier.
The total number of objects in a file can also be obtained by using the
following statement:
OPERATIONS
While performing file operations in the programs, some errors may occur. The file NOTES
operations performed so far in this unit do not deal with any erroneous situation.
However, it is important to identify the occurrence of errors as they can produce
undesirable results. Some of the I/O operations that can cause an error are as
follows:
x An attempt to open a non-existing file for reading
x Using an existing file name for a new file
x Using an invalid file name
x An attempt to perform an invalid operation such as reading beyond the end
of file
x An attempt to write data to a file when there is no space in the disk for data
to be stored
x An attempt to perform an operation on a file not opened for that purpose
In C++, the status information of each I/O operation is maintained by the system.
The current state of the I/O system is stored in a status byte that contains several
bits called error flags. These bits represent the various error states. The position of
these bits is shown in Figure 11.3 and the meaning of the bits is explained in Table
11.4.
Self-Instructional
Material 245
File Pointers and their The status of an error can be determined in two ways, which are as follows:
Manipulations
x By calling the function: The function is a
member function of the class, which returns the current value of
the status byte. This function returns goodbit if no error is encountered;
NOTES otherwise, an error flag corresponding to the particular error is set.
Function Description
int bad() This function returns a non-zero value if
ios::badbit is set; otherwise, it returns 0.
int eof() This function returns a non-zero value if
ios::eofbit is set; otherwise, it returns 0.
int fail() This function returns a non-zero value if
ios::failbit or ios::badbit is set;
otherwise, it returns 0.
int good() This function returns a non-zero value if
ios::goodbit is set; otherwise, it returns
0.
Self-Instructional
246 Material
The output of the program is File Pointers and their
Manipulations
NOTES
This statement resets the specified . However, all the error status
bits can be reset to zero by using the function without arguments as
follows:
Self-Instructional
Material 247
File Pointers and their
Manipulations
NOTES
Self-Instructional
248 Material
File Pointers and their
Manipulations
NOTES
First run
Second run
Self-Instructional
Material 249
File Pointers and their
Manipulations
Check Your Progress
3. How will you access an object in a file directly?
NOTES 4. What will bad () function returns?
1. The get pointer specifies the position from where the next read operation
will start.
2. tellg () function returns the current position of the get pointer.
3. To access an object in a file directly, the put pointer is placed at the beginning
of the object by skipping (object_no-1)*object_size number of bytes from
the beginning of the file.
4. bad () function returns a non-zero value if ios::badbit is set; otherwise, it
returns 0.
11.8 SUMMARY
x Once a file is opened, it can be used for reading or writing text as well as
raw (binary) data through various I/O operations provided by the stream
classes.
x The insertion operator ( ) and the extraction operator ( ) have been used
with the standard stream objects and , respectively, in earlier units.
x The functions and , which are the member functions of classes and ,
respectively, are used to write and read a single character at a time from the
linked stream.
x The get pointer specifies the position from where the next read operation
will start and the put pointer specifies the position from where the next write
operation will start.
x Randomly accessing a file means directly reaching the desired record/object
in the file.
x The arguments can be passed to the program while invoking it from the
command prompt. They are usually used to pass the name of data file to an
application.
x An attempt to write data to a file when there is no space in the disk for data
to be stored
Self-Instructional
250 Material
File Pointers and their
11.9 KEY WORDS Manipulations
x File Stream: It refers to the flow of data between a program and the files.
x Input Stream: It reads the data from the file and supplies it to the program. NOTES
x Output Stream: It receives data from the program and writes it to the file.
Self-Instructional
Material 251
Templates
BLOCK V
TEMPLATES AND EXCEPTION HANDLING
NOTES
UNIT 12 TEMPLATES
Structure
12.0 Introduction
12.1 Objectives
12.2 Function Templates
12.2.1 Defining a Function Template
12.2.2 Calling Function Templates
12.2.3 Function Template with Multiple Parameters/Arguments
12.2.4 Function Templates with Non-type Parameters/User Defined Template
12.2.5 Applicability of Function Templates
12.2.6 Restrictions of Using Function Templates
12.3 Answers to Check Your Progress Questions
12.4 Summary
12.5 Key Words
12.6 Self Assessment Questions and Exercises
12.7 Further Readings
12.0 INTRODUCTION
Templates enable users to define a generic function or a generic class that operates
on various data types, instead of creating a separate function or a class for each
type. Templates are also known as generics or parameterized types. C++ template
mechanism allows a generic type to be passed as a parameter in the definition of
a function or a class so that they can work with different types of data. Such
approach of writing programs is known as generic programming. The main
advantage of using a template is that it reduces the source code size and also
increases code flexibility.
When templates are used with functions, they are known as function
templates and when they are used with classes, they are known as class templates.
12.1 OBJECTIVES
While writing overloaded functions, there may be a situation when the same code
has to be written repeatedly for different types of data. For example, to add two NOTES
integer and floating-point numbers, two separate functions have to be created for
each of the data type.
Program 12.1: Overloaded functions to add two numbers of int and float types
int sum(int x,int y)
{
return x+y;
}
float sum(float x,float y)
{
return x+y;
}
In this program, two overloaded functions sum() with different data types
are defined. The first function adds two numbers of type int and the second
function adds two numbers of type float. If the need arises to add two numbers
of other data types, such as long, double, etc., then more functions have to
be defined. This makes the program very lengthy and difficult to maintain. In such
a situation, function templates can be used.
A function template, also known as a generic function, defines a group or
a family of functions having the same functionality but operating on different data
types. While using function templates, only one function signature needs to be
defined and the compiler automatically generates the required functions for handling
the individual data types.
12.2.1 Defining a Function Template
The definition of templates is similar to the definition of ordinary functions. The
only difference is that it is prefixed by the statement template<class T>
and is known as template statement. It informs the compiler that a template is
being declared. When a template is defined, it does not actually define a function
rather it provides a blueprint or a syntactical skeleton for generating many functions.
The compiler uses this blueprint to automatically generate a new member of the
family of functions when it is required first.
The syntax to define a function template is
Self-Instructional
Material 253
Templates where,
template = C++ keyword
class = C++ keyword that specifies that the parameter T can be either
NOTES built-in data type or user-defined data type
T = generic or arbitrary type—a type that has not yet been specified but
can be one of the built-in data types or a user-defined data type
function_name = name of the function
parameter_list = list of arguments of type T or any other built-in
data type
return_type = return type of the function
The letter T in template definition is called template argument or type
parameter. It is a placeholder name for the data type used by the function. Note
that it is not a keyword and hence, any valid identifier, such as mytype,
newtype, etc., can also be used.
Note: The keyword typename can also be used instead of the keyword class in template
definition.
Like ordinary functions, a function template can be defined either before or
after main(). If it is defined before main(), it need not to be declared
separately. However, if it is defined after main(), its declaration is necessary
before main(). Note that the template statement must be specified in both the
declaration and definition of function template. To understand the concept of
declaring and defining a function template, consider these statements.
Note: The function template results in the creation of a set of overloaded functions, one for
each data type.
Self-Instructional
254 Material
When the function template is called, the data type T is dynamically Templates
determined by the compiler according to the parameter passed and replaced with
actual data type. For example, consider the function template sum() created
earlier. When the parameters of type int are passed, the compiler generates
sum() function compatible for int data type and if the parameters of type NOTES
double are passed, it generates the function compatible for double data
type and so on.
Note: Since T can be replaced by any data type at the time of calling of function templates,
the parameters of types T are not type-checked at compile-time. Moreover, no implicit type
conversions are applied to these arguments.
Program 12.2: A program to demonstrate the concept of calling a function
template
}
The output of the program is
Sum(234,345)= 579
Sum(34.8,58.2)= 93
In this program, a function template sum() is created and is called two
times in main() to add two numbers of type int and double. Note that the
compiler automatically generates appropriate template functions for data type int
and double using the function template. This is called implicit instantiation.
However, a function template can also be instantiated by explicitly specifying
the data type while calling the function template. This is known as explicit
instantiation. To understand this concept, consider these statements.
cout<<“Sum(234,345)=”<<sum<int>(234,345);
cout<<“\nSum(34.8,58.2)=”<<sum<float>(34.8,58.2);
Self-Instructional
Material 255
Templates In these statements, the function template sum() is called by explicitly
specifying the type between angular brackets < >. This method of instantiation
also produces the same result.
Note: If the function template is called more than once with the same data type, the
NOTES compiler generates the specific version of that function only once.
Self-Instructional
256 Material
Templates
NOTES
}
The output of the program is
Max(89,56.8)is 89
Max(56.8,5688.78)is 5688.78
Max(89,5688.78)is 5688.78
In this program, the function template max() accepts two parameters of
different types and returns an object of type T2. The function is called three times
with different parameters. Thus, the compiler generates three instances of max(),
first with int and float data types, second with float and double and
third with int and double data types. This is an example of implicit instantiation.
However, it can also be instantiated by explicitly specifying the types between
angular brackets < > as given in these statements.
Self-Instructional
Material 257
Templates
}
If any other data type, such as float or double is passed, a compile-
time error is generated. For example, consider this statement.
NOTES
template<class T, float n> //invalid, compile-time
error
The function template is invoked by explicitly specifying the non-type
template parameters between the angular brackets. For example, consider these
calls to the function template display().
display<double,4>(5.4); //int value 4
is specified
display<char,2>(‘r’); //int value 2 is
specified
Here, the function template display() is called twice. In the first call,
the template parameter T is replaced with double and in the second call, T is
replaced with char. The actual values (double and char in this case) are
passed as parameters. Note that the non-type template parameters specified within
the angular brackets can only be passed as a constant expression and not variables.
For example, consider these statements.
Self-Instructional
258 Material
Templates
NOTES
}
The output of the program is
Self-Instructional
260 Material
Templates
NOTES
}
The output of the program is
The sorted array is
45 56 78 90 100
The sorted array is
4.6 8.8 9.1 12.4
The sorted array is
a d e m o p x z
In this program, selection() is a function template that sorts a single-
dimensional array of any data type using selection sort. This function accepts two
parameters, one is non-type parameter (int) and another is an array of type T.
In addition to this, another function template display() is defined that displays
a single-dimensional array of any type. It also accepts an additional argument of
type int.
12.2.6 Restrictions of Using Function Templates
Though templates are one of the most useful features of C++, they have certain
restrictions. As discussed earlier, all the overloaded functions having the same
functionality but handling different data types can be replaced by a function template.
However, the overloaded functions having different functionalities cannot be replaced
with a single function template, as the function template must perform the same
general actions for all the data types.
To understand this concept, consider these overloaded functions.
12.4 SUMMARY
Self-Instructional
262 Material
Templates
12.5 KEY WORDS
Self-Instructional
Material 263
Exception Handling
13.0 INTRODUCTION
In this unit‚ you will learn about the exception handling mechanism. Writing error-
free programs is the main objective of programmers. However, whenever a program
is written for the first time, it usually contains errors. These errors are classified
mainly into three types: compile-time errors, logical errors and run-time errors.
The compile-time errors and logical errors can be detected and removed by
exhaustive testing and debugging. However, run-time errors are difficult to detect
and trap. The run-time errors are usually referred to as exceptions.
An exception is an unexpected event that occurs during the execution of a
program and alters the normal flow of the program or terminates the program
abnormally. The errors that can cause exceptions can range from simple
programming errors, such as opening an invalid file for reading, invalid array index,
etc., to serious errors, such as running out of memory.
13.1 OBJECTIVES
C++ exception handling mechanism mainly uses three keywords, try, throw
and catch. A set of statements that needs to be monitored for the exceptions is
contained in the try block. The try block is surrounded by curly braces and prefixed
Self-Instructional
264 Material
by the keyword try. Whenever an exception occurs within the try block, it is Exception Handling
thrown using the throw statement. This passes the control to the catch block
which handles the exception appropriately (as shown in Figure 13.1). The throw
statement and the catch block are prefixed by the keywords throw and catch,
respectively. NOTES
The catch block is also called the exception handler and it must immediately
follow the try block that throws an exception.
The syntax to define try-throw-catch block is
}
The output of the program is
First run
Second run
In this program, an ASCII value entered by the user is checked for the
exception. That is, if the user enters an ASCII value between 31 and 255, the
corresponding character is displayed. Otherwise, an exception is thrown and the
catch block is executed. After executing the catch block, the statements after the
catch block are executed in a normal flow.
In addition to main(), the try block can also be placed in any other user-
defined function. In this case, the try block is localized to the function in which it is
Self-Instructional defined.
266 Material
Program 13.2: A program to demonstrate the concept of defining try block inside Exception Handling
a user-defined function
NOTES
}
The output of the program is
Self-Instructional
Material 267
Exception Handling
13.3 EXCEPTION HANDLING CONSTRUCTS
The syntax to throw an exception from a function defined outside the try
block is
Self-Instructional
268 Material
Exception Handling
NOTES
Self-Instructional
Material 269
Exception Handling
Self-Instructional
270 Material
Exception Handling
NOTES
Self-Instructional
Material 271
Exception Handling However, if the name of the argument is specified, then that argument can
be used in the catch block. To understand this concept, consider this code fragment.
NOTES
}
In this code segment, an argument a of type int is passed to the catch
block and hence, can be used inside the catch block.
Using Multiple Catch Statements
The programs discussed so far contain only one catch block. However, C++ also
allows us to provide multiple catch blocks to handle different types of exceptions.
The syntax to define multiple catch blocks is:
}
Note that there is only one try block in which multiple exceptions are thrown
and depending on the type of exception thrown, a particular catch block is executed.
Whenever an exception is thrown, the catch blocks are searched in sequential
order for an appropriate match. The first catch block whose data type matches
with the type of exception is executed and other catch blocks are skipped. Once
Self-Instructional
272 Material
the execution of the appropriate catch block gets over, the control passes to the Exception Handling
Self-Instructional
Material 273
Exception Handling
NOTES
}
The output of the program is
First run
Enter the coefficients of a quadratic equation:
2 3 3
Exception-square root of a negative number
Second run
Enter the coefficients of a quadratic equation:
0 1 2
Exception-division by zero
Third run
Enter the coefficients of a quadratic equation:
2 4 2
Exception-Roots are equal: -1
Fourth run
Enter the coefficients of a quadratic equation:
4 5 1
The roots are: -0.25 and –1
In this program, multiple exceptions are caught and handled by different
catch blocks. If the first coefficient is zero, the exception of type int is thrown
and the catch block 1 is executed. If the value of d evaluates to a negative number,
the exception of type double is thrown and the catch block 2 is executed.
Finally, if the value of d evaluates to zero, a char exception is thrown and catch
block 3 is executed. If no exception occurs, the roots of the equation are calculated
and displayed.
1. C++ exception handling mechanism mainly uses three keywords, try, throw NOTES
and catch.
2. The point within the function at which the throw statement is executed is
called the throw point.
13.5 SUMMARY
Self-Instructional
276 Material
Other Exception Handling
14.0 INTRODUCTION
In this unit‚ you will learn about the exception class‚ exception handling in constructor
and destructor‚ rethrowing and handling uncaught exception. Exception class is
derived from the single class i.e. std::exception. It is a small interface class designed
to serve as a base class to any exception thrown by the C++ standard library.
14.1 OBJECTIVES
In C++, a header file <stdexcept>, derived from the base class exception,
defines a set of exception classes in which we can categorize the very common
exceptions. The following table illustrates the exception classes and their purposes.
Self-Instructional
Material 277
Other Exception Handling
Sometimes it is not possible to predict all types of exceptions that can occur
during the program execution and hence, separate catch blocks cannot be provided
to handle all the exceptions. In such cases, a single catch block to handle multiple
exceptions can be defined. This can be achieved by using the ellipsis (...) as
the arguments in the catch block. The syntax for defining the catch block with
ellipsis is as follows:
Self-Instructional
278 Material
Program 14.1: A program to demonstrate the concept of catching all exceptions Other Exception Handling
NOTES
Second run
In this program, a single catch block having ellipsis as argument is defined for
catching all types of exceptions. If the user enters an ASCII code between 32 and
255, its equivalent character is displayed. Otherwise, an exception is thrown and
an appropriate message is displayed.
Self-Instructional
Material 279
Other Exception Handling As stated earlier, if an appropriate match of exception handler is not found,
the program terminates abnormally. To prevent this, catch(...) can be used
as a default exception handler along with other catch blocks to handle all those
exceptions that are not handled by any other catch block. However, it should
NOTES always be placed after all the other catch blocks; otherwise, it would prevent
other catch blocks from handling exceptions.
14.3.1 Catching Class Types
As stated earlier, in addition to built-in data types, exceptions of user-defined data
types such as classes can also be caught and handled. In this case, the throw
expression throws an object of the class as exception and the catch block accepts
an object of the class as argument.
Program 14.2: A program to demonstrate the concept of catching exceptions of
class type
Self-Instructional
280 Material
Other Exception Handling
NOTES
Second run
Self-Instructional
Material 281
Other Exception Handling
NOTES
Second run
Sometimes a situation may arise that the exceptions, which occur while creating
the objects of a class, need to be handled. Since constructors cannot return a
Self-Instructional
value, an exception must be thrown inside the constructor of the class. If an
282 Material
exception is thrown from within a constructor, then the object being constructed Other Exception Handling
will not be constructed properly. Therefore, the destructor for the object will never
be called. However, the destructors for completely constructed objects will be
called.
NOTES
To effectively handle exceptions in constructors, a new entity called an
exception class needs to be created. The throw statement, in this case, throws an
object of the exception class, which is handled by the catch block accepting an
object exception class.
An exception class can be defined either globally or in the public section of
another class. Moreover, the body of the exception class can be either empty or it
can contain data members and member functions. This section discusses an
exception class with an empty body.
To understand the concept of handling exceptions in constructors, consider
this example.
Program 14.4: A program to demonstrate the concept of exception handling in
constructors and destructors.
Self-Instructional
Material 283
Other Exception Handling
NOTES
While handling exceptions that involve base as well as derived classes, proper
ordering of catch blocks is necessary. A catch block handling the exception of
derived class should be placed before the base class exception handler. If the
base class exception handler is placed before the derived class exception handler,
the base class handler catches all the derived classes’ exceptions and the derived
class handler will not be executed.
Program 14.5: A program to demonstrate the concept of exception handling in
base and derived classes
Self-Instructional
284 Material
Other Exception Handling
NOTES
In this program, the exception of derived class positive is caught and handled
by the catch block of base class number as it is placed before the catch block of
derived class. However, if the order of catch blocks is changed, the output of the
program is as follows:
Note: If the exception of the base class is thrown, it is handled by the catch
block of base class only irrespective of the order of the catch blocks.
C++ also provides a way to restrict a particular function to throw only a specified
list of exceptions. This can be achieved by providing a list of data types of exceptions
in the function header. The list is known as throw list. The throw list specifies the
type of exceptions that can be thrown by the function. The syntax for specifying a
throw list is as follows:
Self-Instructional
Material 285
Other Exception Handling Note that throwing an exception of type that is not listed in data_type_list
causes abnormal program termination by calling the default function
unexpected().
Program 14.6: A program to demonstrate the concept of restricting exceptions
NOTES
Self-Instructional
286 Material
Other Exception Handling
NOTES
Self-Instructional
Material 287
Other Exception Handling
Self-Instructional
288 Material
Other Exception Handling
In this code segment, the try block defined within the function throws an exception
of type char. The local catch block of the function catches the exception.
NOTES
A function can also be prevented from throwing any type of exception by
specifying an empty throw list in the function header. For example, the function
func() in Program 14.6 can be prevented from throwing any type of exception
by specifying an empty throw list.
C++ also allows a catch block to rethrow an exception without processing it.
Rethrowing an exception allows multiple handlers to access the same exception.
As stated earlier, a throw statement without any argument is used to rethrow an
exception. The exception, which is rethrown by the catch block, passes to the
next enclosing try/catch sequence and is caught by the catch block of that try/
catch sequence. Note that an exception can only be rethrown from within a catch
block or from any function called inside that block.
Note: If an exception is rethrown, it will not be caught again by any of the
catch blocks of the same try block; rather, it passes to the catch block of the
next enclosing try/block sequence.
Program 14.7: A program to demonstrate the concept of rethrowing an exception
Self-Instructional
Material 289
Other Exception Handling
NOTES
In this program, an ASCII code entered by the user is checked for the exception.
If the user enters a value less than zero or greater than 255, an exception of type
int is thrown. Otherwise, its equivalent character is thrown to the catch block
handling the exception of type char. This catch block rethrows the exception
without processing it. Now the control passes to the next enclosing try/catch
sequence and the catch block of that sequence is executed.
Self-Instructional
290 Material
Other Exception Handling
14.8 HANDLING UNCAUGHT EXCEPTION
This function returns True if an exception has been thrown but not yet caught;
otherwise, it returns False.
1. The throw list specifies the type of exceptions that can be thrown by the
function.
2. In C++, a header file <stdexcept>, derived from the base class exception,
defines a set of exception classes in which we can categorize the very
common exceptions.
14.10 SUMMARY
x In C++, a header file <stdexcept>, derived from the base class exception,
defines a set of exception classes in which we can categorize the very
common exceptions.
x An exception class can be defined either globally or in the public section of
another class. oreover, the body of the exception class can be either empty
or it can contain data members and member functions.
x While handling exceptions that involve base as well as derived classes,
proper ordering of catch blocks is necessary.
x C++ also provides a way to restrict a particular function to throw only a
specified list of exceptions. This can be achieved by providing a list of data
types of exceptions in the function header. The list is known as throw list.
x Rethrowing an exception allows multiple handlers to access the same
exception.
Self-Instructional
Material 291
Other Exception Handling
14.11 KEY WORDS
Self-Instructional
292 Material
.emaN e1.sruIncrease
oC eht fothe
ezifont
s tnosize
f ehof
t esthe
aerCourse
cnI .1 Name.
.egaP revoC e2.ht nuse
i rethe
daefollowing
h a sa gniwasolaloheader
f eht esin
u the
.2 Cover Page.
YTISREVINUALAGAPPA
APPAGALAUNIVERSITY
B.C.A. elcyC drihT eht ni )46.3:APGC( CA[Accredited
AN yb edarG
]CGU-DRHM yb ytisrevinU I–yrogeand
300 036 – IDUKIARA
KARAIKUDI
K
with
’+A’’A+’
taC Graded
htiw
sa dedaras
– 630 003
Grade
detidby
ercNAAC
cA[ (CGPA:3.64) in the Third Cycle
G Category–I
dna University by MHRD-UGC]
PROGRAMMING IN C++
II - Semester
PROGRAMMING IN C++
B.C.A.
101 23
itnem sYou
a egaare
p reinstructed
voc eht etatodpupdate
u ot dethe
tcurcover
tsni erpage
a uoYas mentioned below:
.emaN e1.sruIncrease
oC eht fothe
ezifont
s tnosize
f ehof
t esthe
aerCourse
cnI .1 Name.
aP revoC e2.ht nuse
i rethe
daefollowing
h a sa gniwasolaloheader
f eht esin
u the
.2 Cover Page.
ISREVINUALAGAPPA
APPAGALAUNIVERSITY
rihT eht ni )46.3:APGC( CA[Accredited
AN yb edarGwith
’+A’’A+’
htiwGrade
detidby
ercNAAC
cA[ (CGPA:3.64) in the Third Cycle
]CGU-DRHM yb ytisrevinU I–yrogeand
taC Graded
sa dedarasG Category–I
dna University by MHRD-UGC]
300 036 – IDUKIARA
KARAIKUDI
TACUDE ECNATSIDDIRECTORATE
K
FO ETAROTCEOF
– 630 003
RIDDISTANCE EDUCATION
PROGRAMMING IN C++
B.C.A.
II - Semester