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

UG BCA Computer Applications 101 23 Programming in C++ 3653

Uploaded by

Rizwan Latif
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

UG BCA Computer Applications 101 23 Programming in C++ 3653

Uploaded by

Rizwan Latif
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 306

.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]

101 23 NOITACUDE ECNATSIDDIRECTORATE


FO ETAROTCEOF
RIDDISTANCE EDUCATION

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

Directorate of Distance Education

B.C.A.
II - Semester
101 23

PROGRAMMING IN C++
Author
Rohit Khurana, ITL Education Solutions Ltd.

"The copyright shall be vested with Alagappa University"

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.

Vikas® is the registered trademark of Vikas® Publishing House Pvt. Ltd.


VIKAS® PUBLISHING HOUSE PVT. LTD.
E-28, Sector-8, Noida - 201301 (UP)
Phone: 0120-4078900 x Fax: 0120-4078999
Regd. Office: 7361, Ravindra Mansion, Ram Nagar, New Delhi 110 055
x Website: www.vikaspublishing.com x Email: helpline@vikaspublishing.com

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

BLOCK I : PRINCIPLES OF OBJECT - ORIENTED PROGRAMMING


Unit - 1: Principles of Object-Oriented Programming: Software Crisis – Unit 1: Object-Oriented
Software Evolution – Basic Concepts of Object-Oriented Programming – Benefits Programming
of OOP – Object-Oriented Languages - Applications of OOP – Application of (Pages 1-24)
C++. Unit 2: Structure of a
Unit - 2: Structure of a C++ Program: Tokens – Keywords – Identifiers – Basic C++ Program
Data Types – User defined Data types – Derived data types – Symbolic constants– (Pages 25-58)
Type compatibility – Declaration of variables – Dynamic initialization of variables– Unit 3: Control Structures
Reference variables – Operators in C++ - Manipulators – Type cast operator – and Function
Expressions and their types-Implicit conversions. (Pages 59-84)
Unit - 3: Control Structures and Function: The main function – Function
prototyping – inline functions – Function overloading.

BLOCK 2 : CLASSES AND OBJECTS


Unit - 4: Introduction: Specifying a Class -Defining Member Function - C++ Unit 4: Introduction
Program with Class - Making an Outside Function Inline - Nesting of Member to Class
Functions - Arrays within a Class. (Pages 85-99)
Unit - 5: Memory Allocation for Objects: Static Data Members - Static Member Unit 5: Memory Allocation
Functions - Arrays of Objects - Objects as Function Arguments - Friendly for Objects
Functions - Returning Objects. (Pages 100-120)
Unit - 6: Constructors and Destructors: Introduction - Constructors - Unit 6: Constructors and
Parameterized Constructors - Multiple Constructors in Class - Constructors with Destructors
Default Arguments - Dynamic Initialization of Objects - Copy Constructor - (Pages 121-141)
Dynamic Constructors - Constructing Two Dimensional Arrays - Destructors.

BLOCK 3 : INHERITANCE, POLYMORPHISM AND POINTERS


Unit - 7: Inheritance: Introduction - Defining Derived Classes - Single Unit 7: Inheritance
Inheritance- Making a Private Member Inheritable - Multilevel Inheritance - (Pages 142-165)
Multiple Inheritance - Hierarchical Inheritance - Virtual Base classes - Abstract Unit 8: Pointers, Virtual
Classes - Constructors in Derived Classes - Member Classes: Nesting of Classes. Functions and Polymorphism
Unit - 8: Pointers Virtual Functions and Polymorphism: Introduction - Pointers (Pages 166-185)
to Objects - this Pointer - Pointers to Derived Classes - Virtual Functions - Pure Unit 9: Managing Console
Virtual Functions. I/O Operations
Unit - 9: Managing Console I/O Operations: C++ Streams - C++ Stream Classes- (Pages 186-218)
Unformatted I/O Operations, Formatted Console I/O Operations - Managing
Output with Manipulators.

BLOCK 4 : WORKING WITH FILES Unit 10: Introduction


Unit - 10: Introduction: Classes for File Stream Operations - Opening and Closing to Files
a File - Detecting End of File - More About Open (): File Modes. (Pages 219-229)
Unit - 11: File Pointers and their Manipulations: Sequential Input and output Unit 11: File Pointers and
Operations - Updating a File - Random Access - Error handling During File their Manipulations
Operations - Command Line Arguments. (Pages 230-251)
BLOCK 5 : TEMPLATES AND EXCEPTION HANDLING
Unit - 12: Templates: Introduction - Function Templates - Overloaded Function Unit 12: Templates
Templates - Nesting of Function Calls - Multiple Arguments Function Template- (Pages 252-263)
User Defined Templates. Unit 13: Exception Handling
Unit -13: Exception Handling: Introduction: Error Handling - Exception Handling (Pages 264-276)
Model - Exception handling Constructs - Handler Throwing the Same Exception Unit 14: Other Exception
Again. Handling
Unit - 14: Other Exception Handling: List of Exceptions - Catch All Exceptions- (Pages 277-292)
Exceptions in Constructors and Destructors - Handling Uncaught Exceptions-
Ten Rules for Handing Exceptions Successfully.
CONTENTS
INTRODUCTION

BLOCK I: PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING


UNIT 1 OBJECT-ORIENTED PROGRAMMING 1-24
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

UNIT 2 STRUCTURE OF A C++ PROGRAM 25-58


2.0 Introduction
2.1 Objectives
2.2 Structure of C++ Programs
2.2.1 Comments
2.2.2 Headers
2.2.3 iostream Header File
2.2.4 Namespace
2.2.5 main() Function
2.3 Operators in C++
2.3.1 Input Operator
2.3.2 Output Operator
2.3.3 Additional Operators in C++
2.3.4 Operators Precedence
2.4 Tokens
2.4.1 Keywords
2.4.2 Identifiers
2.4.3 Constants
2.4.4 Punctuators
2.4.5 C++ Statements
2.5 Basic Data Types
2.5.1 Built-in Data Types
2.5.2 Derived Data Types
2.5.3 User Defined Data Types
2.6 Variables
2.6.1 Declaration of Variables
2.6.2 Initialization of Variables
2.6.3 Reference Variables
2.7 Expressions
2.7.1 Type Conversions
2.7.2 Type Compatibility
2.8 Answers to Check Your Progress Questions
2.9 Summary
2.10 Key Words
2.11 Self Assessment Questions and Exercises
2.12 Further Readings

UNIT 3 CONTROL STRUCTURES AND FUNCTION 59-84


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

BLOCK II: CLASSES AND OBJECTS


UNIT 4 INTRODUCTION TO CLASS 85-99
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

UNIT 5 MEMORY ALLOCATION FOR OBJECTS 100-120


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

UNIT 6 CONSTRUCTORS AND DESTRUCTORS 121-141


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

BLOCK III: INHERITANCE, POLYMORPHISM AND POINTERS


UNIT 7 INHERITANCE 142-165
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

UNIT 8 POINTERS, VIRTUAL FUNCTIONS AND POLYMORPHISM 166-185


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

UNIT 9 MANAGING CONSOLE I/O OPERATIONS 186-218


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

BLOCK IV: WORKING WITH FILES


UNIT 10 INTRODUCTION TO FILES 219-229
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

UNIT 11 FILE POINTERS AND THEIR MANIPULATIONS 230-251


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

BLOCK V: TEMPLATES AND EXCEPTION HANDLING


UNIT 12 TEMPLATES 252-263
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

UNIT 13 EXCEPTION HANDLING 264-276


13.0 Introduction
13.1 Objectives
13.2 Exception Handling Model/Mechanism
13.3 Exception Handling Constructs
13.3.1 Catching Mechanism
13.4 Answers to Check Your Progress Questions
13.5 Summary
13.6 Key Words
13.7 Self Assessment Questions and Exercises
13.8 Further Readings

UNIT 14 OTHER EXCEPTION HANDLING 277-292


14.0 Introduction
14.1 Objectives
14.2 List of Exception Class
14.3 Catching All Exceptions
14.3.1 Catching Class Types
14.4 Exception Handling in Constructors and Destructors
14.5 Exception Handling in Base and Derived Classes
14.6 Restricting Exceptions
14.7 Rethrowing an Exception
14.8 Handling Uncaught Exception
14.9 Answers to Check Your Progress Questions
14.10 Summary
14.11 Key Words
14.12 Self Assessment Questions and Exercises
14.13 Further Readings
Introduction
INTRODUCTION

Object Oriented Programming or OOP is a programming paradigm which uses


‘objects’ – data structures consisting of data fields and methods together with NOTES
their interactions – to design applications and computer programs. Programming
techniques may include features, such as data abstraction, encapsulation, messaging,
modularity, polymorphism and inheritance.
C++ is a statically typed, free form, multi-paradigm and compiled general
purpose programming language. It is regarded as an intermediate level language,
as it comprises a combination of both high level and low level language features. It
was developed by Bjarne Stroustrup in 1979 at Bell Labs as an enhancement to
the C language. Originally named ‘C with Classes’, the language was renamed
C++ in 1983, ++ being the increment operator in C. C++ is one of the most
popular programming languages with application domains including system
software, application software, device drivers, embedded software, high
performance server and client applications, and entertainment software, such as
video games. Thus, C++ as a high level language maintains almost all aspects of
the C language while simplifying memory management and adding several features
including a new data type known as ‘class’ to allow object oriented programming.
Using functions we can structure our programs in a more modular way, accessing
all the potential that structured programming can offer to us in C++. A class is a
definition of an object. An object is a component of a program that knows how to
perform certain actions and to interact with the complete program. A function is a
group of statements that is executed when it is called from some point of the
program. C++ enables several functions of the same name to be defined as long
as these functions have different sets of parameters as far as their types are
concerned. This capability is called function overloading. When an overloaded
function is called, the C++ compiler selects the proper function by examining the
number, types and order of the arguments in the call. Function overloading is
commonly used to create several functions of the same name that perform similar
tasks but on different data types. Operator overloading allows existing C++
operators to be redefined so that they work on objects of user defined classes.
Inheritance allows one class to reuse the state and behaviour of another class. The
derived class inherits the properties and method implementations of the base class
and extends it by overriding methods and adding additional properties and methods.
Constructor creates an object and initializes it. It also creates v-table for virtual
functions. It is different from other methods in a class. Destructor usually deletes
any extra resources allocated by the object. Constructor with no arguments or all
the arguments has default values are known as default constructor. Inheritance
permits code reusability. Reusability saves time in program development. It supports
the reuse of proven and debugged high quality software thus reducing problem
after a system becomes functional. Polymorphism allows a client to treat different
Self-Instructional
Material
Introduction objects in the same way even if they were created from different classes and
exhibit different behaviours.
This book, Programming in C++, follows the SIM format or the self-
instructional mode wherein each Unit begins with an Introduction to the topic
NOTES
followed by an outline of the Objectives. The detailed content is then presented in
a simple and organized manner, interspersed with Check Your Progress questions
to test the understanding of the students. A Summary along with a list of Key
Words and a set of Self Assessment Questions and Exercises is also provided at
the end of each unit for effective recapitulation.

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

After going through this unit, you will be able to:


x Explain the software crisis and evolution
x Understand the principles of OOP
x Understand the key concepts of OOP including objects, classes,
encapsulation, etc.
x Discuss the benefits of OOP
x Explain object oriented languages
x Discuss the various applications of C++

1.2 SOFTWARE CRISIS AND EVOLUTION

Software is defined as a collection of programs, documentation and operating


procedures. The Institute of Electrical and Electronic Engineers (IEEE) defines
software as a ‘collection of computer programs, procedures, rules and
associated documentation and data.’ It possesses no mass, no volume, and no
color, which makes it a non-degradable entity over a long period. Software does
not wear out or get tired.
Software controls, integrates, and manages the hardware components of a
computer system. It also instructs the computer what needs to be done to perform
a specific task and how it is to be done. For example, software instructs the
hardware how to print a document, take input from the user, and display the
output.
Computer works only in response to instructions provided externally. Usually,
the instructions to perform some intended tasks are organized into a program
using a programming language like C, C++, Java, etc., and submitted to computer.
Computer interprets and executes these instructions and provides response to the
user accordingly. A set of programs intended to provide user with a set of
interrelated functionalities is known as software package. For example, an
Self-Instructional
2 Material
accounting software package such as Tally provides user the functionality to perform Object-Oriented
Programming
accounting-related activities.
1.2.1 Software Characteristics
Different individuals judge software on different basis. This is because they are NOTES
involved with the software in different ways. For example, users want the software
to perform according to their requirements. Similarly, developers involved in
designing, coding, and maintenance of the software evaluate the software by looking
at its internal characteristics, before delivering it to the user. Software characteristics
are classified into six major components, which are shown in Figure 1.1.

Fig. 1.1 Software Characteristics

x Functionality: Refers to the degree of performance of the software against


its intended purpose.
x Reliability: Refers to the ability of software to provide desired functionality
under the given conditions.
x Usability: Refers to the extent the software can be used with ease.
x Efficiency: Refers to the ability of software to use system resources in the
most effective and efficient manner.
x Maintainability: Refers to the ease with which the modifications can be
made in a software system to extend its functionality, improve its performance,
or correct errors.
x Portability: Refers to the ease with which software developers can transfer
software from one platform to another, without (or with minimum) changes.
In simple terms, it refers to the ability of software to function properly on
different hardware and software platforms without making any changes in
it.
In addition to the above-mentioned characteristics, robustness and integrity
are also important. Robustness refers to the degree to which software can keep Self-Instructional
Material 3
Object-Oriented on functioning in spite of being provided with invalid data while integrity refers to
Programming
the degree to which unauthorized access to the software or data can be prevented.
1.2.2 Software Crisis
NOTES In late 1960s, it became clear that the development of software is different from
manufacturing other products. This is because employing more manpower
(programmers) later in the software development does not always help speeding
up the development process. Instead, sometimes it may have negative impacts
like delay in achieving the scheduled targets, degradation of software quality, etc.
Though software has been an important element of many systems since a long
time, developing software with certain schedule or quality is still difficult.
History has seen that delivering software after the scheduled date or with
errors has caused large-scale financial losses as well as inconvenience to many.
Disasters such as the Y2K problem affected economic, political, and administrative
systems of various countries around the world. This situation, where catastrophic
failures have occurred, is known as software crisis. The major causes of software
crisis are the problems associated with poor quality software such as malfunctioning
of software systems, inefficient development of software, and the most important,
dissatisfaction amongst the users of the software.
The software market today has a turnover of more than millions of rupees.
Out of this, approximately 30% of software is used for personal computers and
the remaining software is developed for specific users or organizations. Application
areas such as the banking sector are completely dependent on software application
for their working. Software failures in these technology-oriented areas have led to
considerable loss in terms of time, money, and even human lives. History has been
witness to many such failures, some of which are listed below.
x The Northeast blackout in 2003 has been one of the major power system
failures in history of North America. This blackout involved failure of 100
power plants due to which almost 50 million customers faced power loss
that resulted in financial loss of approximately $6 billion. Later, it was
determined that the major reason behind the failure was a software bug in
power monitoring and management system.
x Year 2000 (Y2K) problem refers to the widespread snags in processing
dates after the year 2000. The roots of Y2K problem can be traced back
to 1960-80 when developers shortened the 4-digit date format like 1972
to a 2-digit format like 72 because of limited memory. At that time they did
not realize that year 2000 will be shortened to 00 which is less than 72. In
the 1990s, experts began to realize this major shortcoming in the computer
application and millions were spent to handle this problem.
x In 1996, Arian-5 space rocket, developed at the cost of $7000 million
over a period of 10 years was destroyed within less than a minute after its

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.

1.3 PRINCIPLES OF OBJECTED ORIENTED


PROGRAMMING (OOP)

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.

Fig. 1.2 Data and Functions in OOP

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.

Fig. 1.3 Single Entity of Class Car

The object model directly supports references of the objects. As in reality,


most object instances ‘reference’ each other in some way. References
are also called ‘relationships’.

Self-Instructional
8 Material
Object-Oriented
Programming

NOTES

Fig. 1.4 Object Identifications of Object Car

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.

Check Your Progress


1. What is software?
2. What does data abstraction refer to?

1.4 BASIC CONCEPTS OF OOP

To understand the concept of object oriented programming, it is necessary to


know the fundamental terms and concepts of this approach. These include objects,
classes, data abstraction, encapsulation, inheritance, polymorphism and message
passing.
1.4.1 Objects
Objects are the small, self-contained and modular units with a well defined
boundary. An object consists of a state and behaviour. The state of an object
is one of the possible conditions that an object can exist in and is represented
by its characteristics or attributes or data. The behaviour of an object determines
how an object acts or behaves and is represented by the operations that it can
perform. In OOP, the attributes of an object are represented by variables and
the operations are represented by functions.
An object biscuit, for example may consist of data product code P001,
product name Britannia biscuits, price 20 and quantity in hand 50. These data
values specify the attributes or features of the object. Similarly, consider another
object noddles with product code P002, product name Maggi Noodles, price
10, and quantity in hand 20 (refer Figure 1.5). In addition, the data in the object
can be used by the functions, such as and
. These functions specify the actions that can be performed on
data.
Objects are what actually runs in the computer and, thus, are the basic
runtime entities in object oriented systems. They are the building blocks of
object oriented programming. Although, two or more objects can have the
same attributes, still they are separate and independent objects with their own
identity. In other words, all the objects in a system take a separate space in
the memory independent of each other. Note that the main objective of breaking
Self-Instructional
10 Material
down complex software projects into objects is that changes made to one part Object-Oriented
Programming
of a software should not adversely affect the other parts.
Some Real Life Examples of Objects
When you consider a programming problem in an object oriented language, you NOTES
need to determine how the problem will be divided into functions, and objects and
class. With the help of class, objects and functions user friendly programs can be
designed using object oriented language which are known as ‘real life programs’.
This approach is helpful in finding the close match between objects in the
programming sense and objects in real world. Table 1.1 summarizes the various
types of objects used in real life as well as programming environment.
Table 1.1 Objects used in Real Life and Programming Environment
Types of Examples Picture
Objects
Real Life Examples of real life objects are
Objects electrical components in a circuit
design program, aircraft in an air
traffic control system, countries in an
economics model, etc.

Graphic Examples of graphic objects are


Objects lines, rectangles, circles, etc.

Computer Examples of computer user


User environment objects are Windows,
Environment menus, mouse, keyboard, etc.
Objects

Computer Examples of computer game objects


Game are positions in board game (chess),
Objects flowers in an ecological simulation,
opponents and friends in adventure
games, ghosts in a maze game, etc.

Programming Examples of programming objects


Objects are customized arrays, stacks, linked
lists, binary trees, etc.

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).

Fig. 1.5 Class and Objects

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).

Fig. 1.6 Inheritance

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).

Fig. 1.7 Operator Overloading

Similarly, a single function can behave differently depending on the type of


data provided. In Figure 1.8, for example, the function can be used to
add two integers and two float-point numbers. This form of polymorphism is known
as function overloading.

Fig. 1.8 Function Overloading


Note: Compile-time polymorphism is also known as static binding, as the linking of function
call to the actual code of the function is done at compile-time itself.
Consider another example in which three different classes, ,
and are derived from the base class
. The function of the base class is
implemented in different ways in all its derived classes, and a call to a particular

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

Fig. 1.9 Runtime Polymorphism

1.4.7 Message Passing


Message passing is a process of interaction between different objects in a program.
As explained earlier, a program following the object oriented paradigm comprises
a set of objects each with a set of data and functions. When the program is executed,
these objects interact or communicate with each other by sending and receiving
messages. The messages are exchanged by calling the member functions of the
classes.
Any object of a class that wants to communicate with the object of another
class requests the object to invoke the required member function of its class. This
function call is different from the normal function call as, in this case, the sending
object is sending a request for the execution of the function. However, the receiving
object may or may not accept the request depending on whether the function
forms the public interface or it is hidden from the outside world. Thus, this form of
communication is called message sending and not an ordinary function call.
Consider, for example two classes and . The object of
the class can communicate with the object of the class by
sending a request for placing order (refer Figure 1.10).

Self-Instructional
Material 17
Object-Oriented
Programming

NOTES

Fig. 1.10 Message Passing

1.4.8 Dynamic Binding


Dynamic binding is the process of linking of a function call to the actual code of
the function at runtime; that is, in dynamic binding, the actual code to be executed
is not known to the compiler until runtime.
The concept of dynamic binding is implemented with the help of inheritance
and runtime polymorphism (virtual functions). Consider, for example, the class
hierarchy shown in Figure 1.9. Each derived class has the same function ,
however, with different body. At runtime, depending on the object being referenced,
the desired function will be called.

Check Your Progress


3. What are objects?
4. What is encapsulation?

1.5 BENEFITS OF OOP

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.

1.6 OOP LANGUAGES

To develop software, the object oriented concepts need to be implemented in any


high level language. The high level language that implements the concepts of OOP
is known as an object oriented language (also called an OO language). In general,
an OO language must support all or some of these OO concepts, such as:
x Encapsulation and data hiding
x Inheritance
x Polymorphism and dynamic binding
x All built-in and user defined data types are objects
x All operations are performed using the message passing techniques
Depending on the extent to which they support OO concepts, the OO
languages are classified into several categories that are as follows:
x Pure Languages: Languages that not only support but also enforce all
object oriented concepts are called pure OO languages. In these languages,
everything from character and punctuations to modules is treated as an
object. Smalltalk, Eiffel and Ruby are the examples of pure OO languages.
x Hybrid Languages: Languages that support some (not all) of the OO
concepts are called hybrid languages. Java, Python and C# are the examples
of hybrid languages.
Self-Instructional
Material 19
Object-Oriented x Multi-paradigm Languages: Languages that support many programming
Programming
paradigms, such as procedural programming, generic programming, etc.,
one of which is object oriented paradigm are called multi-paradigm
languages. C++ is the example of multi-paradigm language.
NOTES
x Object based Languages: Languages that support the concept of abstract
data types and also other OO concepts, such as encapsulation, data hiding
and operator overloading are known as known as object based languages.
However, these languages do not support the concept of inheritance and
dynamic binding. Ada and Modula-2 are the examples of object based
languages.
Note: Though C++ supports multiple paradigms, it can be considered as hybrid language, as
it supports all the OO concepts that other hybrid languages like Java support.
An evaluation and comparison of some of the popularly used programming
languages, based on the OO concepts they support, is listed in Table 1.2.
Table 1.2 A Comparison of Some Popular OO Languages

There is no fixed rule or principle based on which a particular language can be


chosen for developing software. The decision of the choice of language depends
entirely on the characteristics and basic needs of the application to be developed,
re-usability of the existing code, the impact of the organization on the choice of the
programming language and various other aspects. However, C++ is the most
successful and widely used general-purpose OO language.
Note: The implementation of all the basic OO concepts will be discussed in this book using
C++ only.
Self-Instructional
20 Material
Object-Oriented
1.7 APPLICATIONS OF OOP Programming

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.

NOTES Check Your Progress


5. Write one benefit of OOP.
6. What are hybrid languages?

1.8 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. (IEEE) defines software as a ‘collection of computer programs, procedures,


rules and associated documentation and data.’
2. The data abstraction refers to the act of representing the essential features
without including the background details or explanations.
3. Objects are the small, self-contained and modular units with a well defined
boundary.
4. Encapsulation is the technique of binding or keeping the data and functions
(that operate on them) together in a single unit called a class.
5. 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.
6. Languages that support some (not all) of the OO concepts are called hybrid
languages.

1.9 SUMMARY

x (IEEE) defines software as a ‘collection of computer programs, procedures,


rules and associated documentation and data.’
x A programming paradigm describes the structure of a program. In other
words, it determines how the instructions are placed in the program. Each
programming language follows one or the other programming paradigm.
x In an unstructured programming paradigm, all the instructions of a program
were written one after another in a single function and hence were suitable
for writing only small and simple programs.
x In a structured programming, programs are divided into different procedures
(also known as functions, routines or subroutines) and each procedure
contains a set of instructions that performs a specific task. It follows the
top-down approach.

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.

1.10 KEY WORDS

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

NOTES Short Answer Questions


1. What do you understand by software crisis?
2. Why is OOP paradigm developed?
3. What is operator overloading?
4. What is function overloading?
5. Write the function of dynamic binding.
6. Name the multi-paradigm languages.
Long Answer Questions
1. Describe the approach of OOP principles with the help of illustrations and
examples.
2. Explain objects, classes, abstraction, encapsulation, inheritance and
polymorphism with the help of illustrations.
3. What is message passing? Explain.
4. Explain the benefits of OOP with the help of illustrations and examples.
5. Explain some popular object oriented languages.
6. Describe the various OOP applications and their advantages.

1.12 FURTHER READINGS

Jeyapoovan, T. 2006. Computer Programming: Theory and Practice (with


CD). New Delhi: Vikas Publishing House.
Khurana, Rohit. 2008. Object Oriented Programming with C++. New Delhi:
Vikas Publishing House.
Saxena, Sanjay. 2009. Introduction to Information Technology. New Delhi:
Vikas Publishing House.

Self-Instructional
24 Material
Structure of a C++ Program

UNIT 2 STRUCTURE OF A C++


PROGRAM
NOTES
Structure
2.0 Introduction
2.1 Objectives
2.2 Structure of C++ Programs
2.2.1 Comments
2.2.2 Headers
2.2.3 iostream Header File
2.2.4 Namespace
2.2.5 main() Function
2.3 Operators in C++
2.3.1 Input Operator
2.3.2 Output Operator
2.3.3 Additional Operators in C++
2.3.4 Operators Precedence
2.4 Tokens
2.4.1 Keywords
2.4.2 Identifiers
2.4.3 Constants
2.4.4 Punctuators
2.4.5 C++ Statements
2.5 Basic Data Types
2.5.1 Built-in Data Types
2.5.2 Derived Data Types
2.5.3 User Defined Data Types
2.6 Variables
2.6.1 Declaration of Variables
2.6.2 Initialization of Variables
2.6.3 Reference Variables
2.7 Expressions
2.7.1 Type Conversions
2.7.2 Type Compatibility
2.8 Answers to Check Your Progress Questions
2.9 Summary
2.10 Key Words
2.11 Self Assessment Questions and Exercises
2.12 Further Readings

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

After going through this unit, you will be able to:


x Understand the structure of a C++ program
x Discuss operators used in C++ and their precedence
x Explain programming elements and tokens
x Describe basic data types
x Use variables and const qualifier in a C++ program
x Explain expressions and type compatibility

2.2 STRUCTURE OF C++ PROGRAMS

Programs are a sequence of instructions or statements. These statements form the


structure of a C++ program. C++ program structure is divided into various sections,
namely headers, class definition, member functions definitions and
function (refer Figure 2.1).

Fig. 2.1 Structure of a C++ Program

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

as shown in Figure 2.2.

NOTES

Fig. 2.2 A Simple C++ Program Without a Class

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

C Style Header C++ Style Header

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.

2.3 OPERATORS IN C++

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

Fig. 2.3 Types of Operators


In C++, input and output operators are used to take input and display output. The
operator used for taking the input is known as the extraction or get from operator
(>>) while the operator used for displaying the output is known as the insertion
or put to operator (<<).
2.3.1 Input Operator
The input operator, commonly known as the extraction operator (>>), is used
with the standard input stream, cin. As stated earlier, cin treats data as a
stream of characters. These characters flow from cin to the program through
the input operator. The input operator works on two operands, namely the cin
stream on its left and a variable on its right. Thus, the input operator takes (extracts)
the value through cin and stores it in the variable.
Note: A variable refers to a memory location used to store a value that can be modified in the
program.
To understand the concept of an input operator, consider this example.
Program 2.1
A program to demonstrate the working of an input operator.
#include<iostream>
using namespace std;
int main()
{
int a; // variable declaration
cin>>a; // input operator
a=a+1;
return 0;
}
In this program, the statement cin>>a; takes an input from the user and stores
it in the variable a.
Self-Instructional
Material 31
Structure of a C++ Program Note: Always include iostream header in a program in order to use the basic input and
output facilities.

2.3.2 Output Operator


NOTES The output operator, commonly known as the insertion operator (<<), is used
with the standard output stream cout. Like cin, cout also treats data as a
stream of characters. These characters flow from the program to cout through
the output operator. The output operator works on two operands, namely the
cout stream on its left and the expression to be displayed on its right. The output
operator directs (inserts) the value to cout.
To understand the concept of output operator, consider this example.
Program 2.2
A program to demonstrate the working of an output operator.

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

Scope Resolution Operator (::)


In C++, variables in different blocks or functions can be declared with the same
name, that is, the variables in different scope can have the same name. However, NOTES
a local variable overrides the variables having same name in the outer block or the
variable with global scope. Hence, a global variable or variable in the outer block
cannot be accessed inside the inner block. This problem is solved by introducing
new operator scope resolution operator ::introduced in C++.
The scope resolution operator :: is a special operator that allows to access a
global variable that is hidden by a local variable with the same name.
Program 2.3:
A program to demonstrate the use of scope resolution operator.

The output of the program is:

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:

where, value = Initial value


For example, consider this statement.

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.

Similarly, to delete the array pointers arr_iptr and arr_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

Comma Left to right


Note: In C++, there is no operator for exponentiation. It is implemented using a standard
library function pow().

Check Your Progress


1. What are programs?
2. What are operators?
3. What is an input operator?

2.4 TOKENS

A token is defined as the smallest unit of a program. When a program is compiled,


the compiler scans the source code and parses it into tokens to find the syntax
errors. C++ tokens are broadly classified into keywords, identifiers, constants,
operators and punctuators.
2.4.1 Keywords
Keywords are the predefined words that have special significance in any language.
Every keyword is reserved for a specific purpose and hence must not be used as
user defined names (identifiers). All the keywords of C++ are listed in Table 2.4.
Table 2.4 C++ Keywords

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

Character constants refer to a single character enclosed in single quotes (‘ ’).


The examples of character constants are ‘f’, ‘M’, ‘8’, ‘&’, ‘7’, etc. All
character constants are internally stored as integer value. NOTES
Character constants can represent either the printable characters or the
non-printable characters. The examples of printable character constants are ‘a’,
‘5’, ‘#’, ‘;’, etc. However, there are a few character constants that cannot
be included in a program directly through a keyboard, such as backspace, newline
and so on. These character constants are known as non-printable constants and
are included in a program using the escape sequences. An escape sequence
refers to a character preceded by the backslash character (\). Some of the escape
sequences used in C++ are \a (alert (bell)), \b (backspace), \f (form feed),
\n (newline) linefeed, \r (carriage return), \t (horizontal tab), \v (vertical
tab), \0 (Null), \’ (single quote), \” (double quote), \\ (backslash), \?
(question mark), \C (octal constant) and \xC (hexadecimal constant).
String Constants
String constants refer to a sequence of any number of characters enclosed in
double quotes (“ “). The examples of string constants are “hello”, “name”,
“colour”, “date”, etc. Note that string constants are always terminated by
the null (‘\0’) character.
The presence of a backslash character in a string constant indicates an
escape sequence. The string constant, for example, “welcome\”home” is
displayed as welcome” home. Note that the double quote next to the backslash
is an escape sequence and not a delimiter for the string constant.
Symbolic Constants
Symbolic constant is a constant that is represented by a name. It is represented as
a variable. Unlike a variable however after a constant is initialized, its value cannot
be changed. If your program has one integer variable named students and
another variable named classes, you can compute the number students. If 15
students per class are assigned then the following statement is written to calculate
the number of students:

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:

NOTES The studentsPerClass is of no particular type (int, char and so


on). The statement #define does a simple text substitution. Every time the
preprocessor checks the word studentsPerClass, it puts the value 15
wherever variable studentsPerClass appears in the program. Because
the preprocessor runs before the compiler, your compiler never checks your
constant but it sees the number 15. Another way is to define constants with const
keyword in the following way:

Above C++ statement also declares a symbolic constant named


studentsPerClass but this time studentsPerClass is typed as
an unsigned short int. This method has several advantages in making
your code easier to maintain and in preventing bugs. The difference is that this
constant has a type and the compiler can enforce that it is used according to its
type. Constants cannot be changed while running the program. If you need to
change studentsPerClass, then you the code is changed and recompiled
again to display the result.
2.4.4 Punctuators
Punctuators, also known as separators, are tokens that serve different purposes
based on the context in which they are used. Some punctuators are used as
operators, some are used to demarcate a portion of the program, and so on. The
various punctuators defined in C++ are asterisk ‘ ’, braces ‘ ’, brackets ‘
’, colon ‘ ’, comma ‘ ’, ellipsis ‘ ’, equal to ‘ ’, semicolon ‘ ’, parentheses
‘ ’ and pound (hash) ‘ ’.
2.4.5 C++ Statements
A statement is an instruction given to the computer to perform a specific
action. In C++, a statement can be either a single statement or a compound
statement. A single statement specifies a single action and is always terminated
by a semicolon ‘;’. A compound statement, also known as a block, is a set of
statements that are grouped as a compound statement and are always enclosed
within curly braces ‘{}’.
By default, the statements are executed in the same order in which they
appear in the program and each statement is executed only once. However, the
serial execution of statements makes a program inflexible and unsuitabl for most
of the practical applications.
A C++ statement can be either a simple statement (a simple instruction
ending with a semicolon) or a compound statement (several instructions grouped
in a block). To make a simple statement, braces ({}) are included. A C++ program
Self-Instructional
40 Material
consists of a sequence of statements which includes preprocessor directives, Structure of a C++ Program

comments, declarations, function declarations including main() function,


executable statements and preprocessor directives. A preprocessor directive begins
with the character #. A statement is a complete instruction asking the computer to
carry out some tasks. Statement of C++ always end with a semicolon (;) except NOTES
for preprocessor directive, such as #define and #include. C/C++ compiler
is not sensitive to white spaces, such as spaces, tabs and blank lines in the source
code, within the statements. Compiler read a statement in the source code it looks
for the characters and for the terminating semicolon and ignores the white space.
Let us take a simple C++ statement:
Program 2.4:
A program to demonstrate the simple C++ statement.

The output of the program is:

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.

2.5 BASIC DATA TYPES

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.

Fig. 2.4 Various Data Types in C++

2.5.1 Built-in Data Types


The basic (fundamental) data types provided by C++ are integral, floating-
point and void data type. Among these data types, the integral and floating-
point data types can be preceded by several type modifiers. These modifiers (also
known as type qualifiers) are the keywords that alter either the size or range or

Self-Instructional
42 Material
both of the data types. The various modifiers are short, long, signed and Structure of a C++ Program

unsigned. By default the modifier is signed.


Note: The size and range of built-in data types vary from compiler to compiler and are
specified in the header climits.
NOTES
In addition to these basic data types, American National Standards Institute
or ANSI C++ has introduced two more data types namely, bool and wchar_t.
Integral Data Type
The integral data type is used to store integers and includes char (character) and
int (integer) data types.

Characters refer to the alphabet, numbers and other characters (such as {, @, #,


etc.) defined in the American Standard Code for Information Interchange or ASCII
character set. In C++, the char data type is also treated as an integer data type
as the characters are internally stored as integers that range in value from –128 to
127. The char data type occupies 1 byte of memory (that is, it holds only one
character at a time).
The modifiers that can precede char are signed and unsigned.
The various character data types with their size and range are listed in Table 2.6.
Table 2.6 Character Data Types
Type Size (in Bytes) Range
char 1 –128 to 127
signed char 1 –128 to 127
unsigned char 1 0 to 255

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.

2.5.2 Derived Data Types


Data types that are derived from the built-in data types are known as derived
data types. The various derived data types provided by C++ are arrays,
functions, references and pointers.
Array: An array is a set of elements of the same data type that are referred to by
a same name. All the elements in an array are stored at contiguous (one after
another) memory locations and each element is accessed by a unique index or
subscript value. The subscript value indicates the position of an element in an
array.
Self-Instructional
44 Material
Function: A function is a self-contained program segment that carries out a specific Structure of a C++ Program
well defined task. In C++, every program contains one or more functions that can
be invoked from other parts of a program, if required.
Reference: A reference is an alternative name for a variable, that is, a reference
NOTES
is an alias for a variable in a program. A variable and its reference can be used
interchangeably in a program as both refer to the same memory location. Hence,
changes made on any of them (say, a variable) are reflected in the other (on a
reference).
Pointer: A pointer is a variable that can store the memory address of another
variable. Pointers allow to use the memory dynamically, that is, with the help of
pointers, the memory can be allocated or de-allocated to the variables at runtime,
thus, making a program more efficient.
2.5.3 User Defined Data Types
The various user defined data types provided by C++ are structures, unions,
enumerations and classes.
Structure, Union and Class
Structure and union are the significant features of C language. They provide a way
to group similar or dissimilar data types referred to by a single name. However,
C++ has extended the concept of structure and union by incorporating some new
features in these data types to support object oriented programming.
C++ offers a new user defined data type known as class, which forms the
basis of object oriented programming. A class acts as a template that defines the
data and functions that are included in an object of a class. Classes are declared
using the keyword class. Once a class has been declared, its object can be
easily created.
Enumeration
An enumeration is a set of named integer constants that specify all the permissible
values that can be assigned to enumeration variables. These set of permissible
values are known as enumerators. The syntax of enum is as follows:

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.

NOTES In this statement, an enumeration data-type country (country is a tag


name, consisting of enumerators US, UN and so on, is declared. Note that
these enumerators represent integer values, so any arithmetic operation can be
performed on them.
By default, the first enumerator in the enumeration data type is assigned the
value zero. The value of subsequent enumerators is one greater than the value of
previous enumerator. Hence, the value of US is 0, value of UN is 1 and so on.
However, these default integer values can be overridden by assigning values
explicitly to the enumerators as shown here.

In this declaration, the value of US is 0 by default, the value of UN is 3, India is


4 and so on.
Once an enum type is declared, its variables can be declared using this
statement. country country1,country2;
These variables country1, country2 can be assigned any of the
values specified in enum declaration only. For example, consider these statements.

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:

2.6.3 Reference Variables


A reference variable is a new kind of variable that is introduced in C++. It provides
an alias for an already defined variable. Like other variables, reference variables
must be declared in a program before they are used.The syntax for declaring a
reference variable is

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

Fig. 2.5 Arrangement of a Reference in a Memory

In this example, price is declared as a reference variable for the variable


cost. Since both the variables refer to the same memory location, the statement
price=price + 20 changes the value of both price and cost
(refer Figure 2.5).
Some important points related to reference variables are listed here:
x A reference variable can refer to one variable only; that is, once a reference
variable has been declared to refer to a variable, it cannot refer to other
variables.
x A reference to a pointer can also be created as shown here.

x A variable can have multiple references. Hence, changing in the value of


one of them is reflected in all others.
Note: A reference variable must be initialized at the time of declaration with a variable or an
expression, not a literal.

Check Your Progress


4. Write one of the restrictions for keywords.
5. What are identifiers?
6. Why is integral data type used?

2.7 EXPRESSIONS

A combination of variables, constants and operators that represents a computation


forms an expression. Depending upon the type of operands involved in an
expression or the result obtained after evaluating expression, there are different
categories of an expression. These categories of an expression are discussed here.
x Constant Expressions: The expressions that comprise only constant values
are called constant expressions. Some examples of constant expressions
are 20, ‘a’ and 2/5+30.
Self-Instructional
Material 49
Structure of a C++ Program x Integral Expressions: The expressions that produce an integer value as
an output after performing all the type of conversions are called integral
expressions. As for example, x, 6*x-y and 10+int(5.0) are integral
expressions. Here, x and y are variables of type integer.
NOTES
x Float Expressions: The expressions that produce floating-point value as
output after performing all type of conversions are called float expressions,
for example, 9.25, x–y and 9+float(7) are float expressions. Here,
x and y are variables of type float.
x Relational or Boolean Expressions: The expressions that produce a
bool type value, that is, either true or false are called relational or Boolean
expressions, for example, x+y<100, m+n==a–b and a>= b+c are
relational expressions.
x Logical Expressions: The expressions that produce a bool type value
after combining two or more relational expressions are called logical
expressions, for example, x==5 && m==5 and y>x||m<=n are
logical expressions.
x Bitwise Expressions: The expressions that manipulate data at bit level
are called bitwise expressions, for example, a>>4 and b<<2 are
bitwise expressions.
x Pointer Expressions: The expressions that give address values as output
are called pointer expressions, for example, &x, ptr and —ptr are
pointer expressions. Here, x is a variable of any type and ptr is a pointer.
Note: An expression may be formed by combining various combination of the expressions
discussed earlier. Such expression is known as compound expression.

2.7.1 Type Conversions


An expression may involve variables and constants either of same data type or of
different data types. However, when an expression consists of mixed data types
then they are converted to the same type during evaluation to avoid compatibility
issues. This is accomplished by the type conversion, which is defined as the
process of converting one predefined data type into another. Type conversions
are of two types, namely (i) Implicit conversions and (ii) Explicit conversions
also known as typecasting.
Implicit Conversions
Implicit conversion, also known as automatic type conversion, refers to the
type conversion that is automatically performed by a compiler. Whenever the
compiler confronts a mixed-type expression, first of all char and short int
values are converted to int. This conversion is known as integral promotion.
After applying this conversion, all the other operands are converted to the type of
the largest operand and the result is of a type of the largest operand. Table 2.9
illustrates the implicit conversion of data types starting from the smallest to largest
data type. In expression 5 + 4.25, for example the compiler converts the int
Self-Instructional
into float as float is larger than int and then performs the addition.
50 Material
Table 2.9 Order of Data Types Structure of a C++ Program

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

Consider the following statements to illustrate automatic type conversion:

In the above expression, the constant 3 will be converted to float and


then the floating point division will take place (resulting in 3.33333). This (from
int to float) type of conversion where the variable of a lower data type hold
the lower range of values or has low precision is converted to a higher type (hold
higher range of values or has higher precision) is known as promotion. But, the
Lvalue is an integer variable hence the result of f/3 will be automatically truncated
to 3 and the fractional part will be lost. This (from float to int) type of
conversion is known as demotion. The implicit conversions thus occurring are also
known as silent conversions since the programmer is not aware of these conversions
implicitly saves a lot of effort on the part of the programmer but at times it can give
rise to bugs in the programs. The following set of statements explains the process
of type conversion:

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:

Fig. 2.6 Automatic Type Conversion of Expression l = l / a+ f * d – d;

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 this example, float() acts as a conversion function that converts int to


float. However, this form of conversion cannot be used in some situations.
Consider this statement, for example:
Self-Instructional
52 Material
Structure of a C++ Program

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:

Name Type Compatibility


Two variables have compatible types only if they are defined in declarations that
use the same type name. The statement index = count should be illegal as
Indextype is a subset of the integers containing index.
typedef Keyword
C++ provides a typedef feature that allows to define new data type names
for existing data types that may be built-in, derived or user defined data types.
Once the new name has been defined, variables can be declared using this new
name. Consider this declaration, for example:

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.

Note that the typedef is used in a program to contribute to the development of


a clearer program. Moreover, it also helps in making machine-dependent program
more portable.

Check Your Progress


7. How is an expression formed?
8. What does typecasting refers?

Self-Instructional
54 Material
Structure of a C++ Program
2.8 ANSWERS TO CHECK YOUR PROGRESS
QUESTIONS

1. Programs are a sequence of instructions or statements. NOTES


2. Operators are the symbols that represent various computations, such as
addition, subtraction, etc., performed on various data items.
3. The input operator, commonly known as the extraction operator (>>), is
used with the standard input stream, cin.
4. One of the restrictions for keywords is that every keyword is reserved for
a specific purpose and hence must not be used as user defined names
(identifiers).
5. Identifiers are the names given to uniquely identify various programming
elements, such as variables, arrays, functions, classes, structures,
namespaces, and so on.
6. The integral data type is used to store integers and includes char
(character) and int(integer) data types.
7. A combination of variables, constants and operators that represents a
computation forms an expression.
8. Typecasting refers to the type conversion that is performed explicitly using
type cast operator.

2.9 SUMMARY

x Programs are a sequence of instructions or statements. These statements


form the structure of a C++ program.
x C++ supports two comment styles:
(i) Single line comment (//) and
(ii) Multiline comment (/*…*/).
x Standard headers are specified in a program through the preprocessor
directive #include.
x A namespace permits grouping of various entities, such as classes, objects,
functions and various C++ tokens, etc., under a single name.
x Every C++ program must have one and only one main()function and it
is automatically called by the compiler.
x The operator used for taking the input is known as the extraction or get
from operator (>>), while the operator used for displaying the output is
known as the insertion or put to operator (<<).
x A token is defined as the smallest unit of a program. C++ tokens are broadly
classified into keywords, identifiers, constants, operators and punctuators. Self-Instructional
Material 55
Structure of a C++ Program x Keywords are the predefined words that have special significance in any
language.
x Identifiersare the names given to uniquely identify various programming
elements, such as variables, arrays, functions, classes, structures,
NOTES
namespaces, and so on.
x Constants, also known as literals, are the values that a program cannot alter
during its execution.
x A character set can be defined as a set of characters that either individually
or in combination, represents information.
x Numeric constants refer to the numbers consisting of a sequence of digits
(with or without decimal point) that can be either positive or negative.
Numeric constants can be further classified as integer constants and floating-
point constants.
x Integer constants refer to integer-valued numbers while floating-point
constants refer to the real numbers, that is, the numbers with a decimal
point.
x Character constants refer to a single character enclosed in single quotes
(‘ ’) while string constants refer to a sequence of any number of characters
enclosed in the double quotes (“ ”).
x Operators are the symbols that represent various computations (such as
addition, subtraction, etc.) performed on different data items. These data
items on which operators act are known as operands.
x The integral data type is used to store integers and includes char(character)
and int (integer) data types.
x A floating-point data type is used to store real numbers and includes float
and double data types.
x Thebool data type can hold only boolean values that is either true or
false, where true represents 1 and false represents 0.
x The different user defined data types provided by C++ are structures, unions,
enumerations and classes.
x An enumeration is a set of named integer constants that specify all the
permissible values that can be assigned to enumeration variables. These set
of permissible values are known as enumerators.
x A variable is an identifier that refers to the data item stored at a particular
memory location.
x A combination of variables, constants and operators that represents a
computation forms an expression.
x The type conversion is defined as the process of converting one predefined
data type into another.
Self-Instructional
56 Material
x Implicit conversion, also known as automatic type conversion, refers to the Structure of a C++ Program

type conversion that is automatically performed by the compiler.


x Typecasting refers to the type conversion that is performed explicitly using
typecast operators.
NOTES
x Thetypedef feature allows us to define new data type names for existing
data types that may be built-in, derived or user-defined data types.
x The scope resolution operator :: is a special operator that allows one to
access a global variable that is hidden by a local variable with the same
name.
x Two dynamic allocation operators new and delete allocate and de-
allocate memory at runtime, respectively.
x When an expression consists of more than one operator, the operator is to
be evaluated first by determining the precedence and associativity of
operators.

2.10 KEY WORDS

x Character set: A set of characters that either individually or in combination,


represents information.
x Token: The smallest unit of a program, which includes keywords, identifiers,
constants, operators and punctuators.
x Keywords: The predefined words that have special significance in any
language
x Constants: Literals that a program cannot alter during its execution.
x Operators: The symbols that represent various computations, such as
addition, subtraction, etc., performed on various data-items.

2.11 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. What are programs?
2. Why are headers required in C++ programs?
3. How can the entities of a namespace be accessed?
4. What are the advantages of using new operator over malloc() function?
5. Define the term keywords.
6. What are symbolic constants?

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.

2.12 FURTHER READINGS

Jeyapoovan, T. 2006. Computer Programming: Theory and Practice (with


CD). New Delhi: Vikas Publishing House.
Khurana, Rohit. 2008. Object Oriented Programming with C++. New Delhi:
Vikas Publishing House.
Saxena, Sanjay. 2009. Introduction to Information Technology. New Delhi:
Vikas Publishing House.

Self-Instructional
58 Material
Control Structures

UNIT 3 CONTROL STRUCTURES and Function

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

After going through this unit, you will be able to:


NOTES x Explain the importance of control structures and functions in C++
x Describe inline functions
x Return values from functions
x Invoke a function either by value or by reference
x Understand the concept of function overloading
x Discuss the features of function overriding
x Define and use operator overloading

3.2 CONTROL STRUCTURES/STATEMENTS

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.

Nested if-else Statement


A nested if-else statement contains one or more if-else statements.
The if-else statement can be nested in three different ways which are discussed
here.
(i) The if-else statement is nested within the if part.
The syntax is as follows:

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

The output of this program is:

Conditional Operator as an Alternative


The conditional operator ‘? :’ selects one of the two values or expressions
based on a given condition. Due to this decision-making nature of the conditional
operator, it is sometimes used as an alternative to if-else statements. Note
that the conditional operator selects one of the two values or expressions and not
the statements as in the case of an if-else statement. In addition, it cannot
select more than one value at a time, whereas if-else statement can select
and execute more than one statement at a time. For example, consider this statement.

This statement assigns maximum of x and y to max.


switch Statement
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. When a match is
found, all the statements associated with that constant are executed.
The syntax of the switch statement is as follows:

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.

In this program, depending upon the input, an appropriate message is displayed;


that is, if 2 is entered, then the message Option 2 is selected and Self-Instructional
Material 65
Control Structures displayed. In case, 5 is entered, then the message Invalid option! is
and Function
displayed.
Similar to if and if-else statements, switch statements can also
be nested within one another. A nested switch statement contains one or more
NOTES
switch statements within its case label or default label (if any).
Note: Switch statement cannot be used for testing floating-point values or string values.

3.2.2 Iteration Statements or Loops


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(s) is executed. The various iteration statements used in C++ are for
loop, while loop and do-while loop.
for Loop
The for loop is one of the most widely used loops in C++. It is a deterministic
loop in nature, that is, the number of times the body of the loop is executed is
known in advance.
The syntax of the for loop is as follows:

Note that initialize, condition and increase are optional


expressions and are always specified in parentheses. All the three expressions are
separated by semicolons. The semicolons are mandatory and hence cannot be
excluded even if all the three expressions are omitted.
Program 3.5
A program to display a count down using for loop.

Self-Instructional
66 Material
The output of this program is: Control Structures
and Function

for Loop Using Comma Operator NOTES


The for loop allows multiple variables to control the loop using comma operator,
that is, two or more variables can be used in the initialize and the
increase part of the loop. For example, consider this statement.

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:

These points should be noted about the while loop.


x Unlike the for loops where explicit initialize and increase
expressions are specified, while loops do not specify any explicit
initialize and increase expressions. This implies that the control
variable must be declared and initialized before the while loop and needs
to be updated within the body of the while loop.
x The while loop executes as long as condition evaluates to True.
If condition evaluates to False in the first iteration, then the body of
while loop never executes.
x The while loop can have more than one expression in its condition.
However, such multiple expressions must be separated by commas and are
executed in the order of their appearance.
Program 3.6
A program to determine the sum of first n consecutive positive integers.

Self-Instructional
Material 67
Control Structures
and Function

NOTES

The output of the program is:

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

The output of the program is:

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.

3.2.3 Jump Statements


Jump statements are used to alter the flow of control unconditionally, that is, jump
statements transfer the program control within a function unconditionally. The jump
statements defined in C++ are break, continue, goto and return. In
addition to these jump statements, a standard library function exit()is used to
jump out of an entire program.
break Statement
The break statement is extensively used in loops and switch statements. A
break statement immediately terminates the loop or the switch statement,
Self-Instructional
Material 69
Control Structures bypassing the remaining statements. The control then passes to the statement that
and Function
immediately follows the loop or the switch statement. A break statement
can be used in any of the three C++ loops.
Note that a break statement used in a nested loop affects only the inner
NOTES
loop in which it is used and not any of the outer loops. Similarly, a break statement
used in a switch statement breaks out of that switch statement and not out
of any loop that contains the switch statement.
continue Statement
The continue statement is used to ‘continue’ the loop with its next iteration.
In other words, continue statement skips any remaining statements in the
current iteration and immediately passes the control to the next iteration. The
continue statement does not terminate the loop (as in the case of break
statements) rather it only terminates the current iteration of the loop. Like a break
statement, a continue statement can be used in any of the three loops.
Program 3.8
A program to add the factors of a number.

The output of the program is:

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.

The output of the program is:

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

The output of the program is:

Check Your Progress


1. What are the different types of control statements?
2. Write a note on switch statement.

3.3 FUNCTIONS IN C++

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:

In the above statement:


x type is the data type specifier of the data returned by the function.
x name is the identifier by which it will be possible to call the function.
x parameter consists of a data type specifier followed by an identifier
like any regular variable declaration, for example int x and which acts
within the function as a regular local variable. They allow passing arguments
Self-Instructional
72 Material
to the function when it is called. The different parameters are separated by Control Structures
and Function
commas.
x statements is the function’s body. It is a block of statements
surrounded by braces { }.
NOTES
Various concepts of function include function prototyping, function definition,
invoking functions, etc., which are discussed in subsequent sections:
3.3.1 Function Prototyping
Like variables, functions also need to be declared before they are used in programs.
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. Function name together with parameter list is known as
function signature and it does not include return type of a function. The syntax
for declaring a function is as follows:
return_type function_name(parameter_list);
where,
return_type = The data type of the value returned by the function
(by default, it is int)
function_name = The name of the function
(parameter_list)= The list of variables along with their data types
The syntax for specifying a function’s parameter list is as follows:
type1 param1, type2 param2, . . ., typeN paramN
where,
type1, type2, typeN = Data types of parameters — cannot be
void
param1, param2,..., paramN = List of variables (also known
as parameters)
Note: Unlike C, the function prototype is mandatory in C++.
To understand the concept of function declaration, consider this statement.
int func(int x, char y);
In this statement, a function named func is declared which returns an integer
value and takes an integer and a character value as parameters. Note that in function
prototype, data types of parameters must be specified, however, specifying
parameter names is optional. This is because the compiler only needs to be aware
of the data type of every parameter. Thus, the prototype of func can also be
written as follows:
int func(int, char);
These arguments are known as fixed arguments and are type checked at compile-
time.
The function whose parameter_list is empty or void can be declared
as follows:
Self-Instructional
Material 73
Control Structures void disp();
and Function
It can also be written as follows:
void disp(void);
Note: Unlike variables declaration, all the function parameters must be declared individually
NOTES by providing both the type and the name even if the parameters share a common data type.
Thus, the function prototype int newfunc(int x, y) is invalid.
Function prototype enables the compiler to validate a function call. Whenever
a function is called the compiler checks whether the return type, the function name,
and the type and order of parameters are compatible with the function declaration
or not. In case a conflict arises, an error is raised. In addition, function prototype
forces the conversion of arguments to the appropriate type. For example, the
sqrt function of header cmath specifies a double argument in its function
prototype. However, this function can also be called with an int argument and the
function will work correctly because of this implicit conversion.
To understand the concept of implicit type conversion of arguments, consider this
statement.
cout<<sqrt(4);
This statement prints the value 2 as the function prototype will force the compiler
to convert integer argument (4) to double argument (4.0) and then double argument
(4.0) will be passed to sqrt.
Open Parameter List
Generally, a function accepts a fixed number of parameters. However, C++ also
enables to provide variable or open number of parameters in parameter list. Such
functions must have at least one fixed argument. If this mandatory argument is not
provided, the other arguments in the list cannot be accessed. The last argument of
this function should be ellipsis (…), which indicates that the function may take any
number of arguments after the mandatory argument.
To understand the concept of open parameter list, consider this statement.
int myfunc(int count, long total, ...);
In this statement, count and total are the fixed arguments that must be passed
whenever the function is called. However, the variable arguments specified by
ellipsis (…) may or may not be passed. Note that the variable arguments are
passed with no type checking.
3.3.2 Function Definition
In order to use a function in a program, the function must be first defined somewhere
in a program. A function definition contains the code that specifies the actions to
be performed. The syntax for defining a function is as follows:

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.

The output of the program is

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.

The output of the program is:

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

Whenever a function is invoked, a set of operations is performed which includes


NOTES passing the control from the calling function to the called function, managing stack
for arguments and return values, managing registers, etc. All these operations take
much of compiler time and slow down the execution process. This overhead can
be avoided by using macros in a program. However, macros are not considered as
true functions, as they do not perform type checking. Another way to make function
calls execute faster and also perform type checking is to make the function inline.
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.
Inline functions can be declared by prefixing the keyword inline to the return type
in the function prototype. An inline function ‘requests’ the compiler to replace its
each and every call by the code in its body. That is, specifying a function as inline
is just a request to the compiler and not a command. So, it does not change the
behaviour of a function. Moreover, the compiler may or may not choose to replace
each call by the body. In case, it does, the function becomes ‘in line’ with the rest
of the source code.
The syntax for inline function declaration is as follows:
inline return_type function_name(parameter_list);
A difference between a normal function call and inline function call is shown in
Figure 3.1.

(a) Normal Function Call

(b) Inline Function Call


Fig. 3.1 Difference between a Normal and Inline Function Call
Self-Instructional
78 Material
In Figure 3.1(a), when the compiler reads the statement prod(a,b), it transfers Control Structures
and Function
the control to the prod() function. However, in Figure 3.1(b), the prod()
function is declared as an inline function. As a result, when the compiler reads the
statement prod(a,b), it replaces the function call with the definition of the
prod() function. NOTES
Inline functions are ideal for functions that are small in size and frequently used by
the programs. This is because inline functions reduce the time consumption and
overhead involved in function calls. However, they also significantly increase the
size of the program which in turn may adversely affect the readability of the program.
Also, these functions restrict the portability of the program.
Note: The functions containing static variables, loops or switch statements cannot be inlined.

Program 3.15
A program to demonstrate how inline function works.

The output of the program is:

3.5 FUNCTION OVERLOADING

In some cases when a similar action is to be performed on different types of data,


different functions having different names are to be defined for all types of data.
This makes the program very complex as the programmer must keep a track of
the names of all the functions defined in the program. To prevent such situations,
C++ allows the functions to be overloaded.
Overloading affirms the role of a single entity for multiple tasks. Function
overloading is a way to implement compile-time polymorphism that allows multiple
Self-Instructional
Material 79
Control Structures functions to share the same name with different parameters. The compiler identifies
and Function
the function either on the basis of the number of parameters, the data type of the
parameters or the order of the data type of the parameters passed to the function.
Moreover, functions with different return type but with similar function signature
NOTES are not considered as overloaded functions.
Note: Constructors are the most commonly overloaded functions and main()is the only
function that cannot be overloaded.
To understand the concept of function overloading, consider these function
declarations.

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

The output of the program is:


NOTES
Enter side of a square : 12

Check Your Progress


3. What is function prototype?
4. Define inline function.
5. What is function overloading?

3.6 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

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.

3.8 KEY WORDS

x Formal Arguments: The arguments that appear in the function definition


are known as formal arguments
x Command Line Arguments: The arguments which are passed by typing
them after the program name on the command line
x Function Overloading: A way to implement compile-time polymorphism
that allows multiple functions to share the same name with different parameters
x Function Overriding: Redefining process of the base class member function
in the derived class

3.9 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. Differentiate between function prototyping and function definition.
2. Write a function prototype for functions.
3. Write a function prototype for square() function that takes two integer
arguments and returns a long value.

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.

3.10 FURTHER READINGS

Jeyapoovan, T. 2006. Computer Programming: Theory and Practice (with


CD). New Delhi: Vikas Publishing House.
Khurana, Rohit. 2008. Object Oriented Programming with C++. New Delhi:
Vikas Publishing House.
Saxena, Sanjay. 2009. Introduction to Information Technology. New Delhi:
Vikas Publishing House.

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

After going through this unit, you will be able to:


NOTES x Understand the concept of classes and objects
x Explain objects and arrays
x Understand the concept of const with classes and const member
functions
x Define nesting and nesting of member functions

4.2 CLASSES AND OBJECTS

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.

4.2.2 Defining Member Functions


Member functions of a class can be defined either outside the class definition or
inside the class definition. In both the cases, the function body remains the same;
however, the function header is different.
Outside the Class
Defining a member function outside a class requires the function declaration (function
prototype) to be provided inside the class definition. The member function is
declared inside the class like a normal function. This declaration informs the compiler
that the function is a member of the class and that it has been defined outside the
class. After a member function is declared inside the class, it must be defined

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().

4.3 MAKING AN OUTSIDE FUNCTION INLINE


For larger functions, putting the code directly in the class definition can lead to very
large class definitions. To prevent this, C++ lets you to define the member functions
outside the class. A function that is defined outside the class is said to be an outline
function. This term is meant to be the opposite of an inline function that has been
defined within the class. When written outside the class declaration, the Savings.h
file declares the deposit() function without defining it as follows:

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:

The following example is equivalent to the previous example 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

In addition to calling a member function of a class in any non-member function


outside the class, it can be invoked inside another member function of the same
class. The invoked member function is called the nested member function and NOTES
the process is called nesting of member functions. The nested member function
can be invoked directly without using the dot operator.
Program 4.4
A program to demonstrate nesting of member functions.

Self-Instructional
Material 93
Introduction to Class

NOTES

The output of the program is:

In this program, the member function cal_interest() of the class


Interest is invoked inside another member function show_interest()
of the same class. Note that the function cal_interest() is directly invoked
without using the dot operator.
4.4.2 Nested Class
A class that is defined inside another class is known as a nested class. A nested
class (inner class) has a local scope inside the class (enclosing class) that contains
its definition.
The syntax for defining a nested class is as follows:

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.

4.5 ARRAYS WITHIN A 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

The output of the program is:

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.

Fig. 4.1 Memory Allocation for the Object stu

Check Your Progress


1. What are access specifiers?
2. Write any one advantage of inline function.
3. What is nested class?

4.6 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. The keywords private, public and protected are known as


access specifiers (also known as visibility mode).
2. Inline function is the optimization technique used by the compilers. One can
simply prepend inline keyword to function prototype to make a function
inline.
3. A class that is defined inside another class is known as a nested class.

4.7 SUMMARY

x 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.
x Member functions of a class can be defined either outside the class definition
or inside the class definition. Self-Instructional
Material 97
Introduction to Class x Defining a member function outside a class requires the function declaration
(function prototype) to be provided inside the class definition. The member
function is declared inside the class like a normal function.
x Member function of a class in any non-member function outside the class, it
NOTES
can be invoked inside another member function of the same class. The
invoked member function is called the nested member function.
x Arrays can be declared as the members of a class. They can be declared as
private, public or protected members of the class.
x A class that is defined inside another class is known as a nested class. A
nested class has a local scope inside the class that contains its definition.
x A class is a user defined data type that binds data and the functions that
operate on the data together in a single unit.

4.8 KEY WORDS

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

4.9 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. What is a class?
2. How is a member function declared?
3. What is instantiation?
4. Write the syntax for defining a const member function.
5. Write the syntax for defining a member function of a nested class outside
the enclosing class.
Long Answer Questions
1. Explain the concept of specifying a class and defining member functions
with the help of C++ statements.

Self-Instructional
98 Material
2. Explain the definition of member functions outside and inside the class with Introduction to Class

the help of examples.


3. Write a program to demonstrate the concept of classes and objects in C++.
NOTES
4.10 FURTHER READINGS

Jeyapoovan, T. 2006. Computer Programming: Theory and Practice (with


CD). New Delhi: Vikas Publishing House.
Khurana, Rohit. 2008. Object Oriented Programming with C++. New Delhi:
Vikas Publishing House.
Saxena, Sanjay. 2009. Introduction to Information Technology. New Delhi:
Vikas Publishing House.

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

After going through this unit, you will be able to:


x Understand the significance of static data member and functions NOTES
x Discuss the concept of friend functions and friend class
x Explain the concept of array of objects
x Discuss how will a function return the object

5.2 CREATING 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.

5.2.1 Memory Allocation for Objects


Before using a member of a class, it is necessary to allocate the required memory
space to that member. The method in which memory space for data members and
member functions is allocated is different even though both data members and
member functions belong to the same class.
Memory space is allocated to the data members of a class only when an
object of the class is declared and not when the data members are declared inside
the class. Since a single data member can have different values for different objects
at the same time, every object declared for the class has an individual copy of all
the data members.
On the other hand, memory space for the member functions is allocated
only once when the class is defined. In other words, there is only a single copy of
each member function which is shared among all the objects. For instance, the
three objects, namely, book1, book2 and book3 of the class book (defined
in Example 5.1) have individual copies of the data members title and price.
However, there is only one copy of the member functions getdata()and
putdata() that is shared by all the three objects as shown in Figure 5.1.

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:

The syntax for calling a public member function 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

The output of the program is:

Static Members of a Class


The data members and member functions of a class can be declared as static.
Unlike non-static members, the static members are associated with the class as a
whole, rather than with individual objects, however, are accessible by any of them.
The static members can be accessed even before any object of the class is declared.
Self-Instructional
Material 105
Memory Allocation In this section you will learn how static members are declared, defined and accessed
for Objects
in a class.
5.2.3 Static Data Members
NOTES As discussed earlier, each object of the class contains its own copy of data members.
However, if a class data member is declared as static, only one copy of that data
member is created, regardless of the number of objects. All the objects of a class
share the single copy of the static data member. Hence, 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. Like a normal static variable, a static data member is visible only
within the class but continues to exist in the memory until the program terminates.
Since the static data members contain the properties of a class and not of the
individual objects, they are also known as class variables.
Note: As static data members are independent of any particular object of the class, the
const member functions can modify their values.
Any data member that needs to be defined as static is declared inside the
class, however, defined outside the class. Declaring and defining inside and outside
respectively emphasizes the fact that static data member is stored separately from
the objects and can be accessed even before the declaration of the object.
Moreover, the memory space for a static data member is allocated only when the
member is explicitly defined outside the class.
To declare a static data member inside a class, the static keyword is prefixed
to the data type of the data member. The syntax for declaring a static data member
is as follows:

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

NOTES The output of the program is:

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).

Fig. 5.2 Sharing of Static Data Member


Note: If a static data member is declared as a public member of the class then it can be
accessed directly from outside the class using either class name and scope resolution operator
(::) or object name and dot operator (.).

Static Data Members of a Nested Class


Like member functions of a nested class, the static data members of a nested class
also need to be defined outside the enclosing class. The syntax for defining a static
data member of a nested class outside the enclosing class is as follows:

To understand this concept, consider this code segment.

Self-Instructional
108 Material
Memory Allocation
for Objects

NOTES

5.2.4 Static Member Functions


The member functions declared as static can access only other static data members
and static member functions of the same class. Static member functions are defined
by prefixing the keyword static to their return type in the header of their
definition inside the class.
The syntax for defining a static member function inside the class definition is as
follows:

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

The output of the program is:

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:

Program 5.7: A program to demonstrate the concept of array of objects

Self-Instructional
Material 111
Memory Allocation
for Objects

NOTES

In this program, an array of the type class and three is


declared. This implies that is an array of three objects of the class .
Note that every object in the array can access public members of the class
in the same way as any other object, that is, by using the dot operator. For example,
the statement invokes the function
th
for the i element of the array book.
When an array of objects is declared, the memory is allocated in the same
way as to multi-dimensional arrays. For example, for the array a separate
copy of and is created for each member
and However, member functions are stored at a different
place in memory and shared among all the array members. For instance, the memory
Self-Instructional
112 Material
space is allocated to the array of objects of the class as shown Memory Allocation
for Objects
in Figure 5.3.

NOTES

Fig. 5.3 Memory Allocation of the Array

5.4 OBJECTS AS FUNCTION ARGUMENTS

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
object is destroyed when the function terminates. Moreover, any changes made to
the copy of the object inside the function are not reflected in the actual object. On
the other hand, in pass by reference, only a reference to that object (not the entire
object) is passed to the function. Thus, the changes made to the object within the
function are also reflected in the actual object.
Whenever an object of a class is passed to a member function of the same
class, its data members can be accessed inside the function using the object name
and the dot operator. However, the data members of the calling object can be
directly accessed inside the function without using the object name and the dot
operator.
Note: The non-member functions can access only the public members of the
class with the help of objects passed as arguments and the private data
members are not accessible to them.
Program 5.8: A program to demonstrate passing objects by value to a member
function of the same class

Self-Instructional
Material 113
Memory Allocation
for Objects

NOTES

The output of the program is


Self-Instructional
114 Material
Memory Allocation
for Objects

NOTES

In this program, the function has direct access to the data


in this case). However, the members of the objects
passed as arguments ( and ) can be accessed within function using the
object name and the dot operator. Note that the objects and are passed
by value; however, they can be passed by reference also. For example, to pass
and by reference to the function sum_weight() (defined in Program
5.8), the function will be declared and defined as follows:

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

Fig. 5.4 Accessing Data Members within Called Member Function

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:

Program 5.9: A program to demonstrate the concept of returning objects from a


function

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

Fig. 5.5 Result returned from Temporary Object temp

In case of returning an object by reference, no new object is created; rather, a


reference to the original object in the called function is returned to the calling
function. The syntax for defining a function that returns an object by reference is as
follows:

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.

Check Your Progress


1. When memory is allocated to the data members of a class?
2. How will you define the static member functions?
3. What are array of objects?

5.6 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. Memory space is allocated to the data members of a class only when an


object of the class is declared and not when the data members are declared
inside the class.
2. Static member functions are defined by prefixing the keyword static to their
return type in the header of their definition inside the class.
3. The array of type class contains the objects of the class as its individual
elements. Thus, an array of class type is also known as array of objects.

5.7 SUMMARY

x 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.
x An object is an instance of a class, the process of declaring an object of a
class is known as instantiation.
x The data members and member functions of a class can be declared as
static. static members are declared, defined and accessed in a class.
x Any data member that needs to be defined as static is declared inside the
Self-Instructional class, defined outside the class. Defining inside and outside respectively
118 Material
emphasizes the fact that static data member is stored separately from the Memory Allocation
for Objects
objects and can be accessed even before the sdeclaration of the object.
x The member functions declared as static can access only other static data
members and static member functions of the same class. Static member
NOTES
functions are defined by prefixing the keyword static.
x An array of type class can also be created. The array of type class contains
the objects of the class as its individual elements. Thus, an array of class
type is also known as array of objects.
x A function can also return objects either by value or by reference. When an
object is returned by value from a function, a temporary object is created
within the function, which holds the return value.

5.8 KEY WORDS

x Friend Functions: A non-member function that is made a friend of a class.


x Friend Class: A class that is made of another class.
x Objects: The physical entities through which those data and functions can
be used in a program.

5.9 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. Write the syntax of declaring objects of a class.
2. What are array of objects?
3. How can the objects of a class be passed?
4. Name the keyword which is used to declare the friend function.
5. What is a friend class?
Long Answer Questions
1. Explain the process of allocating memory for objects and access members
of a class?
2. Write a program to demonstrate the concept of accessing private members
of a class
3. Write a program to demonstrate the concept of arrays as class members
and array of objects.

Self-Instructional
Material 119
Memory Allocation
for Objects 5.10 FURTHER READINGS

Jeyapoovan, T. 2006. Computer Programming: Theory and Practice (with


NOTES CD). New Delhi: Vikas Publishing House.
Khurana, Rohit. 2008. Object Oriented Programming with C++. New Delhi:
Vikas Publishing House.
Saxena, Sanjay. 2009. Introduction to Information Technology. New Delhi:
Vikas Publishing House.

Self-Instructional
120 Material
Constructors and

UNIT 6 CONSTRUCTORS AND Destructors

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

After going through this unit, you will be able to:


x Explain the significance of constructor and destructors
x Discuss the concept of copy constructors
x Explain dynamic constructor
x Understand the features of destructors
x Explain dynamic initialization of objects Self-Instructional
Material 121
Constructors and
Destructors 6.2 CONSTRUCTORS AND DESTRUCTORS: AN
INTRODUCTION

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

The output of the program is:

In this program, the class library has a parameterized constructor that


accepts three parameters r, n[] and b. The objects lib1 and lib2 are
declared and initialized with different values. The object lib1 calls the
parameterized constructor implicitly whereas the object lib2 calls the
parameterized constructor explicitly.
Self-Instructional
Material 125
Constructors and Note that an explicit call to this constructor can also be made by using the
Destructors
statement library(2,”Mansi”,102).show()which allows to create
a temporary instance of a class. A temporary instance or a temporary object
remains in the memory as long as the statement is being executed. Once the
NOTES execution of the statement terminates, the temporary instance is destroyed.
Note: The temporary instances do not have any name and, hence, cannot be referred to
further in the program. They are automatically deleted when no longer required.
A special case of parameterized constructors is one-parameter constructor that
provides another way to initialize the objects of a class. In one-parameter constructor,
the objects of a class are initialized using the assignment operator ‘=’. Such
constructor automatically converts the parameter of any type into class type to
which it is assigned.
Program 6.3
A program to demonstrate the concept of one-parameter constructor.

The output of the program is:

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.

6.2.3 Multiple Constructors with Default Arguments


Like other member functions, parameterized constructors can also have default
arguments. These arguments are used when no corresponding value is passed at
the time of declaration of the object. When a parameterized constructor is defined
inside the class, the values for the default arguments are provided in the definition
of the constructor. However, when the parameterized constructor is defined outside
the class, the values for the default arguments are provided only in its prototype
and not in its definition.
Program 6.4
A program to demonstrate a parameterized constructor with default arguments.

Self-Instructional
Material 127
Constructors and
Destructors

NOTES

The output of the program is:

In this program, 30 is provided as a default argument for the third parameter in


the constructor test(). First, the constructor is called with only two arguments.
Self-Instructional
128 Material
Since the third argument is missing in the call to the constructor, the default value Constructors and
Destructors
(30) is used to initialize the data member ss. However, in the second call, all the
three values are provided.
The parameterized constructor that has all the default arguments can be
considered as a default constructor since it can be invoked without arguments. NOTES
This implies that if an object is declared without parentheses, all the data members
are initialized with the default values. For example, a default argument constructor
of the form time::time(int=10,int=20,int=30) can be called
with zero or more arguments. If no argument is specified, it can be considered as
a default constructor of the form time::time().

Check Your Progress


1. Define constructor.
2. What are the two ways of calling a constructor?

6.3 COPY CONSTRUCTOR

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

NOTES In this code segment, the statement class_name(class_name&


object_name)is of the form X(X&)and is pronounced as “X of X ref”.
A reference to the existing object is passed as an argument to the copy constructor
to initialize a new object. Note that the existing object cannot be passed by value,
as it requires creating a copy of the object by the copy constructor itself. Since the
copy constructor is already being executed, passing an object by value results in a
recursive call to the copy constructor till the compiler runs out of memory.
Note: Copy constructor can have additional parameters provided they are default parameters.
However, the first parameter must be a reference to the existing object.
While defining the copy constructor, it is recommended to specify the
keyword const for the reference parameter. This is because the existing object
is used only to initialize the new object and cannot be changed by the copy
constructor. Thus, the code segment can be written as follows:

To use a copy constructor in a program, it is necessary to provide either default or


parameterized constructor explicitly to initialiae the object that is passed to the
copy constructor.
Program 6.5
A program to initialize one object with another by calling the copy constructor.

Self-Instructional
130 Material
Constructors and
Destructors

NOTES

The output of the program is:

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.

Fig. 6.1 Shallow Copy

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.

Fig. 6.2 Deep Copy


Note: A copy constructor is not invoked when an object is assigned to another object,
instead the default assignment operator is invoked.

6.4 DYNAMIC CONSTRUCTOR

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

The output of the program is:

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:

The output of the program is:

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.

6.6 INVOKING CONSTRUCTORS AND


DESTRUCTORS

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

The output of the program is

Check Your Progress


3. Define copy constructor.
4. What is a destructor?
5. Which constructor can be used for dynamic initialisation of objects?

Self-Instructional
Material 139
Constructors and
Destructors 6.7 ANSWERS TO CHECK YOUR PROGRESS
QUESTIONS

NOTES 1. 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.
2. Once a constructor is defined, it can be called implicitly as well as explicitly.
3. 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.
4. A destructor releases the resources and memory at runtime to clean up the
unused storage area.
5. Parameterized constructors can also be used to dynamically initialize the
objects of a class.

6.8 SUMMARY

x 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.
x 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.
x 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.
x A dynamic constructor is a constructor that allocates memory to the objects
at the time of their construction using the new operator.
x the memory allocated to objects must be released when an object is
destroyed. This is accomplished by another special member function called
destructor.
x The parameterized constructor can initialize the object with the values
provided by the user at runtime.
x A special case of parameterized constructors is one-parameter constructor
that provides another way to initialize the objects of a class.

6.9 KEY WORDS

x Parameterized Constructor: It 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.

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

6.10 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. Write a note on constructor.
2. What are default constructors?
3. What is the significance of parameterized constructors?
4. Write the syntax to define a copy constructor.
Long Answer Questions
1. Write a program that illustrates the invoking of constructor implicitly and
explicitly.
2. Write a program to initialize one object with another by calling the copy
constructor.
3. Explain the concept of dynamic constructor.
4. Explain the concept of dynamic initialization of objects.

6.11 FURTHER READINGS

Jeyapoovan, T. 2006. Computer Programming: Theory and Practice (with


CD). New Delhi: Vikas Publishing House.
Khurana, Rohit. 2008. Object Oriented Programming with C++. New Delhi:
Vikas Publishing House.
Saxena, Sanjay. 2009. Introduction to Information Technology. New Delhi:
Vikas Publishing House.

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

After going through this unit, you will be able to:


Self-Instructional x Explain the concept of inheritance
142 Material
x Discuss the various types of inheritance Inheritance

x Understand the order of calling constructor and destructor


x Differentiate between containership and inheritance
NOTES
7.2 INHERITANCE

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.

Fig. 7.1 Inheritance

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.

Fig. 7.2 Members of a Derived Class

As stated earlier, inheritance allows creating a logical relationship between two or


more classes. Depending on the number of classes involved and the way the
classes are inherited, inheritance can be of several types. The different types of
inheritance in C++ are single inheritance, multilevel inheritance, hierarchical
inheritance, multiple inheritance and hybrid inheritance.

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.

Fig. 7.3 Single Inheritance


Note: Programs discussed so far are the examples of single inheritance.

7.2.2 Multilevel Inheritance


When one class is inherited from another class, which in turn is inherited from
some other class, it is referred to as multilevel inheritance. Multilevel inheritance
comprises two or more levels. However, in this unit, only two levels of multilevel
inheritance are discussed.
The derived class is inherited from the direct base class which in turn is
derived from another base class. Hence, the derived class has all the members of
its direct base class as well as its indirect base class. This is known as the transitive
nature of multilevel inheritance. Figure 7.4, for example, shows a multilevel
inheritance in which the base class person is inherited by the derived class employee
which in turn becomes the base class of another derived class faculty. Hence,
person is the indirect base class of faculty.

Fig. 7.4 Multilevel Inheritance

The syntax to implement multilevel inheritance is as follows:

Self-Instructional
144 Material
Inheritance

NOTES

7.2.3 Multiple Inheritance


When a derived class inherits from more than one base class simultaneously, it is
referred to as multiple inheritance. In multiple inheritance, the derived class inherits
the members of all its base classes and can directly access the public and the
protected members of its base classes. Figure 7.5 shows multiple inheritance in
which the derived class owner is inherited from two base classes, namely person
and company.

Fig. 7.5 Multiple Inheritance

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

The output of the program is:

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.

Fig. 7.6 Hierarchical Inheritance

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

7.2.5 Hybrid Inheritance


According to the user requirement, the various types of inheritance can be combined
in a program. Such inheritance is called hybrid inheritance. Figure 7.7, for example,
shows hybrid inheritance that involves multilevel and multiple inheritances.

Fig. 7.7 Hybrid Inheritance

Program 7.2
A program to demonstrate hybrid inheritance.

Self-Instructional
148 Material
Inheritance

NOTES

Self-Instructional
Material 149
Inheritance

NOTES

The output of the program is:

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

Various types of inheritance can be combined to form a hybrid inheritance. In


NOTES some hybrid inheritance an ambiguity arises when the derived class directly accesses
a member of its indirect base class. This ambiguity can be resolved by qualifying
the member with the name of either of the direct base classes using the scope
resolution operator. Though the scope resolution operator enables to refer to
specific class for accessing its members, it does not prevent the duplication of
indirect base class members. The duplication of inherited members due to multiple
paths can be avoided by making common base class as virtual base class while
declaring intermediate base class.
Virtual base class is an indirect base class declared using the keyword
virtual in order to prevent its duplication. Specifying a base class as virtual
ascertains that only one copy of the base class members exists for its derived
classes. In other words, the virtual base class can be derived several times without
its duplication. The syntax for specifying a virtual base class is as follows:

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

The output of the program is

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

Check Your Progress


1. What are the different types of inheritance?
2. What is virtual base class? NOTES

7.4 ABSTRACT CLASSES

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

The output of the program is

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

The output of the program is

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

base_class2(parameter_list2)and so on are the explicit calls to


the base class constructors.
Note: In case of multiple inheritance, the parameterized constructor of the
NOTES
base classes are called in the order in which they are specified in the derived class
definition and not in the order in which they are called in the header of the derived
class constructor.
Program 7.7: A program to demonstrate the calling of a parameterized constructor
of the base class

Self-Instructional
Material 159
Inheritance

NOTES

The output of the program is

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.

7.5 MEMBER CLASSES: NESTING OF CLASSES

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

In this program, the object edu1 of the class edudetail is declared in


the class employee. The public data member degree of the class
edudetail can be accessed with the help of object edu1. However, the
protected data member school is inaccessible.
7.5.1 Containership versus Inheritance
Containership and inheritance facilitate the implementation of different real-world
relationships through various classes. However, both differ in the type of relationship
that they implement. Containership implements ‘has-a’ relationship, whereas
inheritance implements the ‘is-a-kind-of’ relationship. Containership is appropriate
in a situation where one real-world object has or contains another real-world
object, whereas inheritance is appropriate in a situation where one real-world
object is a special kind of some other real-world object.

Self-Instructional
162 Material
Inheritance

NOTES

Fig. 7.8 Containership and Inheritance

Figure 7.8(a) is an example of containership that depicts ‘has-a’ kind of relationship.


Here, the class employee ‘has-a’ object edu1 of the class edudetail.
Figure 7.8(b), is an example of inheritance that depicts ‘is-a-kind-of’ relationship.
That is, manager ‘is-a-kind-of’ employee. The differences between
containership and inheritance are listed in Table 7.1.
Table 7.1 Difference between Containership and Inheritance

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.

Check Your Progress


3. What is an abstract class?
4. What do you understand by nesting of classes?

7.6 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. The different types of inheritance in C++ are single inheritance, multilevel


inheritance, hierarchical inheritance, multiple inheritance and hybrid
inheritance.
2. Virtual base class is an indirect base class declared using the keyword it in
order to prevent its duplication.
3. A class that contains at least one pure virtual function is known as an abstract
class or abstract base class.
Self-Instructional
Material 163
Inheritance 4. When a class has an object of another class as its member it is known as
nesting of classes or containership.

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.

7.8 KEY WORDS

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.

7.9 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. What do you understand by the base and derived class?
2. Define abstract classes.
3. Differentiate between containership and inheritance.
Long Answer Questions
1. Explain the different types of inheritance.
2. How will you define the derived class?

Self-Instructional
164 Material
3. Explain the concept of virtual base classes. Inheritance

4. Explain the order of calling the constructor and destructor in case of


inheritance.
NOTES
7.10 FURTHER READINGS

Jeyapoovan, T. 2006. Computer Programming: Theory and Practice (with


CD). New Delhi: Vikas Publishing House.
Khurana, Rohit. 2008. Object Oriented Programming with C++. New Delhi:
Vikas Publishing House.
Saxena, Sanjay. 2009. Introduction to Information Technology. New Delhi:
Vikas Publishing House.

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

After going through this unit, you will be able to:


x Define pointer
x Discuss the pointer declaration and initialization
x Understand the concept of pointer to objects
Self-Instructional
166 Material
x Explain compile time and runtime polymorphism Pointers, Virtual Functions
and Polymorphism
x Explain the significance of virtual functions

8.2 POINTERS AND POLYMORPHISM NOTES

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:

Fig. 8.1 Initializing a Pointer ptr

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.

The declaration and initialization of a pointer to data member can be performed


together using a single statement as follows:

In this statement, the expression emp::*ptr denotes ‘pointer-to-member of


class emp’ and the expression &emp::emp_no denotes ‘address of member
emp_no of class emp’. Note that both the pointer and the data member must
be qualified with the class name using the scope resolution operator (::).
After declaring and initializing a pointer to data member, its contents can be
accessed with the help of the ‘.*’ operator. The syntax for accessing a public
data member using the object and the pointer to that member is as follows:

For example, consider the following statements:

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:

Note: In the expression (*eptr).display(), parentheses must be specified around


the object pointer as the ‘.’ operator has higher precedence than the ‘*’ operator.
However, if in addition to an object pointer, pointers to class members (say
ptr to emp_no and fptr to display()) are also declared, the ‘->*’
operator is used with the object pointer to access the members. 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

The output of the program is:

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

The output of the program is:

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.

8.2.4 Pointers to Derived Classes


A pointer to a derived class object is assigned to a base class pointer and a virtual
function called through the pointer. If the function is virtual and occurs both in the
base class and in derived classes, then the right function will be picked up based
on what the base class pointer really points at.
Self-Instructional
Material 173
Pointers, Virtual Functions Program 8.4
and Polymorphism
A program to demonstrate function of pointers to derived class.

NOTES

Self-Instructional
174 Material
Pointers, Virtual Functions
and Polymorphism

NOTES

The output of the program is:

8.2.5 Compile-Time Polymorphism


Poly means ‘Many’. Polymorphism is one of the features of OOPS. It simply
means one name many forms. The concept of polymorphism is implemented using
overloaded function and operator. Polymorphism is a mechanism to use a single
name with multiple forms. Figure 8.2 displays the structure of polymorphism which
is categorized as compile-time polymorphism and runtime polymorphism.

Fig. 8.2 Compile Time and RunTime Polymorphism

Examples of compile-time polymorphism are function overloading and operator


overloading whereas example of runtime polymorphism is virtual function.
In compile time of polymorphism, the selection of the function invocation is
done on compile-time. This is also called early binding or static binding. This can
be achieved by two ways which are known as function overloading and operator
overloading. The compile-time polymorphism is implemented with templates.
Compile-time polymorphism is also known as static binding and runtime
Self-Instructional
Material 175
Pointers, Virtual Functions polymorphism is also known as runtime binding. Compile-time polymorphism is
and Polymorphism
achieved using operator and function overloading as shown in code below:

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

The output of the program is:

8.3 VIRTUAL FUNCTIONS

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 this class definition, the function display() of the class base is


declared virtual. Thus, the display() function can be redefined in the
derived classes of the class base.
Note: If the virtual function is declared inside and defined outside the base
class, then the keyword virtual is not required in the function definition.
Whenever a virtual function is inherited, its virtual nature is also inherited
into all its derived classes and it is not required to use the keyword virtual in
the subsequent derived classes. For example, consider the following derived 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

The output of the program is

In this program, the functions getdata() and display() of the


base class person are declared as virtual and are overridden in the derived
Self-Instructional
Material 181
Pointers, Virtual Functions classes emp and stu. An array of pointers ptr to person is declared in
and Polymorphism
main() and depending on the user’s choice, the elements of ptr point to the
objects of either emp or stu class. Note that whenever ptr points to the
object of emp class, the functions getdata() and display() of the emp
NOTES class are called. Similarly, the functions getdata() and display() of the
stu class are called when ptr points to the object of the stu class.
Note: A class that declares or inherits a virtual function is called
polymorphic class and the objects of such a class are called polymorphic
objects.
Some more points regarding virtual functions are as follows:
x The base class virtual function and its redefined versions in the derived
classes must have the same prototype. However, if the prototype differs,
the compiler considers these functions as overloaded functions and the
virtual function mechanism is ignored.
x A virtual function cannot be global or static; however, it can be declared
as a friend function of another class.
x The constructors of a base class cannot be made virtual since at the time
the constructor is invoked, the virtual table is not available in the memory.
However, the destructors can be made virtual.
x On incrementing or decrementing the pointer of base type, it will always
point to the next or the previous object, respectively, of its base class
type irrespective of the contents of the pointer.
8.3.2 Virtual Function Call Mechanism
For each class containing at least one virtual function, a v-table (pronounced as
virtual table) is constructed in the memory by the compiler. The v-table contains
the base addresses of all the virtual functions defined in the class. Each object of
the class (containing one or more virtual functions) contains a vptr (pronounced
as virtual pointer) in the beginning of the object in the memory that points to the v-
table in the memory (see Figure 8.3). Note that if a virtual function is not overridden
in the derived class, the v-table of derived class contains the address of the function
defined in the base class.

class object v-table


virtual func1()
virt_func1_ptr
vptr
virtual func2()
virt_func2_ptr
virtual func3()
virt_func3_ptr

Fig. 8.3 Virtual Table in Memory

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:

To understand the concept of pure virtual functions, consider Program 8.6.


In this example, the virtual function display() of the class person is defined
without a body. Moreover, this function has never been called within the program.
Thus, display() can be made a pure virtual function.
Program 8.7: A code segment to demonstrate pure virtual function

Note that if a virtual function is declared as pure, it must be redefined in all


of its derived classes; otherwise, a program error occurs. In addition, a virtual
function cannot have both the pure specifier and the definition.

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?

8.4 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

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

x A pointer is a variable that contains the address of another variable or a


literal. In other words, a pointer ‘points to a location in the memory.
x The compiler match a function call with the correct function definition at
runtime; this is called Dynamic Binding.
x A pointer to an object of a class is known as object pointer.
x A pointer to a derived class object is assigned to a base class pointer and a
virtual function called through the pointer.
x Runtime polymorphism can be achieved using virtual functions. In virtual
function mechanism, any derived class function can be called using Base
class pointer.
x A virtual function is a member function that is declared inside the base class
and its functionality can be overridden in the derived classes.
x A class that declares or inherits a virtual function is called polymorphic class
and the objects of such a class are called polymorphic objects.

8.6 KEY WORDS

x Reference Operator: It is a unary operator that returns the address of a


variable stored in the memory.
x Object Pointer: It is a pointer to an object of a class.
Self-Instructional
184 Material
x This Pointer: It is a special pointer that contains the address of an object Pointers, Virtual Functions
and Polymorphism
of a class currently calling the member function of the class.

8.7 SELF ASSESSMENT QUESTIONS AND NOTES


EXERCISES

Short Answer Questions


1. Write a note on pointer.
2. What do you understand by the static and dynamic binding?
3. What is pointers to objects?
4. Write a note on virtual function.
Long Answer Questions
1. Explain the pointer declaration and initialization with a code segment.
2. Write a program to demonstrate the concept of pointer to objects.
3. Explain the significance of this pointer.
4. What do you understand by the compile time and runtime polymorphism?
Explain.

8.8 FURTHER READINGS

Jeyapoovan, T. 2006. Computer Programming: Theory and Practice (with


CD). New Delhi: Vikas Publishing House.
Khurana, Rohit. 2008. Object Oriented Programming with C++. New Delhi:
Vikas Publishing House.
Saxena, Sanjay. 2009. Introduction to Information Technology. New Delhi:
Vikas Publishing House.

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

After going through this unit, you will be able to:


x Define the basic concept of streams
x Describe various streams that help in handling I/O operations
x Understand C++ console I/O headers that are used in a program to
Self-Instructional implement streams
186 Material
x Explain how stream extraction and insertion operators handle I/O formatting Managing Console I/O
Operations
implicitly
x List various functions and manipulators used for formatting the data
x Describe various unformatted I/O operators NOTES

9.2 BASIC CONCEPT OF STREAMS


A C++ I/O system is capable of working with a variety of devices such as terminals,
disks, tape drives, etc. Therefore, the need for an interface independent of physical
devices being used arises. Such a common interface is known as stream.
A stream refers to the flow of data in the form of sequence of bytes. A
stream is an interface that acts as the source and destination for the input and
output data, respectively. In C++, streams handle all I/O operations. Streams,
which help to consume data from various sources, namely, keyboard, 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 streams. Figure 9.1 shows the
flow of data between the program and standard I/O devices with the help of
streams.

Fig. 9.1 Streams

9.2.1 Stream Classes


A stream in C++ is represented using an object of a particular stream class. For
example, the standard streams cin and cout are the stream objects. cin is
the input stream object, which represents input stream connected to standard
input devices (keyboard). cout is the output stream object, which represents
output stream connected to a standard output device (monitor).
The C++ I/O library comprises a hierarchy of classes used to define various
streams that help to handle console I/O and file I/O operations. Figure 9.2 shows
the hierarchy of stream classes used to handle console I/O operations.

Self-Instructional
Material 187
Managing Console I/O
Operations

NOTES

Fig. 9.2 Console I/O Stream Classes

The description of various stream classes is given in Table 9.1.


Table 9.1 Stream Classes

Class name Description


ios ƒ a base class for the hierarchy of stream classes.
ƒ declared as a virtual base class for istream and ostream
classes.
ƒ keeps track of the format and error state information for
derived classes. The format state is a collection of flags and
variables that control the formatting of I/O operation. The
error state is collection of flags that records the errors taken
place during the processing of ios object. The error state
also checks the end of input stream.
istream ƒ an input stream class.
ƒ inherits the properties and behaviour of ios class.
ƒ comprises the extraction operator (>>).
ƒ comprises istream objects to extract input from a stream.
ƒ also contains input functions such as get(), getline()
and read().
ostream ƒ an output stream class.
ƒ inherits the properties and behaviour of ios class.
ƒ comprises the insertion operator (<<).
ƒ comprises the ostream object to insert output into the
stream.
ƒ facilitates formatted as well as unformatted output.
ƒ also contains output functions such as put() and write()
that provide unformatted output.
iostream ƒ an input/output stream class.
ƒ inherits the properties from two classes that is, istream and
ostream.
istream_withassign ƒ inherited from istream.
ƒ facilitates objects assignment.
ƒ the stream object cin can be reassigned to different
istream object at the run-time.
ostream_withassign ƒ inherited from ostream class.
ƒ facilitates object assignment.
ƒ the predefined objects such as cout, cerr and clog
reassigned to different ostream objects at run-time.
iostream_withassign ƒ inherited from iostream class.
ƒ facilitates object assignment.
streambuf ƒ a sequence of characters that either grows or shrinks.
ƒ inherited from ios class.
ƒ indirectly used by streams.
ƒ provides buffering capabilities to the streams in order to hide
details of physical I/O devices.
ƒ whenever a stream is created, the streambuf is associated
with it.
Self-Instructional
188 Material
The C++ I/O stream classes have various advantages, which are as follows: Managing Console I/O
Operations
x Stream classes use the concept of inheritance. Thus, the I/O functions
once defined in the base classes are inherited in the derived classes and
overridden whenever required.
x Stream classes facilitate implementation of the new overloaded operators NOTES
and the functions that work like standard functions.
x Unlike C, no format specifiers such as %d, %f, etc. are required.
9.2.2 Managing Console I/O Operations
Streams facilitate the data to be passed in and out of a medium such as a console
or a file. 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 defines the behaviour of the insertion operator (<<),
which is used to direct the output to various destinations such as screen. The
stream class defines some standard stream in the I/O headers to handle the console
I/O operations. This section discusses these standard streams and the I/O headers.
Whenever a C++ program is executed, the input is read from the various
sources and the output is sent to different destinations. However, generally keyboard
and screen are used as standard input and output devices, respectively. The four
standard built-in stream objects, namely, cin, cout, cerr and clog enable the use of
standard input and output devices as shown in Figure 9.3.

Fig. 9.3 Standard Streams

x cin: standard input stream—the standard source of input (usually


keyboard)
x cout: standard output stream—the standard destination for the output
(usually monitor)

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

Header File Description


<iostream> provides standard I/O objects such as cin, cout, etc.
<istream> provides functions for performing basic input
operations
<ostream> provides functions for output stream
<iomanip> provides several manipulators
changes the characteristics of I/O streams

9.3 TYPES OF I/O OPERATIONS


Streams defined in the console I/O headers enable to perform two types of I/O
operations, namely, formatted I/O and unformatted I/O.
9.3.1 Formatted I/O Operations
The I/O operations in which character translation occur is called formatted I/O
operations. The extraction (<<) and insertion (>>) operators handle I/O formatting
implicitly. However, data values can also be formatted (using ios class functions,
special functions called manipulators and user-defined manipulators) explicitly.
Formatting the data values involves setting a field width, number base, the number
of digits, etc.
Stream extraction and insertion operators
The extraction and insertion operators facilitate the I/O operation using standard
stream objects. The extraction operator (>>), also interpreted as the
operator>>() function, is used to extract the characters from the stream.
The extraction operator is also called the input operator. It comprises two
operands, namely, istream object on its left and a variable on its right.
istream object is used to extract the characters, which are copied to the variable.
The prototype of using the extraction operator to read one value is as follows:

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:

treated by the compiler as

For example, consider the following statements:

Fig. 9.4 istream

In these statements, a variable x is declared of type int and its value is


taken from the user. Suppose the input given to the variable x through the keyboard
is ‘ 37R’ (7 characters) as shown in Figure 9.4. The first four characters
are blank spaces succeeded by 3, 7 and R. This input passes through a stream
called istream. The stream object cin scans each character one by one. It
extracts character from the stream, ignoring white space characters (a blank, a
tab, a newline, etc.). Therefore, stream object cin ignores the first 4 blank spaces
and accepts the characters 3 and 7 as the second operand (x) is of integer type.
The stream object leaves the character R in the input stream as it is not of integer
type. The characters 3 and 7 are combined to form an integer value 37 and
assigned to the variable x. The character R remains in the stream and is examined
by the next input operator; however, if the data type does not match, the character
R is ignored.
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 the operator>>() cannot
read white spaces. Note that the operator>>() returns a reference to the
stream object in order to use this return value to call the next operator>>()
function. For example, consider the following statements:

The statement cin>>i>>j is translated into

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:

The prototype of the insertion operator to output multiple values is as follows:

treated by compiler as

Like operator>>(), operator<<() returns a reference to the


stream object, which in turn is used to call the next operator<<(). For
example, consider the following statements:

This statement is translated into

In this statement, the operator<<(m) function returns a reference to


the stream object cout, which in turn is used to call the next operator<<(n)
function.
The insertion operator is overloaded to handle data values of all the built-in
data types and pointers. However, null-terminated string, that is, pointer to type
char is handled as a special case by the insertion operator. The prototypes to
display a null-terminated string are as follows:

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

The output of the program is

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:

The output of these statements is

In these statements, the data value of x occupies three characters space.


The width() function changes the width from 3 to 5. Note that data value of
x occupies 5 spaces (right justified and first two blanks are filled with spaces).
Consider the following statements, which shows the effect of specifying
field width using width() lesser than required.

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 output of these statements is

In these statements, the width is set to 5 spaces; however, the value of x


occupies 3 spaces. Therefore, using the fill() function, the unused spaces
are filled with the specified character ‘*’.
precision() function: The precision() function allows to specify
the precision of floating-point data values. By default, the precision value is 6. The
prototype of the precision() function is as follows:

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

The output of the program is

In this program, width() is used to change the width of a field. fill()


is used to fill the unused space with ‘*’ and the precision() function is
used to set the precision of the percentage field to 3.
setf() and unsetf() functions: The setf() function is used
to set the format flags which are required to change the default format settings of
the data values. Flags (format flags) are used by the streams to control the way
the data values are formatted. They are defined by ios class for standard input and
output and are specified using the class name ios and the scope resolution operator
(::). The format flags values used in I/O functions are listed in Table 9.4.
Note: Flags are also manipulated using unsetf() and flags() functions. Self-Instructional
Material 197
Managing Console I/O Table 9.4 Format Flags
Operations
Flags Description

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.

The prototype for using the setf() function is as follows:

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:

The output of these statements is

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:

For example, consider the following statements:

In these statements, the setf(ios::scientific) function is used


to display floating-point value in scientific notation. However, the
unsetf(ios::scientific) function is used to clear the scientific notation
flag.
The shorthand combination of unsetf() and setf() functions is the
overloaded form of the setf()function. The prototype of overloaded setf()
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:

Program 9.3: A program using setf() function

Self-Instructional
200 Material
Managing Console I/O
Operations

NOTES

The output of the program is

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

The output of these statements is


NOTES

In these statements, precision() is used to set floating-point precision


to 4 digits. cout<<23.23443 and cout<<25.0000003 display output
23.23 and 25, respectively. Note that the trailing zeros after decimal point are
truncated. To display the zeros after 25, the showpoint flag is set using
cout.setf (ios:: show point). It displays 25.00.
Formatting using manipulators
The data values can be formatted using manipulators. Manipulators are the special
functions included in the iomanip header. Manipulators are simple functions
and not member functions; therefore, they are used directly without using the object
name and the dot operator along with the stream. They also enable to set field
width, precision, format flags, flush streams, insert newline, skip white space, etc.
Manipulators have similar functions as that of ios class functions and flags.
However, they are simpler to use. The manipulators used to format the I/O
operations are listed in Table 9.5.
Table 9.5 Manipulators

Manipulators Description Equivalent


setprecision(int n) sets the precision for floating-point precision()
numbers to n digits—the settings remain
until changed
setw(int n) sets the field width for the next output to width()
n characters
setfill(char ch) sets the fill character ch to be used as fill()
padding
setiosflags(long f) sets the format flag setf()
resetiosflags(long clears already specified flags unsetf()
f)
Endl gives same functionality as ‘\n’ newline \n
character—it also flushes stream buffer

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

The output of these statements is


NOTES
Here, the setprecision(4) sets the precision for the floating point
numbers to 4.
setw(int n) function: setw(int n) is used to change the width
of the field. The data values are printed within the characters specified by n. For
example, consider the following statements:

The output of these statements is

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:

The output of these statements is

In these statements, setfill(), which is similar to ios class fill()


function, is used for padding the field width set by the setw() function.
setiosflags() and resetiosflags() functions: The
setiosflags()and resetiosflags()functions are used to set or reset
the flags, which control the output stream format. These functions also use the
same flags defined by the ios class. For example, consider the following statements:

Self-Instructional
Material 203
Managing Console I/O The output of these statements is
Operations

NOTES In these statements, the setiosflag() is used in combination with


flags defined by the ios class. The setiosflag() function enables to set
scientific notation using flag of ios class for the variable n.
Program 9.4: A program to demonstrate the use of manipulators

The output of the program is

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:

The output of these statements is

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,

Program 9.5: A program showing the user-defined manipulators

The output of the program is

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

The output of the program is

In this program, the input manipulator getmenu is created that returns


the reference to stream. The getmenu input manipulator is called in the statement
cin>>getmenu>>ch, which displays the contents in the getmenu
manipulator.
9.3.2 Unformatted I/O Operations
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. Such I/O functions defined in the iostream class
are get(), put(), getline(), read() and write().
get() and put() functions: The get() member function extracts
unformatted data from the stream and is similar to operator >>(). However, get()
includes white spaces. The get()function is used to extract one character or a
sequence of characters. The prototype of the get()function is:

Program 9.7: A program using get() function

Self-Instructional
208 Material
Managing Console I/O
Operations

NOTES

The output of the program is

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

The output of the program is

In this program, cout<<cin.get() statement displays the int value of A,


that is, 65, which is retrieved from the get() function.
The character ch in which the value read by the get()function is stored
(as shown in Program 9.7) can also be passed as an argument. The prototype of
get() function accepting the character ch as argument is as follows:

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

The output of the program is

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:

Program 9.10: A program using getline() function

The output of the program is

read() and write() functions: The read() function reads a


specified number of characters from the input stream (file) to a memory location.
The prototype of the read() function is as follows:

The read() function reads n number of characters and stores in the


pArray. streamsize determines the number of characters to be read. If
the streamsize is not specified, the reading process terminates when the physical
end of file is reached or EOF (End Of File) character is read.
Self-Instructional
Material 211
Managing Console I/O The characters stored in the pArray can be displayed using the write()
Operations
function. The write() function writes the specified number of characters (output)
that is line of text to the invoking stream from the buffer. The prototype of the
write() function is as follows:
NOTES
where,
streamsize = specifies largest number of characters
pArray = acts as a buffer

Program 9.11: A program using read() and write() functions

The output of the program is

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:

The output of these statements is

In these statements, the buffer size specified in write() is greater


than the number of characters that can be read; hence, it displays garbage values
in the remaining buffer spaces.

9.4 OVERLOADING << AND >> OPERATORS


FOR OBJECTS
C++ provides two operators, namely insertion (>>) and extraction (<<) operators
to input and output standard data types. However, these operators cannot be
used with user-defined data types unless they are overloaded. These operators
cannot be overloaded in a way the other unary and binary operators are overloaded.
The following points must always be kept in mind to overload these operators:
x These operators can only be overloaded as friend functions.
x The operator function for the >> operator accepts two arguments: first, the
reference to the istream class and second, the reference to the class for
which it is being overloaded. In addition, it returns the reference to the
istream class.
x The operator function for the << operator accepts two arguments: first, the
reference to the ostream class and second, the reference to the class for
which it is being overloaded. In addition, it returns the reference to the
ostream class.
The syntax for overloading the >> operator is as follows:

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

Check Your Progress


1. What is a stream?
2. What are the two types of console i/o operations?
3. Define manipulators.

9.5 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. A stream refers to the flow of data in the form of sequence of bytes.


2. Streams defined in the console I/O headers enable to perform two types of
I/O operations, namely, formatted I/O and unformatted I/O.
3. Manipulators are the special functions included in the iomanip header.
Manipulators are simple functions and not member functions; therefore,
they are used directly without using the object name and the dot operator
along with the stream.

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.

9.7 KEY WORDS


x Stream: The flow of data in the form of a sequence of bytes.
x Input Streams: Streams that help to consume data from various sources,
namely keyboard, mouse, storage devices, etc. in order to supply it to the
program.
Self-Instructional
216 Material
x Output Streams: Streams that receive data from the program and direct it Managing Console I/O
Operations
to the physical devices or other programs.
x Formatted I/O Operations: The I/O operations in which character
translation occur.
NOTES

9.8 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. What are the differences between C I/O-based systems and C++ I/O-
based systems?
2. What is a stream? What are stream classes?
3. Discuss the differences between formatted and unformatted I/O operations.
4. How the extraction operator works?
Long Answer Questions
1. Explain the differences between getline() and read() functions.
2. Explain read() and write() functions.
3. What are the differences between manipulators and ios member functions?
Explain with an example.
4. Identify the errors in the following programs:
(a) #include<iostream>

(b) #include<iostream>

5. Write the output of the following programs:


Self-Instructional
Material 217
Managing Console I/O
Operations

NOTES

9.9 FURTHER READINGS

Jeyapoovan, T. 2006. Computer Programming: Theory and Practice (with


CD). New Delhi: Vikas Publishing House.
Khurana, Rohit. 2008. Object Oriented Programming with C++. New Delhi:
Vikas Publishing House.
Saxena, Sanjay. 2009. Introduction to Information Technology. New Delhi:
Vikas Publishing House.

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

After going through this unit, you will be able to:


NOTES x Define the concept of file streams
x Differentiate between text and binary files
x Describe the classes specific to disk file I/O operations
x Open and close a file to perform different operations on it
x Explain various modes for opening a file

10.2 FILE STREAMS

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.

Fig. 10.1 File Input and Output Streams

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.

Fig. 10.2 Representation of a Number in Character and Binary Formats

10.2.1 Classes for File Stream Operations


C++ provides different streams to represent different kinds of data flow. Each
stream is associated with a particular class, which contains the member functions
for reading from or writing to the devices. For example, the class,
which is derived from , provides members like extraction operator ( ),
, etc. on console for performing the input-specific operations. The classes
used for the console I/O operations are declared in the header < .
However, the classes specific to the disk file I/O operations are known as
file stream classes and declared in the header < . The header
< defines several classes, including , and
, which are used for working with files. These classes are derived
from , and , respectively, which in turn are
derived from class (see Figure 10.3). Thus, the file-specific classes can have
access to all the member functions of . In addition, the file-specific classes
are also derived from class. The class contains
the object of class , which also inherits member functions of the class
.

Self-Instructional
Material 221
Introduction to Files

NOTES

Fig. 10.3 C++ Stream Class Hierarchy

The description of all file-specific classes is as follows:


x : The is an input file stream class, which provides
functions for performing the reading operations only. It contains functions,
such as , , , ,
which are derived from the class.
x : The is an output file stream class, which provides
functions for performing the writing operations only. It contains functions,
such as , , , which are derived
from the class.
x : The is an I/O file stream class and hence, provides
functions for performing the input as well as output operations. It contains
all the functions of and classes, which are inherited
through the class.
x : The class is used to manage the buffered I/O of
file stream. It contains and functions.
x : The class serves as a base class for
, and classes. It contains
and functions and also other operations, which are common to
all file streams.

Check Your Progress


1. What are the two types of file stream?
2. Name the various modes by which data can be transferred to and from
streams.

Self-Instructional
222 Material
Introduction to Files
10.3 OPENING AND CLOSING A FILE

To perform any operation on a file, it needs to be opened first. A file is opened by


linking it to a stream. Thus, for opening a file, an object of the particular stream NOTES
class is created first and then associated with the file. The stream class to be used
for creating the stream object depends on the type of operations to be performed
on the file. For example, to read data from a file, an object of is
required; to write data to a file, an object of is required and to
perform reading and writing to a file, an object of is required. A file
can be opened in two ways, that is, either by using the constructor or by using the
member function of the stream class.
Note: In C++, each file is an object of a particular stream class.
10.3.1 Opening a File using the Constructor
When a file is opened using the constructor of a stream class, the file name is
passed to it as an argument. Thus, the constructor initializes the stream object with
the file name passed to it. The syntax for opening a file using the constructor is as
follows:

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:

In this statement, an object of the class (input file


stream) is created and initialized with the file . Thus, the object
can be used only to read data from the file .
Similarly, a file named can be opened for output using
constructor shown as follows:

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:

For example, consider the following statements:

A stream object, created once using the function, can be linked


repeatedly with different files. Hence, it helps in managing multiple files without the
overhead of creating a new stream object each time.
Sometimes, opening a file (either using constructor or the method)
fails due to some reason. In that case, the value of the associated stream evaluates
to false. Thus, before performing any operation on a file, it is necessary to know
whether the file is successfully opened or not. This can be accomplished by using
the function , which is a member function of the classes ,
. The prototype of 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:

10.3.4 Closing a File


When a stream object goes out of scope, the destructor of the object is invoked
implicitly, which closes the associated file automatically. However, a file can also
be closed explicitly by using the function , which is a member function
of the class. The function takes no parameter and
returns no value. The syntax for explicitly closing a file is 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.

10.4 DETECTING END-OF-FILE


NOTES
While reading data from the file, the end position of the file is required to be
detected so that any further attempt to read data from the file can be prevented.
When the end of file is encountered, a signal end-of-file (EOF) is sent to the
program by the operating system. This signal can be detected by using the function
, which is a member function of the class. The use of the function
is as follows:

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.

Check Your Progress


3. What does file mode specify?
4. What happened when the end of file is encountered?

10.5 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. Depending on the flow of data from a file or to a file, a stream can be


classified into two types i.e. input and output stream.
Self-Instructional
Material 227
Introduction to Files 2. There are two modes by which data can be transferred to and from streams:
text mode and binary mode.
3. The file mode 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.
NOTES
4. When the end of file is encountered, a signal end-of-file (EOF) is sent to the
program by the operating system.

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.

10.7 KEY WORDS

x File Stream: The flow of data between a program and files.


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.
x Text file: A file which is opened in the text mode.
x Binary File: A file which is opened in the binary mode.

10.8 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. Write a short note on file stream.
2. Discuss the C++ class stream hierarchy.
3. Write the syntax for opening and closing a file.

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?

10.9 FURTHER READINGS

Jeyapoovan, T. 2006. Computer Programming: Theory and Practice (with


CD). New Delhi: Vikas Publishing House.
Khurana, Rohit. 2008. Object Oriented Programming with C++. New Delhi:
Vikas Publishing House.
Saxena, Sanjay. 2009. Introduction to Information Technology. New Delhi:
Vikas Publishing House.

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

After going through this unit, you will be able to:


x Understand sequential input and output operations
x Read and write data to and from a file using formatted as well as unformatted
I/O operations
x Manipulate file pointers
x Access a file randomly

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

In this program, an object of class is created for


output only and is initialized with the file name . The insertion
operator is used with stream object to insert data into the file.
Since integers are stored as a sequence of characters, a delimiter is required to
identify the starting and ending of an integer while reading the file using the extraction
operator. Thus, the integers and are separated by space. Similarly, the strings
(stored in ) and
are separated by space.
When this program is executed, the data is written to the file. Thus, no
output is displayed on the screen. However, the data of file can
be seen by using the text editor or the command of DOS.
Note: The header includes header; thus, there is no need to include
header explicitly in a program.
Program 11.2: A program to demonstrate reading data from a file using the insertion
operator

Self-Instructional
232 Material
File Pointers and their
Manipulations

NOTES

The output of the program is

In this program, an object of the class is created


for input only and is initialized with the file name . The extraction
operator is used with the stream object to extract data from the file.
Character I/O: using and
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. The function has many forms;
however, the commonly used form along with the the form of function is
shown as follows:

The function reads a single character from the associated stream


and puts that value in and the function writes the value of to the
stream. Both the functions return a reference to the stream.

Self-Instructional
Material 233
File Pointers and their Program 11.3: A program to demonstrate the use of
Manipulations

NOTES

The output of the program is

In this program, a single program is used for performing output as well as


input operations in a file instead of writing two different programs as in Program
11.1 and Program 11.2. The statement extracts
a single character from the array and writes it to the file
using stream. While the statement extracts a
single character from file using stream object and
stores it in until the end of file is reached that is checked by using the statement
. Note that to use for reading, this file
is disconnected from the output stream using the statement
and then it is again opened in the input mode by
associating it with the stream.
Note: The functions and write and read data in bytes, respectively, if the
file is opened for the binary operations.
Self-Instructional
234 Material
String I/O: using File Pointers and their
Manipulations
The function , which is a member of the input stream class, reads
multiple characters from the associated stream. The function is
overloaded in several forms. However, the prototype of the commonly used form NOTES
is given as follows:

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

The output of the program is

In this program, two different files, namely, and


are used sequentially to write the name of the countries and their currency,
respectively, using the same stream object . Note that the file
is closed before opening the file as they are used with
the same stream object . Then, both the files are opened simultaneously
in the input mode and their contents are read, one line at a time using the
function and displayed on the screen.
Object I/O: using and
The functions and , also known as binary I/O functions, are
used to handle blocks of binary data. Unlike , , and , the
functions operate on binary values and not on text, that
is, they treat data as a sequence of bytes. Both these functions can read and write
the entire structure (array, structure variable or a class object) in one I/O operation.
Hence, the data members are not required to be read or written separately. The
prototypes of and are given as follows:

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

The output of the program is

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

NOTES The output of the program is

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

Fig. 11.1 Default Position of File Pointers

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

where, is a type defined by , which is capable of holding the


largest value that can be returned by any of these functions.
To understand the concept of the function , consider the following
statements:

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.

Fig. 11.2 Use of seekg()

11.3.2 Specifying the Offset


As discussed earlier, the get pointer can be moved to the desired position by
specifying the positive value of in the function as an
argument. This positive value represents the absolute position in the file. However,
Self-Instructional
242 Material
the get pointer can also be moved to the desired position using an offset value (can File Pointers and their
Manipulations
be positive or negative) relative to one of the three specific positions in the file.
These three positions, which are defined in the class, are mentioned in Table
11.2.
NOTES
Table 11.2 Relative Positions

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,

that determines how seek


takes place
Thus, the functions move the get pointer and
put pointer, respectively, by number of bytes from the position specified
by the parameter . The must be one of the
positions as mentioned in Table 11.2:
Various examples of the calls to overloaded forms of the function
with an object of class are listed in Table 11.3.
Table 11.3 Examples of Calls using Offset

seek calls Output


iofile.seekg(n,ios::beg); moves the get pointer to (n + 1)th byte in the file

iofile.seekg(0,ios::beg); sets the get pointer at the beginning of the file

iofile.seekg(2,ios::cur); moves the get pointer forward by 2 bytes from the


current position
iofile.seekg(0,ios::cur); get pointer remains at the current position

iofile.seekg(0,ios::end); sets the get pointer at the end of the file

iofile.seekg(- moves the get pointer backward by 5 bytes from


5,ios::end); the end of file
iofile.seekg(3,ios::cur); moves the get pointer forward by 3 bytes from the
current position.
Self-Instructional
Material 243
File Pointers and their Note that the function returns a reference to the file stream
Manipulations
object. Thus, it can be combined with an input operation by using an extraction
operator shown as follows:

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 .

Check Your Progress


1. What does get pointer specifies?
2. What does tellg () function returns?

11.4 UPDATING A FILE: RANDOM ACCESS

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:.

Once, the size of an object is determined, the position of the object


can be obtained using the following statement:

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:

where, can be determined by using the functions or


the file pointer is located at the end of the file.
Note: Random-access I/O should be performed only on the files opened for
the binary operations to get the correct output.
Self-Instructional
244 Material
File Pointers and their
11.5 ERROR HANDLING DURING FILE Manipulations

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.

unused eofbit 0x01


failbit 0x02
badbit 0x04
hardfail 0x08

Fig. 11.3 File Status Bits

Table 11.4 File Status Bits

Status Bit Meaning


goodbit 0x00 no bit is set, if there is no error
eofbit 0x01 set to 1 if EOF is encountered
failbit 0x02 set to 1 if read or write operation fails
badbit 0x04 set to 1 if some invalid operation occurs including
opening a nonexistent file
hardbit 0x08 set to 1 if hardware error occurs

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.

x By using error handling functions: There are various other functions


provided by the class, which are used to determine the status of
individual bits. These functions along with their purpose are listed in Table
11.5.
Table 11.5 Error Handling Functions

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.

Program 11.7: A program to demonstrate handling error in a file

Self-Instructional
246 Material
The output of the program is File Pointers and their
Manipulations

NOTES

In this program, a non-existent file is opened using the file


mode . Since the function fails if a non-existent
file is opened in the mode, the function returns
error state . This is the bit that signifies that file does not exist, so this bit is set to
1 while all other bits are set to . The and functions return a
non-zero value, since an error has occurred.
Once an error has occurred, the error status flags need to be reset before
continuing the program. For example, once the contents of a file are read and end
of file is reached, the bit is set. This bit can be reset for further operations in
the program using the function shown as follows:

This statement resets the specified . However, all the error status
bits can be reset to zero by using the function without arguments as
follows:

11.6 COMMAND-LINE ARGUMENTS

C++ supports command-line arguments by which 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. For example, consider the following
statement:

where, is the command-line argument that follows the name


of the program to be executed.
Program 11.8: A program to create a file comparison utility, which takes the
name of files as arguments from the command prompt

Self-Instructional
Material 247
File Pointers and their
Manipulations

NOTES

Self-Instructional
248 Material
File Pointers and their
Manipulations

NOTES

The output of the program is

First run

Second run

In this program, two files, namely, and are passed as


arguments from the command prompt, which are accessed using the appropriate
pointer and , respectively. Firstly, the program checks if
the number of command-line arguments is correct or not using , which
represents the total number of command-line arguments. If the number of command-
line arguments does not match, a message is displayed. Further, the program checks
whether the files can be opened or not.
If the files are opened, the number of characters in both the files is determined
using the function . If the size of both files is different, the message is
displayed accordingly. Otherwise, the characters are compared and the message
is displayed depending on whether the contents are same or not.

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?

11.7 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

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.

11.10 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. Write a short note on put () and get ().
2. What is the significance of getline () function?
3. What are the function that are used for manipulation of the pointers?
Long Answer Questions
1. The functions get() and put() can be used to read and write data in
bytes. Explain.
2. Is it necessary that a file created in the binary mode must always be opened
in the binary mode for subsequent operations? If yes, why?
3. How does the statement while(infile) work for testing the end of
file, if infile is an ifstream object ? Explain.
4. How many stream objects are required to handle the following situations?
(a) To process three files sequentially
(b) To merge two sorted files into a third file Explain.
5. What does the current position mean when applied to files?
6. How can you determine the number of objects in a file? When is such type
of information required?

11.11 FURTHER READINGS

Jeyapoovan, T. 2006. Computer Programming: Theory and Practice (with


CD). New Delhi: Vikas Publishing House.
Khurana, Rohit. 2008. Object Oriented Programming with C++. New Delhi:
Vikas Publishing House.
Saxena, Sanjay. 2009. Introduction to Information Technology. New Delhi:
Vikas Publishing House.

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

After going through this unit, you will be able to:


x Understand the concept of templates and its need
x Explain the function templates
x Discuss the applicability of function templates
x Understand the restrictions of using function templates
Self-Instructional
252 Material
Templates
12.2 FUNCTION TEMPLATES

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.

12.2.2 Calling Function Templates


After defining the function template, the next step is to call it in another function,
such as in main(). When the function template is called with actual data type,
the compiler generates a specific version of the function template for that data
type. A function generated from a function template is known as a template
function (also known as generated or instantiated function) and the process is
known as function template instantiation. The definition created from a template
instantiation is called specialization.
Note: A function template is used to generate template functions. That is, each template
function is a specific instance of function template.

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.

12.2.3 Function Template with Multiple Parameters/Arguments


The function template sum() defined in Program 12.2 accepts two parameters,
both of type T. Thus, the function template cannot be called with two parameters
of different data types. For example, consider these statements.
int a=8;
float b=90.9;
cout<<sum(a,b);//invalid statement
In these statements, a call to function template sum() with two parameters
of different types results in compile-time error. The compiler generates the message
‘A m b i g u i t y between sum(int,int) and
sum(float,float)’.
This problem can be resolved by specifying a comma-separated list of more
than one generic data type in the template statement.
The syntax to specify multiple parameters of different data types in function
template statement is

Program 12.3: A program to demonstrate the concept of function template with


multiple parameters

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.

12.2.4 Function Templates with Non-type Parameters/User Defined


Template
In addition to generic types, a function template can also have other parameters,
such as variables of built-in or an enumeration type, function names, constant
expressions, a pointer or a reference to an object or a pointer to a class member.
These additional parameters are known as standard or non-generic or non-
type parameters. The non-type parameter can be specified either as a template
parameter (in the template statement) or as a function parameter (in the function
header). This section discusses only the variables of built-in types.
Note: Unlike parameter T, the standard parameter is always type checked by the compiler
when the function is called.

Non-type Template Parameter


The non-type template parameter of built-in type can only be of integral type,
such as int, char or long. For example, consider this function template
definition.

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.

Non-type Function Parameter


When non-type parameters are specified as function parameters, they add flexibility
to the program. Firstly, these parameters can be of any data type—they can also
be float or double. Secondly, when the function template is invoked, they
are passed as normal parameters to the function template. That is, there is no need
to explicitly specify the non-type parameter in angular brackets. Moreover, variables
can also be passed as non-type function parameter. Thus, non-type function
parameters are preferred over non-type template parameters.
Program 12.4: A program to demonstrate the concept of non-type function
parameters

Self-Instructional
258 Material
Templates

NOTES

}
The output of the program is

In this program, n is a non-type function parameter of type int passed to


the function template display(). Hence, the first argument should always be
of type int when the function template is invoked, however, the second parameter
can be of any type.
12.2.5 Applicability of Function Templates
The function templates can be used wherever the same set of operations has to be
performed with different data types. The mathematical and logical operations,
such as addition, subtraction, comparison, etc., are few examples where function
templates can be used. Moreover, operations on single dimensional arrays, such
as sorting, searching, etc., and operations on two-dimensional array (matrices),
such as addition, multiplication can also be implemented using function templates.
Self-Instructional
Material 259
Templates Some of the applications of function templates are shown with the help of these
examples.
Program 12.5: Selection sort using function templates
NOTES

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.

{ return (3.14*radius*radius);} //function 3


All these overloaded functions have different functionalities, that is, function
1 calculates the area of a square, function 2 calculates the area of a rectangle and
function 3 calculates the area of a circle. Note that different actions are performed
inside the body of each function as the formula for calculating the area is different
for different geometrical shapes. Hence, these functions cannot be replaced with a
single function template.
Self-Instructional
Material 261
Templates

Check Your Progress


1. What is function template?
NOTES 2. What does function template informs?
3. What is implicit instantiation?

12.3 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. 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.
2. Function template informs the compiler that a template is being declared.
3. The compiler automatically generates appropriate template functions for
data type int and double using the function template. This is called implicit
instantiation.

12.4 SUMMARY

x 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.
x Templates is similar to the definition of ordinary functions. The only difference
is that it is prefixed by the statement template and is known as template
statement.
x A function template is used to generate template functions. That is, each
template function is a specific instance of function template.
x The definition created from a template instantiation is called specialization.
x The compiler automatically generates appropriate template functions for
data type int and double using the function template. This is called implicit
instantiation.
x A function template can also be instantiated by explicitly specifying the data
type while calling the function template. This is known as explicit instantiation.
x When non-type parameters are specified as function parameters, they add
flexibility to the program.These parameters can be of any data type—they
can also be float or double.

Self-Instructional
262 Material
Templates
12.5 KEY WORDS

x Generic Function: A group or a family of functions having the same


functionalitybut operating on different data types. NOTES
x Template Function: A function generated from the generic function.
x Explicit Instantiation: A generic function instantiated by explicitly
specifyingthe data type while calling it.

12.6 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. Write the syntax to define a function template.
2. What is implicit and explicit instantiation?
3. Discuss the applicability of function template.
Long Answer Questions
1. Explain how will you define a function template?
2. Write a program to demonstrate the concept of function template with multiple
parameters.
3. What are the restrictions of using function template?

12.7 FURTHER READINGS

Jeyapoovan, T. 2006. Computer Programming: Theory and Practice (with


CD). New Delhi: Vikas Publishing House.
Khurana, Rohit. 2008. Object Oriented Programming with C++. New Delhi:
Vikas Publishing House.
Saxena, Sanjay. 2009. Introduction to Information Technology. New Delhi:
Vikas Publishing House.

Self-Instructional
Material 263
Exception Handling

UNIT 13 EXCEPTION HANDLING


NOTES Structure
13.0 Introduction
13.1 Objectives
13.2 Exception Handling Model/Mechanism
13.3 Exception Handling Constructs
13.3.1 Catching Mechanism
13.4 Answers to Check Your Progress Questions
13.5 Summary
13.6 Key Words
13.7 Self Assessment Questions and Exercises
13.8 Further Readings

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

After going through this unit, you will be able to:


x Define an exception
x Describe the C++ exception handling mechanism that includes try block,
throw statement and catch block

13.2 EXCEPTION HANDLING MODEL/MECHANISM

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

Fig. 13.1 Try-throw-catch Mechanism

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

}//end of catch block


Note: The catch block must always immediately follow the try block irrespective of the
location of the throw point.
The exception thrown using the throw statement is the object that transmits
the information about the exception. This object is known as an exception object
(see Figure 13.1). Once an exception is thrown, the control is automatically
transferred to the catch block and the try block is terminated. If the data type of
the exception object matches with the data type of the parameter specified in the
catch block, the catch block is executed. If an appropriate match is not found, the
standard library function terminate() is invoked, which by default calls the
abort() function to terminate the program abnormally. However, it is not
necessary that every time the program is executed, an exception occurs. If an
exception does not occur, the catch block is skipped and the control passes to the
statement immediately following the catch block. Self-Instructional
Material 265
Exception Handling Note: An exception usually carries three types of information with it, namely, the type of
exception, the place where the exception has occurred and the context information, such
as error message and other state information.
Program 13.1: A program to demonstrate the exception handling mechanism
NOTES

}
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

Sum of positive numbers is: 34


In this program, the try block is defined inside the function sum() and
hence, it is local to this function.

Self-Instructional
Material 267
Exception Handling
13.3 EXCEPTION HANDLING CONSTRUCTS

As stated earlier, whenever an exception occurs it is thrown using the throw


NOTES statement. The throw statement can be written in any of these forms.
throw(exception);
throw exception;
throw;
The argument exception used with the throw statement can be either
of built-in data type, such as int, float, etc., or a user-defined data type,
such as class, struct, etc. In addition to variables, constants can also be
used with the throw statement. The throw statement without any argument is used
to rethrow the exception caught by the catch block.
Note that it is not necessary that the exception should always be thrown
from the try block. It can also be thrown by a function defined outside the try
block. However, the function throwing the exception must be called within the try
block (as shown in Figure 13.2). The point within the function at which the throw
statement is executed is called the throw point. Note that once an exception is
thrown to the catch block, the control cannot return to the throw point. That is,
any statement after the throw statement will not be executed.

Fig. 13.2 Throwing an exception outside the try block

The syntax to throw an exception from a function defined outside the try
block is

Self-Instructional
268 Material
Exception Handling

NOTES

Program 13.3: A program to demonstrate the concept of throwing an exception


outside the try block

Self-Instructional
Material 269
Exception Handling

NOTES The output of the program is


First run
Enter any number: 64
Square root of the number is: 8
Second run
Enter any number: -23
Exception-a negative number
In this program, a number entered by the user is checked for an exception.
If the user enters a positive number, the square root of the number is displayed.
Otherwise, an exception is thrown and the catch block is executed.
Note that if the function containing the throw statement is called more than
once in the try block, the function call is executed as long as no exception occurs.
Once the exception is thrown by the called function and the catch block is executed,
subsequent calls to the function will not be executed. To understand this concept,
consider this code fragment.

In this code fragment, the function square_root() (defined in Program


13.3) is called three times. Since, the exception is thrown in the second function
call, the third function call will not be executed. Thus, the output of the program is
Square root of the number is: 2.23607
Exception-a negative number
This problem can be resolved by defining the try/catch block inside the
function. In this case, each time the function is called, the exception handler is
reset and invoked. For example, the try/catch block defined in Program 13.3 can
be made local to the function as given in this code fragment.

Self-Instructional
270 Material
Exception Handling

NOTES

The output of the program is


Square root of the number is: 2.23607
Exception-a negative number
Exception-a negative number
In this example, since the try/catch is local to the function, all the function
calls are executed.
13.3.1 Catching Mechanism
When an exception is thrown, it needs to be handled appropriately. The code that
handles the exception is written in the catch block. As stated earlier, catch accepts
an argument of any built-in or user-defined data type. However, it is optional to
specify the name of the argument. For example, consider this code fragment.

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

statement immediately following the last catch block. If an appropriate match is


not found, the program terminates abnormally.
Program 13.4: A program to demonstrate the concept of catching multiple
NOTES
exceptions

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.

Check Your Progress


1. What are the three keywords that are used in exception handling
mechanism?
2. What is throw point?
Self-Instructional
274 Material
Exception Handling
13.4 ANSWERS TO CHECK YOUR PROGRESS
QUESTIONS

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

x C++ exception handling mechanism mainly uses three keywords, try,


throw and catch.
x A set of statements that needs to be monitored for the exceptions is contained
in the try block.
x Whenever an exception occurs within the try block, it is thrown using the
throw statement. This passes the control to the catch block which handles
the exception appropriately.
x The exception thrown using the throw statement is the object that transmits
the information about the exception. This object is known as an exception
object.
x The point within the function at which the throw statement is executed is
called the throw point.

13.6 KEY WORDS

x Exception: An unexpected event that occurs during the execution of a


program and alters the normal flow of the program or terminates the program
abnormally.
x Synchronous Exceptions: The exceptions that occur at specific program
statements.
x Throw Point: The point within the function at which the throw statement is
executed.

13.7 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. Write a short note on C++ exception handling mechanism.
2. What is an exception object? Self-Instructional
Material 275
Exception Handling 3. What is a throw point?
4. When do we use multiple catch blocks?
Long Answer Questions
NOTES
1. Write a program that illustrates the use of the catch(...) handler.
2. Write a program that demonstrates the concept of rethrowing an exception.
3. Write a program that illustrates the use of multiple catch blocks.

13.8 FURTHER READINGS

Jeyapoovan, T. 2006. Computer Programming: Theory and Practice (with


CD). New Delhi: Vikas Publishing House.
Khurana, Rohit. 2008. Object Oriented Programming with C++. New Delhi:
Vikas Publishing House.
Saxena, Sanjay. 2009. Introduction to Information Technology. New Delhi:
Vikas Publishing House.

Self-Instructional
276 Material
Other Exception Handling

UNIT 14 OTHER EXCEPTION


HANDLING
NOTES
Structure
14.0 Introduction
14.1 Objectives
14.2 List of Exception Class
14.3 Catching All Exceptions
14.3.1 Catching Class Types
14.4 Exception Handling in Constructors and Destructors
14.5 Exception Handling in Base and Derived Classes
14.6 Restricting Exceptions
14.7 Rethrowing an Exception
14.8 Handling Uncaught Exception
14.9 Answers to Check Your Progress Questions
14.10 Summary
14.11 Key Words
14.12 Self Assessment Questions and Exercises
14.13 Further Readings

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

After going through this unit, you will be able to:


x Understand exception classes and their purposes
x Explain exception handling in constructor and destructor
x Rethrow an exception from one catch block to another
x Handle uncaught exception

14.2 LIST OF EXCEPTION CLASS

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

Exception Standard C++ base class for exceptions


in C++

NOTES out_of_range For value that exceeds its allowed range

domain_error Condition violation

length_error For length larger than the maximum size


allowed

logic_error For errors in program logic

invalid_argument For invalid argument passed to a function

runtime_error Error occurs at execution time

range_error Post condition violation

overflow_error Arithmetic overflow error

underflow_error Arithmetic underflow error

bad_alloc Failure in allocating storage

bad_cast Unvalid dynamic cast

bad_typeid Null pointer in expression

When we include stdexcept as header in a C++ program, we can use


the standard exception classes and identify the exact type of exception to be
thrown to the catch block. We place the exception class name within the arguments
section of the catch block within parentheses. To catch the various types of
exceptions, we can add multiple catch blocks successively, if needed. When the
previously referred exceptions are not present, we can place a final catch block,
which is termed as ellipsis, which is specified with three dots within parentheses of
the catch statement, i.e., catch(…).

14.3 CATCHING ALL EXCEPTIONS

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

The output of the program is


First run

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

The output of the program is


First run

Second run

In this program, a class positive is defined with a private data member n. If


a user enters a negative value for n, an exception is thrown in the
getdata()member function, which is caught by the catch block accepting a
parameter of type positive.
Sometimes a situation may arise that the exceptions, which occur while
creating the objects of a class, need to be handled. In such situation, an exception
must be thrown inside the constructor of the class. However, the throw statement
inside the constructor of the class cannot throw the object of the same class. In
this case, a new entity called exception class needs to be created. Now the
throw statement throws an object of the exception class, which is handled by the
catch block accepting a parameter of type 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
can contain data members and member functions. This section discusses an
exception class with an empty body.
Program 14.3: A program to demonstrate the concept of defining an exception
class inside another class

Self-Instructional
Material 281
Other Exception Handling

NOTES

The output of the program is


First run

Second run

14.4 EXCEPTION HANDLING IN CONSTRUCTORS


AND DESTRUCTORS

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

14.5 EXCEPTION HANDLING IN BASE AND


DERIVED CLASSES

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

The output of the program is

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.

14.6 RESTRICTING EXCEPTIONS

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

In this program, the function func()is restricted to throw the exceptions of


NOTES
type int and double. Note that if an exception of type char (which is not in
the throw list) is thrown, the catch block will not be executed and the program
terminates abnormally.
Note that the function can only be restricted to throw exceptions back to
the try block that has called it. A try block within the function can throw any type
of exception as long as it is caught within the function. Thus, the char exception
(in Program 14.6) can be caught inside the function as shown in the following
code fragment:

The output of the program is

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.

14.7 RETHROWING AN EXCEPTION

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

The C++ exception handling mechanism provides a function


uncaught_exception() for the uncaught exception, that is, the exception NOTES
that has been thrown but not yet caught. The prototype of this function as follows:

This function returns True if an exception has been thrown but not yet caught;
otherwise, it returns False.

Check Your Progress


1. Which header file defines a set of exception classes?
2. What does throw list specifies?

14.9 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

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

x std::exception: It is a small interface class designed to serve as a


NOTES base class to any exception thrown by the C++ standard library.
x Throw List: It specifies the type of exceptions that can be thrown by the
function.

14.12 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short Answer Questions


1. Discuss the purpose of various exception classes.
2. Write the syntax for defining the catch block with ellipsis.
Long Answer Questions
1. Write a program that accepts two strings from the user. Compare two strings
in a try block. If the two strings are not equal, then throw an exception.
Write an appropriate catch block to handle the exception.
2. Create a class matrix to add and subtract two matrices. Add an exception
class to it. Now handle the exception that occurs while creating the objects
of the matrix class. Also, handle the exception that occurs if the two
matrices are of unequal dimensions (that is, rows and columns of the first
matrix are not equal to rows and columns of the second matrix).
3. Write a program to show the exception handling mechanism in base and
derived classes.

14.13 FURTHER READINGS

Jeyapoovan, T. 2006. Computer Programming: Theory and Practice (with


CD). New Delhi: Vikas Publishing House.
Khurana, Rohit. 2008. Object Oriented Programming with C++. New Delhi:
Vikas Publishing House.
Saxena, Sanjay. 2009. Introduction to Information Technology. New Delhi:
Vikas Publishing House.

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]

101 23 NOITACUDE ECNATSIDDIRECTORATE


FO ETAROTCEOF
RIDDISTANCE EDUCATION

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

You might also like