C.A - C - 308
C.A - C - 308
(CA) C++
B.Com.(C.A)
Second Year
Paper No. 9
C++
BHARATHIAR UNIVERSITY
SCHOOL OF DISTANCE EDUCATION
COIMBATORE – 641 046
1
B.Com.(CA) C++
2
B.Com.(CA) C++
CONTENT
Lessons PAGE
No.
UNIT-I
Lesson 1 Object Oriented Paradigm 7
Lesson 2 Evaluation of Programming Paradigm 13
Lesson 3 Software Evolution 17
Lesson 4 Basic Concepts of Object oriented Programming 24
Lesson 5 Popular OOPs Languages,Merits,Applications of OOPs 31
UNIT-II
Lesson 6 C++ Language 41
Lesson 7 Variable, Constants and Operators 50
Lesson 8 Control Flow 85
Lesson 9 Functions in C++ 129
Lesson 10 Classes and Objects 147
UNIT-III
Lesson 11 Array of Objects 167
Lesson 12 Constructors and Destructors 186
Lesson 13 Operator Overloading 201
Lesson 14 Type Conversions 212
Lesson 15 Function Overloading 221
UNIT-IV
Lesson 16 Inheritance 229
Lesson 17 Types of Inheritance 235
Lesson 18 Base class and Derived Class 250
Lesson 19 Polymorphism 263
Lesson 20 Vitual Functions and Pointer to Derived Classes 267
UNIT-V
Lesson 21 Managing Console I/O Operations 277
Lesson 22 Formatted and Unformatted I/O Operations 282
Lesson 23 File Operations in C++ 288
3
B.Com.(CA) C++
(Syllabus)
Objectives : To promote the knowledge of OOPs Concepts through C++.
UNIT-I
OOPs, A New Paradigm – Evaluation of Programming Paradigm – Objects –
Classes – Multiple Viewing of the Same Object – Encapsulation and Data
Abstraction – Inheritance - Delegation – Object Composition – Polymorphism =
Message Communication – Popular OOPs Languages – Merits and Demerits of
OOPs Methodology – Application of OOPs.
UNIT-II
Application of C++ - Structure of C++ Program – Tokens, Expression –Basic Data
Types – Symbolic Constants – Declaring Data Types – Reference Variables –
Operator in C++ - Scope Resolution Operator – Expressions and Implicit
Conversions – Control Structures – Functions in C++ - Call by Reference – Call
by Value – Inline Functions – Default Arguments – Constant Arguments –
Classes and Objects – Defining Member Functions – Nesting Member Function –
Private Member Function – Static Member Function.
UNIT-III
Array of Objects – Friend Function – Returning Objects – Constant Member
Function – Pointer to Members – Constructors with Default Arguments – Copy
Constructor – Dynamic Constructor – Destructor – Operator Overloading and
Type Conversions – Rules for Operator Overloading – Function Overloading –
Function Overloading with Arguments – Special Features of Function
Overloading.
UNIT-IV
Inheritance – Single Inheritance – Types of Base Classes – Types of Derivation –
Public - Private – Protected Inheritance – Multilevel Inheritance – Multiple
Inheritance – Hierarchical Inheritance – Hybrid Inheritance – Polymorphism –
Virtual Functions – Pure Virtual Function – Pointer to Derived Classes.
UNIT-V
Managing Console I/o Operations – C++ Streams – Stream Classes – istreams,
ostreams, iostreams, fstream, ifstream, ofstream, filebuf, istrstream, ostrstream
– Unformatted I/O Operation – Classes for File Stream Operations – Opening
and Closing a file.
Books for Reference :
1. E.Balagurusamy, “Object Oriented Programming with C++”, Tata McGraw-
Hill Publishing Company Limited, New Delhi, 2003.
2. D.Ravichandran, “Programming with C++”, Tata McGraw-Hill Publishing
Company Limited, New Delhi, 2002.
4
B.Com.(CA) C++
UNIT – I
5
B.Com.(CA) C++
6
B.Com.(CA) C++
LESSON-1
OBJECT ORIENTED PARADIGM
CONTENTS
1.0 Aims and Objectives
1.1 Introduction
1.2 C++ At Glance
1.3 Object Oriented Paradigm
1.4 Let us Sum up
1.5 Keywords
1.6 Suggested Text Books
1.1 INTRODUCTION
The most basic program you can create in C++ is called a console application.
This type displays its results in a dark box that we will call the DOS window.
7
B.Com.(CA) C++
C++ is such a huge language that part of its foundation is provided to you so
that you can write your programs by adding to it. A program is made of various
objects that you use to build your programs. Some of these objects have already
been created and are supplied to you. Although you will not see the whole
functionality of these objects, you should be aware of which ones exist and how
to use them. These objects are provided in files called Header Files or libraries.
A file that you will use as a foundation for your program is called a Header File,
this is because, as "head", this file controls some aspects of your program.
Therefore, you will place it at the "head" section of your program. When placing a
particular file at the head of your program, you are said to "include" it. As
headers, these files have an extension of .h. To use such a file, you have to
"include" it using the include keyword. Here is an example:
include file.h
You must include the extension; this allows C++ to know that you are including
a header file. As a rule, when including a file, you must precede the line with a #
sign. Therefore, our include line would be
#include file.h
There are usually two kinds of header files you will be using in your programs:
those supplied to you and those that you create. You will mostly create your own
files in the same folder where you create your program. There are two ways you
let C++ know where a header file is located. Which means that it was supplied to
you, include it as:
#include <file.h>
If you created your own file, which means the file is probably located in the same
folder you are creating your program, include it as follows:
#include "myfile.h"
C++ offers all the (Well! Almost all) facilities to implement an object-oriented
program. However, it also supports the figments of procedural programming.
C++ also offers generic classes known as "templates", as well as multiple-
inheritance.
C++ does not provide automatic garbage collection. However, it is possible with
some effort to layer reference counting garbage collection onto C++ using smart
pointers.
C++ does not support reflection which is the ability for a program to determine
various pieces of information about an object at run-time. It does support a
limited form of runtime type information that allows a program to determine the
type of an object at runtime.
8
B.Com.(CA) C++
The ability to manipulate data and other members in the memory using their
memory references called pointers has been perhaps the most important
characteristic of the language 'C'. The same has been retained in C++. This is
both an advantage and a disadvantage at the same time. C++ provides direct
support for pointer arithmetic, both for compatibility with C and to allow C++ to
be used for systems programming without the need to drop down to a lower level
language. This is the source both of C++'s great flexibility as well as much of its
complexity. Because direct memory manipulation using pointers is unsafe if not
used cautiously, sometimes it becomes a disadvantage. Moreover, the higher
abstraction is lost if low level memory manipulation is allowed.
The Object Oriented Paradigm draws heavily on the general systems theory as a
conceptual background. A system can be viewed as a collection of entities that
interact together to accomplish certain objective. Entities may represent
physical objects such as equipment and people, and abstract concepts such as
data files and functions. In object oriented approaches, the entities are called as
Object.
The object oriented paradigm places more emphasis on the objects that
encapsulate data and procedures. They play the central role in all the stages of
the software development. Any graphical representation of the object oriented
version of the software development life cycle must, therefore, take into account
based on two aspects like overlap and iteration.
All the phases in the object oriented approach work more closely together
because of the common of the object model. The problem domain objects are
identified while in the next phase additional objects required for a particular
solution are specified. The design process is repeated for these implementation
level objects.
Object oriented analysis provides us with a simple, yet powerful mechanism for
identifying objects the building block of the software to be developed. The
analysis is basically concerned with the decomposition of a problem into its
component parts and establishing a logical model to describe the system
functions.
9
B.Com.(CA) C++
The object oriented analysis (OOA) approach consists of the following steps
Design is concerned with the mapping of objects in the problem space into
objects in the solution space, and creating an overall structure and
computational models of the systems. This stage normally uses the bottom up
approach to build the structure of the system and the top-down functional
decomposition approach to design the class member functions that provide
services.
The Object oriented design (OOD) approach consists of the following steps
• Review of objects created in the analysis phase
• Specification of class dependencies
• Organization of class hierarchies
• Design of classes
• Design of member functions
• Design of driver program
10
B.Com.(CA) C++
..........................................................................................................................
..........................................................................................................................
..........................................................................................................................
..........................................................................................................................
1.5 KEYWORDS
Design: The term design describes both a final software system and a process by
which is developed.
11
B.Com.(CA) C++
12
B.Com.(CA) C++
LESSON-2
EVALUATION OF PROGRAMMING PARADIGM
CONTENTS
2.0 Aims and Objectives
2.1 Introduction
2.2 Evaluation of Programming Paradigm
2.3 Let us sum up
2.4 Keywords
2.5 Questions for Discussion
2.6 Suggested Text Books
2.1 INTRODUCTION
Computer programming has been around for some decades now. The style and
manner in which people have been developing programs itself has undergone a
sea change. In the early days of computer development programming was looked
upon as some kind of black magic – to be understood only by a few wizards
mostly the people who had designed the computer. However, the entire scenario
has changed now.
13
B.Com.(CA) C++
1. Procedure-oriented paradigm
2. Object-oriented paradigm
Each time, writing a program used to be a new project in itself having nothing to
do with the old existing codes. Programmers were, most of time, busy creating
perhaps the same thing again and again; writing same or similar codes
repeatedly in each project implementation.
In the wake of this, questions like - how to develop software, how to support a
growing volume of existing software, and how to keep pace with a rapidly
growing demand for more error-free and efficient software - became important
concerns in connection with software development activities.
Soon software crisis became a fact of life. Engineers and Scientists of the
computing community were forced to look into the possible causes and to
suggest alternative ways to avoid the adverse affects of this software crisis
looming large at software industry all over the world. It is this immediate crisis
that necessitated the development of a new approach to program designing that
would enhance the reusability of the existing codes at the least. This approach
has been aptly termed as object oriented approach.
• Some programming languages like C++ have extended their previous form
to incorporate OOP facilities while some like Java have implemented
complete OOP concepts right form the scratch.
14
B.Com.(CA) C++
15
B.Com.(CA) C++
2.5 KEYWORDS
16
B.Com.(CA) C++
LESSON-3
SOFTWARE EVOLUTION
CONTENTS
3.0 Aims and Objectives
3.1 Introduction
3.2 Software Evolution
3.2.1 Study
3.2.2 Analysis
3.2.3 Design
3.2.4 Implementation
3.2.5 Maintenance
3.3 Procedure-oriented Programming Paradigm View
3.4 Object Oriented Programming Paradigm
3.5 Let us sum up
3.6 Keywords
3.7 Questions for Discussion
3.8 Suggested Text Books
The concept of Software evolution has been discussed in this chapter. Some of
the techniques are discussed in this chapter. At the conclusion of this chapter
you should be able to:
• Describe Evolution of Software
• Describe to attempts to eliminate pitfalls of conventional programming
methods.
3.1 INTRODUCTION
Since the invention of the computer, many programming approaches have been
tried. These include techniques such as modular programming, top-down
programming, bottom-up programming and structured programming. The
Primary motivation in each has been the concern to handle the increasing
complexity of programs that are reliable and maintainable. These techniques
have become popular among programmers over the last two decades.
17
B.Com.(CA) C++
Evolution of software technology to the growth of a tree. Like a tree the software
evolution has distinct phases of growth. The phases were built up one by one
over the last five decades. Each phase representing an improvement over the
previous one. The analogy fails if we consider the life of these phases. In
Software systems, each of the phases continues to be functional, whereas in the
case of trees, only the uppermost layer is functional.
Alan Kay, one of the promoters of the object oriented paradigm and the principal
designer of smalltalk, has said, “As complexity increases, architecture
dominated the basic material”. To build complex software it is just not enough to
put together a sequence of programming statements and sets of procedures and
modules; we need to incorporate sound construction techniques and program
structure that are easy to comprehend, implement and modify. With the advent
of languages such as C, structured programming became very popular and was
the main technique of the 1980’s. Structured programming was a powerful tool
that enabled programmers to write moderately complex programs fairly easily.
However, as the programs grew larger, even the structured approach failed to
show the desired results in terms of bug-free, easy to maintain, and reusable
programs.
18
B.Com.(CA) C++
3.2.1 STUDY
The genesis of any software begins with the study of the problems, which it
intends to solve. Software cannot be envisaged unless there is a problem that it
must solve. Therefore, studying the problem in depth, understanding the true
nature of the problem and representing the problem in comprehensible manner
is what necessitates inclusion of this phase.
3.2.2 ANALYSIS
During analysis, data are collected in available files, decision points, and
transactions handled by the present system. Bias in data collection and
interpretation can be fatal to the developmental efforts. Training, experience and
common sense are required for collection of the information needed to do the
analysis.
Once analysis is completed the analyst has a firm understanding of what is to be done.
The next step is to decide how the problem might be solved. Thus, in the software
systems design, we move from the logical to the physical aspects of the life cycle.
3.2.3 DESIGN
The most creative and challenging phase of software life cycle is design. The
term design describes both a final software system and a process by which it is
developed. It refers to the technical specifications (analogous to the engineer’s
blueprints) that will be applied in implementing the software system. It also
includes testing the software. The key question around which this phase
revolves is – How should the problem be solved?
• The first step is to determine how the output is to be produced and in what
format. Samples of the output (and input) are outlined.
• Second, input data and master files (data base) have to be designed to
generate the required output. The operational (processing) phase are
handled through program construction and testing, including a list of the
programs needed to meet the software objectives and complete
documentation.
19
B.Com.(CA) C++
3.2.4 IMPLEMENTATION
This phase is primarily concerned with coding the software design into an
appropriate programming language; testing the programs and installing the
software. User training, site preparation, and data migration are other important
issues in this phase.
3.2.5 MAINTENANCE
Change is inevitable. Software serving the users’ needs in the past may become
less useful or sometimes useless in the changed environment. Users’ priorities,
changes in organizational requirements or environmental factors may call for
software enhancements. A bank, for instance, may decided to increase its service
charges for checking accounts from Rs. 5.00 to Rs. 10.00 for a minimum
balance of Rs. 500. In this phase the software is continuously evaluated and
modified to suit the changes as they occur.
Function 1 Function 6
Function 4
Function 5
Function 3 Function 8
20
B.Com.(CA) C++
You do not have to look far to find examples of this kind of programming – C
function libraries are implemented this way. Each function in a library performs
a well-defined operation on its input arguments and returns the transformed
data as a return value. Arguments may be pointers to data that the function
directly alters or the function may have the effect of displaying graphics on a
video monitor.
Function 2 Function 4
Function 3
21
B.Com.(CA) C++
The term object-oriented programming (OOP) is widely used yet experts do not
seem to agree on its exact definition. However, most experts agree that OOP
involves defining abstract data types (ADT) representing complex real-world or
abstract objects and organizing programs around the collection of ADTs with an
eye toward exploiting their common features. The term data abstraction refers to
the process of defining ADTs; inheritance and polymorphism refer to the
mechanisms that enable you to take advantage of the common characteristics of
the ADTs - the objects in OOP. This chapter further explores these terms later.
Before going any further into OOP, take note of two points. First, OOP is only a
method of designing and implementing software. Use of object-oriented
techniques does not impart anything to a finished software product that the user
can see. However, as a programmer while implementing the software, you can
gain significant advantages by using object-oriented methods, especially in large
software projects. Because OOP enables you to remain close to the conceptual,
higher-level model of the real world problem you are trying to solve, you can
manage the complexity better than with approaches that force you to map the
problem to fit the features of the language. You can take advantage of the
modularity of objects and implement the program in relatively independent units
that are easier to maintain and extend. You can also share code among objects
through inheritance.
• Software Technology has evolved through a series of phases during the last
five years. Procedure Oriented Programming is the most popular phase till
recently was procedure oriented programming. POP has two major draw
backs, 1. Data move freely around the program and are therefore
vulnerable to changes caused by any function in the program and 2. it does
not model very well the real words problems.
• Top-down programming is the approach where a problem is viewed as a
sequence of tasks to be performed and OOP was invented to overcome the
drawbacks of the POP. It employs the bottom up programming approach. It
treats data as a critical element in the program development and does not
allow it to flow freely around the system. It ties data more closely to the
functions that operate on it in a data structure called class. This feature is
called data encapsulation. In OOPs a problem is considered as a collection
of a number of entities is known as Objects. Objects are instances of
classes. Insulation of data from direct access by the program is known as
data hiding.
22
B.Com.(CA) C++
3.6 KEYWORDS
1. What do you mean by object oriented programming? What are its benefits?
2. What do you mean by dynamic binding?
3. What is the difference between data abstraction and data encapsulation?
4. Compare what you look for in the problem description when applying
object-oriented approach in contras
23
B.Com.(CA) C++
LESSON-4
BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING
CONTENTS
4.0 Aims and Objectives
4.1 Introduction
4.2 Basic concepts of Object Oriented Programming
4.2.1 Objects
4.2.2 Classes
4.2.3. Data abstraction
4.2.4. Data encapsulation
4.2.5. Inheritance
4.2.6. Polymorphism
4.2.7. Dynamic binding
4.2.8. Message Communication
4.3 Popular OOPs Languages
4.4 Keywords
4.5 Questions for Discussion
4.6 Suggested Text Books
The Basic concepts of Object oriented Programming has been discussed in this
chapter. Some of the techniques are discussed in this chapter. At the conclusion
of this chapter you should be able to:
• Describe to ensure the basic concepts of OOPS
4.1 INTRODUCTION
24
B.Com.(CA) C++
Let us now, try to understand what aspects of problems are dealt with in object-
oriented approach. We shall be discussing some essential concepts that make a
programming approach object-oriented. In object-oriented parlance, a problem is
viewed in terms of the following concepts:
• Objects
• Classes
• Data abstraction
• Data encapsulation
• Inheritance
• Polymorphism
• Dynamic binding
• Message Communication
4.2.1 OBJECTS
Objects are the basic run-time entities in an object-oriented system. They may
represent a person, a place, a bank account, a table of data; they may also
represent user-defined data such as vectors, time and lists.
They occupy space in memory that keeps its state and is operated on by the
defined operations on the object. Each object contains data and code to
manipulate the data. Objects can interact without having to know details of each
other data or code.
The figure shows the two notations popularly used.
4.2.2 CLASSES
A class represents a set of related objects. The object has some attributes, whose
value consist much of the state of an object. The class of an object defines what
attributes an object has. The entire set of data and code of an object can be
made a user-defined data type with the help of a class.
25
B.Com.(CA) C++
Classes are user defined data types that behave like the built-in types of a
programming language. Classes have an interface that defines which part of an
object of a class can be accessed from outside and how. A class body that
implements the operations in the interface, and the instance variables that
contain the state of an object of that class.
The data and the operation of a class can be declared as one of the three types:
a. Public: These are declarations that are accessible from outside the class to
anyone who can access an object of this class.
b. Protected: These are declarations that are accessible from outside the
class to anyone who can access an object of this class.
c. Private: These are declarations that are accessible only from within the
class itself.
The wrapping up to data and functions into a single unit (class) is known as
encapsulation. Data encapsulation is the most striking feature of a class. The
data is not accessible to the outside world and only those functions that are
wrapped in the class can access it. These functions provide the interface
between the object’s data and the program. This insulation of the data from
direct access by the program is called data hiding.
4.2.5 INHERITANCE
Inheritance is the process by which objects of one class acquire the properties of
objects of another class. It supports the concept of hierarchical classification.
For example, a manager class is a type of the class employee, which again is a
type of the class person as illustrated below (Figure 4.2).
26
B.Com.(CA) C++
Person
Name
Dob
Father’s Name
The principle behind this sort of division is that each derived class shares
common characteristics with the class from which it is derived. The power of
inheritance lies in the fact that all common features of the subclasses can be
accumulated in the super class.In other words, a feature is placed in the higher
level of abstraction. Once this is done, such features can be inherited from the
parent class and used in the subclass directly. This implies that if there are
many abstract class definitions available, when a new class is needed, it is
possible that the new class is a specialization of one or more of the existing
classes.
In OOP, the concept of inheritance provides the idea of reusability. This means
that we can add additional features to an existing class without modifying it.
This is possible by deriving a new class from the existing one. The new class will
have the combined features of both the classes. Each subclass defines only
those features that are unique to it. In OOP, The concept of inheritance provides
the idea of reusability. This means that we can add additional features to an
existing class without modifying it. This is possible by deriving a new class from
the existing one. The new class will have the combined features of both the
classes. Each subclass defines only those features that are unique to it.
27
B.Com.(CA) C++
Classes and objects thereof can access each others resources even without
directly being derived from them. Though in principle, private and protected
members of a class cannot be accessed from outside the class in which they are
declared. To allow this friend functions and classes are used.
4.2.6 POLYMORPHISM
Polymorphism means the ability to take more than one form. An operation may
exhibit different behavior in different instances. The behavior depends upon the
types of the data used in the operation. For example considering the operator
plus (+).
18 + 2 = 20
“Bharathiar ” + “University”
18,2 20
Function ADD
“Bharathiar ”,“University” “Bharathiar University”
Figure : 4.3
28
B.Com.(CA) C++
be redefined in each class that defines the objects. At run-time, the code
matching the object under reference will be called.
4.4 KEYWORDS
29
B.Com.(CA) C++
Pre-defined objects: The in-built units must be all object-oriented classes and
objects.
Garbage collection: The capability of removing the objects no more in use and
reclaiming the space occupied by them in the memory.
Messaging: The capability allowing classes to pass and share messages to which
they may respond.
30
B.Com.(CA) C++
LESSON-5
POPULAR OOPS LANGUAGES, MERITS AND
APPLICATIONS OF OOPS
CONTENTS
5.0 Aims and Objective
5.1 Introduction
5.2 Popular OOPs Languages
5.3 Merits of OOPs
5.4 Applications of OOPs
5.5 Let us sum up
5.6 Keywords
5.7 Questions and Answers
5.8 Suggested Text Books
5.1 INTRODUCTION
31
B.Com.(CA) C++
Object oriented programming is not the right of any particular language like
structured programming, OOP concepts can be implemented using languages
such as C and Pascal. A language that is specially designed to support the OOP
concepts makes it easier to implement them. Several programming languages
have been developed to allow OOP - some have their roots in the previously
existing programming languages like C++ (See Plus Plus) and some new like
Java. They can be classified into the following two categories.
• Object based Programming languages
• Object oriented programming languages
Languages that are supports programming with objects are to be called as object
based programming languages. They do not support inheritance and dynamic
binding. Ada is a typical object based programming language.
32
B.Com.(CA) C++
Through inheritance, we can eliminate redundant code and extend the use of
existing classes.
33
B.Com.(CA) C++
We can build programs from the standard working modules that communicate
with one another, rather than having to start writing the code from scratch. This
leads to saving of development time and higher productivity.
The principle of data hiding help the programmer to build secure programs that
cannot be invaded by code in other parts of the program.
Object-Oriented approach offers perhaps the most logical description of the real
world. Therefore, it can be applied in almost all the situations of problem
solving. Because of its effectiveness in problem solving and programming, OOP
has been adopted all over the software industry. The existing systems are being
migrated to OOP. Applications of OOPS are beginning to gain importance in
many areas. The most popular application of object oriented programming, up to
now has been in the area of user interface design such as windows. Hundreds of
windowing systems have been developed, using the OOP techniques. Real
business systems are often much more complex and contain many more objects
with complicated attributes and methods. OOP is useful in these types of
34
B.Com.(CA) C++
applications because it can simplify a complex problem. The promising areas for
applications of OOP includes the following ;
• Real time systems
• Object oriented databases
• Simulation and Modeling
• Artificial Intelligence and Expert Systems
• Hyper text and hyper media
• Neural networks and parallel programming
• Decision support and office automation systems
• CIM/CAM/CAD systems
Above all, the reusability feature of the Object Oriented approach has facilitated
the rapid growth of software both in variety and scope.
Programming practices have evolved considerably over the past few decades. By
the end of last decade, millions and millions lines of codes have been designed
and implemented all over the word. The main objective is to reuse these lines of
codes. More and more software development projects were software crisis. It is
this immediate crisis that necessitated the development of object-oriented
approach which supports reusability of the existing code.
35
B.Com.(CA) C++
Object-oriented approach offers the most logical description of the real world.
The framework of OOP encompasses all the phases of system development. The
reusability feature of OOP has facilitated the rapid growth of software.
5.6 KEYWORDS
Design: The term design describes both a final software system and a process by
which is developed.
36
B.Com.(CA) C++
Inheritance: The process by which objects of same class acquire the properties
of object of another class.
37
B.Com.(CA) C++
38
B.Com.(CA) C++
UNIT – II
39
B.Com.(CA) C++
40
B.Com.(CA) C++
LESSON-6
C++ LANGUAGE
CONTENTS
6.0 Aims and Objectives
6.1 Introduction
6.2 Applications of C++
6.3 Structure of a C++ Program
6.4 Running C++ Program
6.5 Let us Sum up
6.6 Keywords
6.7 Questions for Discussion
6.8 Suggested Readings
6.1 INTRODUCTION
41
B.Com.(CA) C++
there are a few minor differences that will prevent a C program to run under C++
compiler. The most important facilities that C++ adds on to C are classes,
inheritance, function overloading and operator overloading. These special
features are creating of abstract data types, inheritance properties from existing
data types and support polymorphism. So, C++ a truly object oriented language.
C++ allows programmers to create large programs with clarity, extensibility and
easy to maintenance, incorporating the sprit and most efficient of C. In addition
of new features has transformed C from a language that currently facilitates top-
down approach, structured design, to one that provides bottom-up, object
oriented design.
C++ language for handling very large problems. It is suitable for virtually and
programming task including development of Languages, editors, compilers,
databases, communication systems and any complex area of real-life application
systems.
• While C++ is able to map the real life problem properly, the C part of C++
given the language the ability to get close to the machine level particulars.
• C++ programs are easily maintainable and expandable. When a new feature
needs to be implemented, is very easy to add to the existing structure of an
object.
Following the "simple first complex later" dictum of learning to write programs,
in this section a simple working C++ program will be introduced explaining the
various components of the program. We will write a C++ program and run it on a
computer.
// a simple program in C++
#include <iostream.h>
int main ()
{
cout << "Bharathiar University SDE!!";
return 0;
}
42
B.Com.(CA) C++
The program prints "Bharathiar University SDE!!" on the computer screen when
run. Though this is a very simple program it contains some of the basic elements
that you will often have to write in any C++ program. Let us get acquainted with
different lines of code of the program.
Line Explanation
// a simple program A line beginning with two slash (//) is ignored by the
in C++ compiler and hence acts as a comment line. The
programmer can use it to include short explanations or
observations within the source code itself. In our case
the comment says that this is simple program.
#include All the lines beginning with pound sign (#) are
<iostream.h> commands to preprocessor and hence are called
preprocessor directives. #include directs the preprocessor
to replace this line with the contents of the file
iostream.h. This file is a standard header file provided by
C++ library. Usually it is stored in a directory named -
include – in the file system. This file defines a number of
standard I/O objects and functions. Since our program
is using – cout – output stream which is defined in the
iostream.h. File, this file must be included. The angle
brackets (< and >) is a part of the directive that directs
the pre-processor to search this file in the default
directory. If the file is not located in the default directory
pre-processor generates an error. Another way to specify
the include file is by writing the full pathname of the
location and filename in which case double quotes (“ and
“) are used rather than angle brackets.
int main () The main function is the point by where all C++
programs start their execution, independently of its
location within the source code. It does not matter
whether there are other functions with other names
defined before or after it - the instructions contained
within this function's definition will always be the first
ones to be executed in any C++ program. For that same
reason, it is essential that all C++ programs have a main
function.
The word main is followed in the code by a pair of
parentheses (()). That is because it is a function
declaration: In C++, what differentiates a function
declaration from other types of expressions are these
parentheses that follow its name. Optionally, these
parentheses may
43
B.Com.(CA) C++
This program works just fine. However, as you will agree, the previous indented
form is more readable. A statement in C++ is always terminated by a semicolon
(;). Therefore, it does not matter how many statements you write on a single line.
Though this is an example of valid working C++ program it does not employ any
object orientation from the programmer's side. You will gradually learn how to
work write object oriented code in the later lessons.
44
B.Com.(CA) C++
Writing any program on a piece of paper as above will not execute by itself. A
series of activities is required to run the program on the target machine. These
activities include the following steps in that order. Remember that the hardware
of a computer can only execute instructions written in its own machine
language. Therefore your program needs to be translated into the machine's
code.
1. Creating a program source file: You must first create a file and type your
program into the file. You can use any text editor to do this. You can choose a
name for the source file. However, some compilers put restriction over the
number of letters that can be used in the file name. Moreover, some compilers
make it mandatory to keep the file name extension to CPP (for C Plus Plus).
2. Pre-processing: Pre-processor is a program, usually part of compiler, that
removes all the comment lines from the source program. It also processes the
include directives to insert the contents of the mentioned include files.
3. Compiling the pre-processed program source file into object code file:
Compiler is a program that translates a program written in a high level language
like (C, Java, C++ etc.) into machine code. The file containing machine code of a
program is called object file. In order to generate object file for your program file
you will need a C++ compiler.
4. Linking the object code file with other required files to obtain executable
file: The object file though contains machine language cannot be executed
because there are other pre-compiled library codes are needed to be
incorporated into your program code. This process is called inking. You need a
program called a linker to do this. A linker assembles the input object files into
an executable file.
5. Executing the executable file: Once you have obtained an executable file
(usually with file name extension EXE) you can execute the program just by
mentioning the file name at the command prompt of the operating system.
Operating system provides a program called loader that loads the final program
into the memory and gets it executed.
The steps depicted in the figure above are simplistic view of the entire process
from a programmer view only which shows how the files transition from textual
form to executable form.
Integrated Development Environment (IDE): All the programs, viz., editor,
compiler, linker, etc. are made available by the language implementer. To help
ease the programming activities, these programs can be accessed from a single
user interface. An Integrated Development Environment or IDE is a
programmers' interface that allows all these subprocesses take place in one
single environment.
Debugger: Debugger is a utility program (integrated into the IDE) that can be
used to identify errors and fix them.
45
B.Com.(CA) C++
In all the programming examples in this book we will be using Borland C++ IDE.
You can download a free version of this IDE from Borland's website and install
on your computer. Described below is the actual process on our example C++
program. We will assume that our source file name is ONE.CPP.
Launch TC.EXE (IDE for C++) by either clicking at the program file or otherwise.
Create a new file - ONE.CPP and write the program, as shown below.
You can compile this program by opening the Compile menu as shown below.
46
B.Com.(CA) C++
You have two choices here. The first choice - "Make EXE file E:ONE.EXE" -
should be chosen if the program is contained in a single file (here ONE.CPP).
Larger programs are split into a number of source files. In that case the option
should be picked. Likewise the Run menu allows you to issue commands for
executing the file. Readers are strongly advised to get familiar with the menus
and command therein of the IDE they intend to work with.
• Some programming languages like C++ have extended their previous form
to incorporate OOP facilities while some like Java have implemented
complete OOP concepts right form the scratch.
• A line in a C++ program beginning with two slash (//) is ignored by the
compiler and hence acts as a comment line.
47
B.Com.(CA) C++
• To create a C++ program file text editor programs are used. Compiler is a
program that translates a program written in a high level language like (C,
Java, C++ etc.) into machine code. The object file though contains machine
language cannot be executed unless linked with library codes.
• All the programs, viz., editor, compiler, linker, etc. necessary for creation
and execution of a program in a programming language are made available
by the language implementer in the form of a single program called an
Integrated Development Environment or IDE.
• Debugger is a utility program (integrated into the IDE) that can be used to
identify errors and fix them.
6.6 KEYWORDS
48
B.Com.(CA) C++
1. In order to work with C++ program on your computer you must have an
IDE for C++ like Turbo C++ installed on your computer. Argue this
statement with appropriate illustration.
49
B.Com.(CA) C++
LESSON-7
VARIABLE, CONSTANTS AND OPERATORS
CONTENTS
7.0 Aims and Objectives
7.1 Introduction
7.2 C++ Character Set
7.3 Token, Identifier and Keywords
7.4 Constants and Variables
7.5 Data Types
7.5.1 Creating Constants
7.5.2 Creating Variables
7.5.3 User-Defined Data Types
7.5.4 Enumerated Data Type
7.5.5 Derived Data Types
7.6 Operators and Expressions
7.6.1 Arithmetic Operators
7.6.2 Assignment Operators
7.6.3 Assignment Expression
7.6.4 Relational Operators (Comparison Operators)
7.6.5 Logical Operators
7.6.6 Shift Operators
7.6.7 Special Operators
7.6.8 The size of Operator
7.6.9 Operator Precedence and associativity
7.7 Let us Sum up
7.8 Keywords
7.9 Questions for Discussion
7.10 Suggested Readings
50
B.Com.(CA) C++
Data must be stored in a program before they can be processed. This chapter
deals with mechanism through which data may be stored in a C++ program. At
the conclusion of this chapter you should be able to:
• Enumerate C++ character set
• Differentiate between identifiers and tokens
• Identify C++ reserved words
• Specify and create various types of data in a C++ program
• Use operators to construct expressions
7.1 INTRODUCTION
Character set for any language refers to the collection of all the alphabets,
punctuation marks and symbols which can be used in writing that language.
C++ borrows a lot from the normal English language as far as the character set
is concerned. The same is reproduced below.
ABCDEFGHIJK LMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz0123456789
51
B.Com.(CA) C++
A C++ program is written using these tokens, white spaces, and the syntax of
the language. Most of the C++ tokens are basically similar to the C tokens with
the exception of some additions and minor modifications.
The keywords implement specific C++ language features. They are explicitly
reserved identifiers and cannot be used as names for the program variables or
other user-defined program elements. Table 7.1 gives the complete set of C++
keywords.
Table 7.1
52
B.Com.(CA) C++
A major difference between C and C++ is the limit on the length of a name. While
ANSI C recognizes only the first 32 characters in a name, C++ places no limit on
its length and, therefore, all the characters in a name are significant.
Care should be exercised while naming a variable that is being shared by more
than one file containing C and C++ programs. Some operating systems impose a
restriction on the length of such a variable name.
Data values processed by a program fall into two categories - constants and
variables. While constants are those data values whose value remains the same
through out the life of the program, the variables keep changing their value.
Thus, a computer program takes data values from the input devices, stores them
in variables in the memory, creates constants in the memory, if needed, fetches
them wherever necessary and write the result back into the variables as shown
in Figure 7.1.
Processing Memory
Program Variable
53
B.Com.(CA) C++
Variables and constants have the following attributed associated with them:
A unique name: An identifier that refers to the constant or variable in the
program.
A data type: The type of data specifying range of values it can store and kind of
operations applicable.
A stored value: This is the actual value stored.
A location in the memory: A memory location identified by memory address
where the value corresponding to the constant or variable is stored.
Constants and variables can be created and manipulated in a variety of ways
discussed in the later sections.
Main Program
54
B.Com.(CA) C++
may also be applied to double. Table 7.2 lists all combinations of the basic data
types and modifiers along with their size and range.
55
B.Com.(CA) C++
Or alternatively, they can be given a specific name. Once assigned a value the
name becomes synonymous with the value. Wherever the name appears it is
interpreted as the value. Such constants are called symbolic constants. There
are two ways of creating symbolic constants in C++:
In both C and C++, any value declared as const cannot be modified by the
program in any way. However, there are/some differences in implementation. In
C++, we can use const in a constant expression, such as:
const int size = 10: //create a constant named size of int type with value 10
As with long and short, if we use the const modifier alone, it defaults to int. For
example,
const size = 10;
Another method of naming integer constants is as follows:
enum {X,Y,Z};
This defines X, Y and Z as integer constants with values 0, 1, and 2 respectively.
This is equivalent to:
const X = 0;
const Y = 1;
const Z = 2;
Enumeration data type has been taken up for detailed discussion in later
sections.
For instance, the following statement declares a variable named age as integer
type data variable.
int age;
Since the number of spaces (or white spaces) do not matter the following is also
correct in C++.
int age;
56
B.Com.(CA) C++
C++ allows both declaration and initialization in one statement as shown below.
float sum = 0.0; //declare sum as float variable and store an initial value into it
The data stored in a variable (or in a constant) is accessed just by mentioning its
name. Wherever the name appears it is interpreted to be the value stored in it as
demonstrated in the following code snippet.
float sum = 2.5; //declare sum as float variable and store an initial value into it
The statement varsum = sum + 3.6; is equivalent to varsum = 2.5 + 3.6; where
sum has C++ Data Types been replaced with the value stored in it.
In C++ all variables must be declared before they are used in executable
statements. C++ allows the declaration of a variable anywhere in the scope. This
means that a variable can be declared right at the place of its first use. This
makes the program much easier to write and reduces the errors that may be
caused by having to scan back and forth. It also makes the program easier to
understand because the variables are declared in the context of their use. The
example below illustrates this point.
57
B.Com.(CA) C++
main ( )
{
float x; // declaration x as float variable
float sum = 0; //declare sum as float variable
for (int i = 0; i<5; i++) //declaration i as integer variable
{
cin >> x;
sum = sum+x;
}
float average; //declare average as float variable
average = sum / i;
cout << average;
}
The only disadvantage of this style of declaration is that we cannot see at a
glance all the variables used in a scope. In a single statement more than one
variable of same data type can be declared if they are separated by comma as
shown below.
int x, y, z;
Remember a C++ statement terminates with semicolon (;). Therefore, all the
variables separated by comma (,) are declared of the same type. Moreover you
can also initialize the variables in a single statement as follows.
int x = 10, y = 90, z;
The simple atomic data types provided by C++ may not be sufficient for many
programming assignments. To allow users to create their own data types C++
provides a mechanism. Once a user-defined data type is created successfully it
can be used just as any other data type. Some of the user-defined data types are
discussed below.
Structures :
Structures are data types composed of a number of other data types which can
be identified as a single unit of data. Some data items are inherently structure
type. For example, date is a data containing three simple integer type data items
- day, month and year, yet referred to as a single data item. For such kind of
data items structure offer a convenient way to organize them in a single unit. A
C++ structure can be declared with the following syntax.
58
B.Com.(CA) C++
struct <structure_name>
{
<data type1> <variable_name1>;
<data_type2> <variable_name2>;
-------
<data_typen> <variable_namen>;
}
The keyword struct declares a data type as a structure. Thus, the date data type
can be implemented as a structure as follows.
struct date
{
int day;
int month;
int year;
}
The member variables of a structure data type are often referred to as fields. A
variable of structure data type can be created just as any other data type
variable. Let us create two variables - BirthDate and JoiningDate - as date data
type. The following code snippet does just the same.
struct date BirthDate, JoiningDate;
Variables which are member of structure type variable can be accessed by dot (.)
operator. Thus, BirthDate.day refers to the day field of BirthDate structure type
variables while JoiningDate.day refers to the day field of JoiningDate structure
type variable. These fields can be used just as any other simple data type. Thus,
to store 26 in day field, 12 in month, and 2008 in year field of the BirthDate
structure type variable, the following statements can be used.
BirthDate.day = 26;
BirthDate.month = 12;
BirthDate.year = 2008;
Structure fields can also be another structure data type as shown below.
struct date
{
int day;
int month;
int year;
}
59
B.Com.(CA) C++
struct friend
{
int friendNumber;
struct date BirthDate;
}
In this case structure friend has four fields:
friend.friendNumber
friend.BirthDate.day
friend.BirthDate.month
friend.BirthDate.year
As is clear from the above illustration, structures can be nested and are
accessed just using multiple dot (.) operators.
Classes
Classes are the very essence of C++ programming. This is also a user-defined
data type closely related to structures albeit possessing many other special
features. Classes once declared can be used just like any other data type.
Classes are discussed in detail in later chapters.
An enumerated data type is another user-defined type which provides a way for
attaching names to numbers thereby increasing comprehensibility of the code.
The enum keyword (continued from C) automatically enumerates a list of words
by assigning them values 0, 1, 2, and so on. This facility provides an alternative
means for creating symbolic constants. The syntax of an enum statement is
similar to that of the struct statement. Here are a few examples:
The enumerated data types differ slightly in C++ when compared with those in
ANSI C. In C++, the tag names shape, color, and position become new type
names. That means we can declare new variables using these tag names. See the
following examples:
60
B.Com.(CA) C++
ANSI C defines the types of enums to be ints. In C++, each enumerated data type
retains its own separate type. This means that C++ does not permit an int value
to be automatically converted to an enum value. Examples:
color backgrounds blue; //allowed
color background = 7; //Error in C++
color background = (color) 7; //OK
However, an enumerated value can be used in place of an int value.
int c " red; //valid, color type promoted to int
By default, the enumerators are assigned integer values starting with 0 for the
first enumerator, 1 for the second, and so on. We can override the default by
explicitly assigning integer values to the enumerators. For example,
are valid definitions. In the first case, red is 0 by default. In the second case,
blue is 6 and green is 7. Note that the subsequent initialized enumerators are
larger by one than their predecessors.
61
B.Com.(CA) C++
main( )
{
cout << "Enter shape code:";
int code;
cin>> code;
while (code >= circle && code <= triangle)
{
switch(code)
{
case circle: //incase user entered code for circle
….
break;
case rectangle //incase user entered code for rectangle
….
break;
case triangle: //incase user entered code for triangle
….
break;
}
cout << "Enter shape code:"
cin>> code;
}
cout << "GOOD BYE\n";
}
ANSI C permits an enum to be defined within a structure or a class, but the
enum is globally visible. In C++, an enum defined within a class (or structure) is
local to that class (or structure) only.
With simple atomic and user-defined data types C++ serves the data type
purposes in many programming assignments. However, there are other data
types and code units that are essential too. These types called derived data types
are listed below. They will be discussed in later chapters.
1. Arrays
2. Pointer
3. Reference variables
62
B.Com.(CA) C++
We have already seen that individual constants and variables are the basic data
objects manipulated in a program. Operators specify what is to be done with
them. Expressions can be formed by joining them together, which could lead to
generate a statement as most statement are compared of expression and
operators.
1. Arithmetic operators
2. Assignment operators
3. Unary operators
4. Relational operators
5. Shift operators
6. Bit-wise operators
7. Logical operators
8. Conditional operators
63
B.Com.(CA) C++
Notice the truncated quotient resulting from the division operation, since both
operands represent integer quantities. Also, notice the integer remainder
resulting from the use of the modulus operator in the last expression.
Finally, suppose that x1 and x2 are character-type variables that represent the
character M and U, respectively. Several arithmetic expressions that make use of
these variables are shown below, together with their resulting values (based
upon the ASCII character set).
64
B.Com.(CA) C++
A = ((a/b) * b) + a % b)
If x had been assigned a value of -12 and b had been assigned 2, then the value
of x/y would still be -6 but the value of a % y would be 0. Similarly, if x and y
had both been assigned negative values (-12 and -2, respectively), then the value
of x/y would be 3 and the value of x%b would be -2.
Operands that differ in type may undergo type conversion before the expression
takes on its final value. In general, the final result will be expressed in the
highest precision possible, consistent with the data type of the operands. The
following rules apply when neither operand is unsigned.
2. If one operand is a floating-point type (e.g., float, double or long double) and
the other is a char or an int (including short int or long int), the char or int
will be converted to the floating-point type and the result will be expressed
as such. Hence, an operation between an int and a double will result in a
double.
3. If neither operand is a floating-point type but one is long int, the other will
be converted to long int and the result will be long int. Thus, an operation
between a long int and an int will result in a long int.
65
B.Com.(CA) C++
in a C++ program, it doesn't mean "a is equal to b". Instead, it means "assign the
value of b to a". Assignment statement that makes use of this operator is written
in the form:
left_hand_operand = right_hand_operand;
where left_hand_operand generally represents a variable, and
right_hand_operands represents a constant, a variable or a more complex
expression. This statement, when executed, causes the value of the
right_hand_operand to be computed and the resulting value is to assign the
left_hand_operand. For example, the statement:
a = 5;
assigns the value of the right hand operand (5) to the left hand operand i.e. to
the integer variable a. There are several other assignment operators in C++
which provide a shorthand method for combining a binary mathematical
operation with an assignment operation. For example, to increase the value of a
by 1 you could write
a = a + 1;
using shorthand notation of assignment, you would write
a += 1;
A general format of using the short hand notation is:
v OP= exp;
Where v is a variable, exp is an expression and OP represents a binary operator.
You can create shorthand assignment operators using the five binary arithmetic
operators (i.e. +, -, *, /, %). The combination of the assignment operator with the
arithmetic operators carried a new term for these operators 'arithmetic
assignment operators'. The following table 7.4 summarizes these astigmatic
assignment operators with examples.
66
B.Com.(CA) C++
Note that this short hand notation is also applicable to the bitwise operators
(discussed later in this section). The use of shorthand notations in assignment
expression has various advantages over the simple or traditional assignment
operator. There are as follows:
• Arithmetic assignment operators save coding time.
• Left hand operand need not be repeated and therefore easier to write.
• The statement are more concise and, therefore, easier to read.
• It can possibly produce more efficient object code.
67
B.Com.(CA) C++
68
B.Com.(CA) C++
69
B.Com.(CA) C++
Note that the prefix and postfix versions have the same effect upon the operand.
When increment and decrement operators are used as part of other expressions,
then they work differently in prefix and postfix notation. The increment and
decrement operators have higher precedence than the assignment operator as
well as other binary operators. These operators are used extensively in the
control statements (discussed later). The following rules apply while working
with increment and decrement operators:
• The operand used with each of these operators must be a single variable.
An expression such as:
(a + b) ++
would be illegal because the whole expression (a+b) cannot be incremented as it
represents a value not a variable.
• Postfix increment/decrement operators have higher precedence over prefix
increment/decrement operators. For instance, consider the following
expression, if
a=1 initially:
b = ++ a + a ++ ;
The value of b will be 4. Let's see how?
Step 1 : a++ first uses the value of a i.e. 1 (due to precedence)
Step 2 : Then the value of a get increased by 1 i.e. a becomes 2 now.
70
B.Com.(CA) C++
Relational operators are used to test the relationship between two variables, or
between a variable and a constant. Most precisely, Relational operators compare
the values to see if they are equal or if one of them is greater than the other and
so on. Thus, the relational operators determine the relations among different
operands. For instance, the following expression a < b
71
B.Com.(CA) C++
Note that these relational operators compare numbers and characters. But they
don't work with strings (sequence of characters).
Note that logical operators also have a precedence order, both among themselves
and in relation to other operators. Precedence of execution of logical operators
are: ! (NOT),&& (AND), || (OR). On the other hand in a logical expression, !
(NOT) has a higher precedence than all the relational operators and all the
binary mathematical operators. In Contrast, the && and || operators have
much lower precedence, lower then all the mathematical and relational
operators. However, the precedence of execution can be changed by using
parenthesis.
72
B.Com.(CA) C++
As you may know, A bit is the most fundamental unit of computer data storage.
There are times when some applications require the manipulation of individual
bits with in a word of memory. C++ contains several special operators called as
bitwise operators that allow such manipulation. The following Table 7.11 lists
these operators and their meanings.
Opeartor Meaning
& Bitwise AND
! Bitwise OR
^ Bitwise Exclusive OR
<< Shift left
>> Shift right
~ One’s complement
Beside these, C++ also contains several operator that combine bitwise operations
with ordinary assignment operator called as compound assignment operators.
The following tables 7.12 slow these shorter notations:
Opeartor Meaning
& Bitwise AND
! Bitwise OR
^ Bitwise Exclusive OR
<< Shift left
>> Shift right
~ One’s complement
73
B.Com.(CA) C++
Shift operators work on individual bits in a byte. Using the shift operator
involves moving the bit pattern left or right. You can use them only on integer
data type and not on the char, bool, float, or double data types.
If the int data type occupies four bytes in the memory, the rightmost eight bits of
the number 10 are represented in binary as
0 0 0 0 1 0 1 0
When you do a right shift by 3(10 >> 3), the result is C++ Data Types
0 0 0 0 0 0 0 1
10/23, which is equivalent to 1.
When you do a left shift by 3 (10 << 3), the result is
0 1 0 1 0 0 0 0
10*23, which is equivalent to 80
For negative numbers, the unused bits are initialized to 1. Therefore, -10 is
represented as:
1 1 1 1 0 1 1 0
There are special operators used in C++ language to perform some particular
type of operation. The following Table 7.13 lists these operators.
The Comma and Sizeof Operators are Discussed in this Section While The Other
Operators will be Discussed when Required in this Text.
74
B.Com.(CA) C++
Simply stated, the sizeof operator is used to measure the date sizes. It is a unary
compile time operator that is to return the length (in bytes) of the variable or
parenthesized type specifiers that it proceeds.
Each data type has its own size. Depending upon the operating system and the
C++ compiler, the size of a data type varies. So, what will be the size of a data
type in your machine? C++'s sized operator will give the answer of this question.
The sizeof operator has one of the following formats:
int a ;
char b ;
a = sizeof b ;
Note that the sizeof operator has the same precedence as prefix
increment/decrement operators level. The unusual about the sizeof operator is
that it doesn't resemble on operator at all but looks like a library function as its
syntax is:
sizeof a ;
In this format parentheses are optional, if the expression is not a C data type,
the parentheses can be discarded.
While evaluating an expression that contains more than one operator, the
following two questions may arise:
First, what will be the order in which operations are performed, so understand
the importance of this question, consider the following expression:
a=1+2*3;
75
B.Com.(CA) C++
(1) 3
(2) 9
In contrast, performing the multiplications first will assign a value of 7 to a i.e.
a= 1 + 2 * 3;
(1) 6
(2) 7
6 / 2 * 6 / 2;
As division (/) and multiplication operators are of the same importance, will
yields a different result if evaluated from left to right and vice versa i.e. 9 and 1
respectively. Clearly some rules are needed about the order in which operations
are performed and for also in which direction the operator acts upon its
operands. Let's discuss in detail. Operators have two important properties - their
precedence and the associativity. An understanding of both of these is a
prerequisite for their proper use in C++.
The precedence of an operator determines the order in which the expression will
be evaluated. Whereas associativity refers to the direction in which operators
possessing the same precedence are to be executed, as there are distinct level of
precedence and an operator may belong to one of the levels, the operators at the
higher level of precedence are evaluated either from left to right or right to left,
depending on the level.
The result may be quite unexpected if the above expression would have been
written for calculating the average of three numbers. As mentioned earlier,
parentheses can be used to change the order of execution. A sub-expression
enclosed in parentheses is evaluated first, without regard to operator
precedence. Thus, the above expression could be written as:
a = (1 +2 +3) / 3;
76
B.Com.(CA) C++
The following Table 7.14 provides a complete list of operators, their precedence
levels and their rules of association.
Operator Symbol Associativity Rank Precedence
Function expression () Left to right 1 Highest
Array expression [] --
Structure operator ->
Unary plus + Right to left 2
Unary minus -
Increment ++
Decrement --
Logical negation !
One.s complement ~
Address of &
Pointer reference (indirection) *
Size (size of an object) sizeof
Type cast (conversion) (type)
Multiplication * Left to right 3
Division /
Modulus %
Addition + Left to right 4
Subtraction -
Left shift << Left to right 5
Right shift >>
Less than < Left to right 6
Less than or equal to <=
Greater than >
Greater than or equal to >=
Equal to == Left to right 7
Not equal to !=
Bitwise AND & Left to right 8
Bitwise XOR (exclusive OR) ^ Left to right 9
Bitwise OR | Left to right 10
77
B.Com.(CA) C++
This expression yields different values in both the direction i.e. if evaluated from
left to right or vice versa. Both the operators ( * and /) are of equal precedence
level, but behave differently as far as their direction of execution is concern how?
With the operators such as (binary multiplication), a change in the position of
the operands will not affect the value of the resultant expression. These type of
operators are called as commutative operators. The following Table 7.15 lists the
various commutative operator of C++:
78
B.Com.(CA) C++
a = 2/5;
Hence, would be of non-commutative.
All of C++'s data object have a specific type. For instance, a numeric variable can
be an int or long and float or double and so on. Program often requires the
different types be combined in expressions and statements. When a statement or
expression contains operands of mixed data type, they are necessarily converted
to a common type according to some specified rules. So, the process of
converting one predefined type into another is called type conversion. It is easy
to convert values from one type to another in a program. Sometimes C++
automatically handles the different types, so you don't need to be concerned.
Other times, you must explicitly convert one data type to another to avoid
erroneous results. In C++, type conversions can be carried out by two ways:
x=y;
The first statement will assign ASCII code of 'A' to ch, as letter and symbol are
represented in the memory by their associated number codes. And the second
statement will store the same code i.e. 65, in an integer variable num. In the
above example, because both the variables are of integral flavor, no
complications were associated with this promotion.
Given below is the sequence of the rules that are applied while evaluating
expressions.
79
B.Com.(CA) C++
3. Else, if either operand is a float, the other will be converted to float; result
will be a float.
4. Else, the integral promotions are performed on both operands i.e. all
primary value of char or short data class will be converted to int
fundamental data class.
6. Else, if one of the operand is long int and the other is unsigned int, then:
(a) If unsigned int can be converted to long int, the unsigned int operand will
be converted as such; result will be a long int.
(b) Else both operand will be converted to unsigned long int; result will be
unsigned long int.
7. Else, if either operand is long, the other will be converted to long; result will
be a long.
Once these conversion rules have been applied, each pair of operands will be of
the same type and the result of each operation will be same as the type of both
operands.
Type promotion can also occur with the assignment operator. The expression on
the right side of an assignment statement is always promoted to the type of the
data object on the left side of the assignment operator. If, in the following
statement, f is a type float and i is a type int then i will be promoted to type float.
f=i;
Note that when an integer type is converted to a floating type, the resulting
floating-point value might not exactly match the integer value. Consider the
following statement:
80
B.Com.(CA) C++
float f ;
int i = 3;
f=i;
In this case, the value of f could be 2.999995 instead of 3. This is because the
floating point format used internally by the computer can't accurately represent
every possible integer number.
Conversion using assignment operator might cause a "demotion" rather than a
promotion. The result is much different when one assign a higher data type
value to a data type of a relatively lower class. Consider the above statements
once again, if:
float f = 2.999995 ;
int i ;
i=f;
After the execution of these statements, the variable i will have the value 2 i.e. f
will be denoted to type int as its fractional part is last on assignment to integer
type variable i. This process of denoting one integral value to a lower data type is
called as demotional type conversion.
Note that ++ itself isn't changed at all, conversion affects only a copy of the
value. Thus, f still has the value 2.999995. Similarly demotion of a double to
float causes rounding of digits in the mantissa and lay int to int causes dropping
of the excess higher order bits.
You might think that assigning the resulting to a type float variable promotes it
to type float. This is correct, but now it's too late as decimal part of the result of
the division has been last and f is representing a wrong figure.
This problem can be solved by converting one of the type int variable to type
float. This conversion requires cast operator to forcefully convert one data type
to another. The operator used to force this conversion is known as the cast
operator and the process is known as type casting or casting simply. As this
conversion is defined by the user explicitly, is called as explicit type conversion.
81
B.Com.(CA) C++
Example Action
a = (int) 9.2 9.2 is converted to integer by truncation
a = (float) a / 2 a is converted to float before evaluation and the
result would be 9.0
a = (int) (9.0 / 2.0) the result of (9.0 / 2.0) is converted to integer
and would be 4
a = (int) 9.0 / 2 9.0 is converted to integer and then division will
take place
a = (int) 9.2 / (int) 2.0 Evaluated as 9 / 2 and the result would be 4
Table 7.16: Examples of Type Casting
82
B.Com.(CA) C++
7.8 KEYWORDS
Bitwise operator: An operator that operates on the individual bits of the input value.
Expression: A combination of identifiers and operators according to some rule
that yields a value.
Operator: A symbol that works on one or more values to yield another value.
Unary operator: An operator that takes one operand only.
Type casting: Specifying the data type before a value in order to convert one
data type to another compatible data type.
83
B.Com.(CA) C++
84
B.Com.(CA) C++
LESSON-8
CONTROL FLOW
CONTENTS
8.0 Aims and Objectives
8.1 Introduction
8.2 Statements & Branching
8.2.1 Simple If Statement
8.2.2 If-else Statement
8.2.3 Nested If-else Statement
8.2.4 Else-if Statement
8.2.5 Goto Statement
8.2.6 Switch Statement
8.3 Looping
8.3.1 For Loop
8.3.2 While Loop
8.3.3 Do-while Loop
8.3.4 Break Statement
8.3.5 Continue Statement
8.4 Let us Sum up
8.5 Keywords
8.6 Questions for Discussion
8.7 Suggested Readings
85
B.Com.(CA) C++
8.1 INTRODUCTION
There are some situations when you have to take decisions like whether to
purchase this book or not.
There are also some situations where you have to perform the particular action
again and again like for better understanding read this unit 5 times
continuously. In the some manner, hardly we write a computer program that
may not encounter these situations. Most of the programs require a statement or
set of statements to be executed multiple times or not to execute at all,
depending on the circumstances. C++ includes a variety of program control
statements that let you control the order of program execution.
This unit discusses the various program control statements like sequential,
selection, and iteration in detail and how these can be implemented in a
program.
The statement by which we can control the flow of the program execution is
called as control flow statement or program control statement. C++ provides
constructs to support sequence, selection and iteration. The combination of one
or more of following constructs explains the flow of the program.
• Sequence
• Branching
• Looping
• Sequence
Statement 1
Statement 2
Statement
Figure 8.1: The Sequence Construct
You must have observed in the last unit that the execution of a C++ program is
top down i.e., execution starts with the beginning of the main() function and
proceeds, statement by statement, the end of the main () is reached. The
86
B.Com.(CA) C++
A statement is a section of code which directs the computer to carry out some
task. In the C++, a statement is a complete instruction, ending with a semicolon.
The term instruction refers to any basic, complete process allowed in the
reference language. For example, the instructions: Adding two numbers and
assigning the result to a variable could be represented in a C++ statement as:
c=a+b;
In C++, statements are usually written one per line, although some statement
seen multiple lines as number of expressions can be included in each statement.
87
B.Com.(CA) C++
• Expressions Statements
• Compound Statements
• Control Statements
An expression statement consists of any valid C++ expression and followed by a
semicolon. The execution of an expression statement causes the expression to be
evaluated. Following are some of the examples of expression statements:
• a=2;
• c=a+b;
• ++i;
• cout<<"This is an example of output function";
• ;
The first two statements are assignment type statements. Each causes the value
of the expression on the right of the equal sign to be assigned to the variable on
the left. The third statement is an incrementing type statement, which causes
the value of i to increased by 1. The fourth statement is a standard C++ library
stream cout<<, that writes the message with in the quotes on to the standard
output device. Last statement is a null statement - a statement that does not
perform any action. It can write by simple placing a semicolon by itself on a line.
A null statement is useful in thoseinstances where the syntax of the language
requires the presence of a statement but where the logic of the program does
not, like in loops.
A compound statement, also called a block, is a group of two or more C++
statements enclosed in braces. The individual statements may be of expression
statement, compound statement or even a control statement. A general format of
compound statement is as follows:
{ statement 1;
statement 2;
:
statement n;
}
Unlike an expression statement, a compound statement does not end with a
semicolon. The opening & closing braces are the indications of beginning and
end point of a compound statement. It is treated as a single unit and may
appear anywhere a single statement may appear. A typical compound statement
is shown below:
{
a = 2;
c = a + b;
c + +;
}
88
B.Com.(CA) C++
Though, this block consists of three various statements, but will be considered
as a single entity with in the program in which it appears.
Control statements are used to control the flow of the program by using special
program structures, such as logical tests, loops and branches. The key words of
the control statements are normally a predefined or a reserved word that can not
be used as an ordinary variable such as shown below.
if ( a > b)
--
else
--
As mentioned earlier, any part of your program that starts with /* and ends */ is
called a comment and is used to enhance the readability of your program. The
compiler ignorers all comments, so they have absolutely no effect on how a
program works. Following are the example of comment statements:
//A single line comment
c=a+b; // A single line comment
/* A comment
spanning
Multiple lines */
is a non-executable statement.
89
B.Com.(CA) C++
c = a + /* assigning a + b to c */ b;
A declaration statement is used to declare a variable, a function, or any other
user defined data type. Note that the declaration statement reserves no memory
but only declares the format of the data object. Following are the examples of
declaration statements:
• int a, b, c;
• void sum (int, int);
• struct student;
{
int rn;
char*name;
int mks;
};
The first statement is declaring three variables a, b, c of integer type. C++ Data
Types The second statement is a function prototyping that tells the compiler that
sum is a function, which is receiving two arguments of integer types and will not
return any value. Functions have been discussed in detail in later chapters.
Preprocessing directives are lines of code that begin with a pound sign (#). The
C++ preprocesses are executed at the beginning of the compilation process as
these are not the part of C++ compiler. Preprocessor directions are placed in the
source program before the main line, though this is not a firm requirement.
However, these have to be defined before it can be used in your program. The
C++ preprocessor is line oriented i.e. must end with a new line character, not a
semicolon.
90
B.Com.(CA) C++
Branching
Sometimes, instead of executing all the statements, only suitable statements are
executed depending on the input and the condition involved. In selection
construct, the execution of statements depends upon a condition test. If the test
evaluates to true, you direct the program to take one course of action, otherwise,
you direct the program to do something else. In selection construct, two or more
sets of statements are written but only ‘one’ of these sets is executed as show in
the Figure 8.2.
Statement 1 Statement 1
Statement 2 Statement 2
Statement Statement
Stop
Statement 1
Statement 2
Statement
91
B.Com.(CA) C++
The iteration construct is also called as loop. The statement s that are to be
executed is called as body of the loop and the condition on which a loop
terminates is called as exit condition.
BRANCHING
A branching (or selection) statement enables you to execute either one section of
code or another. The execution of the particular section of code is, actually
determined by the evaluation of a test condition. If the condition evaluates to
true then the particular section of code will be executed, otherwise, if the
condition evaluates to false, another set of code will be executed. In this category
C consider the following statements:
• The simple if statement
• The if - else statement
• The nested if statement
• The else-if statement
• The switch statement
• The conditional operator : an alternative statement
In its basic form, the if statement evaluates a test condition (i.e., nothing but a
conditional expression) and directs program execution depending on the result
of that evaluation. The general form of a simple if statement is as shown below:
if (expression)
statement;
A statement may consist of a single statement, a compound statement or an
empty statement. The expression also referred so as test condition must be
enclosed in parentheses, which causes the expression to be evaluated first. If it
evaluate to true (i.e., a non-zero value), then the statement associated with it will
be executed otherwise ignored and the control will pass to the next statement.
For example, consider the following statement:
:
if (marks > 39)
cout << “\n Pass”;
:
:
The above code fragment will display “Pass” on the monitor if the value of marks
is greater than 39. If the value of marks is not grater than 39, the control
simply ignores this statement and will pass to the next statement. The follow
program shows the use of simple if as it accepts the marks of a student and
prints his/her result.
92
B.Com.(CA) C++
#include<iostream.h>
void main
{
int marks;
cout << “\n enter your marks”;
cin >> marks;
if (marks>9) //if construct with test condition
cout << “ \n Pass”; //statement associated with if
cout << “ Thank you”; //next statement
}
The output of the program (run 1):
Enter your marks : 77<ENTER>
Pass
Note that “Pass” has been displayed only if the expression evaluated to true
otherwise if it evaluated to false, the control ignores the associated statement
and executed the next statement i.e., “Thank you”.
93
B.Com.(CA) C++
As you must observed in the previous section that the simple if statement
executes a single statement or a group of statement when the given expression
evaluates to true (i.e. non-zero value). It does nothing when the expression
evaluates to false (i.e. a zero value) and simply moves to next statement of the
program.
94
B.Com.(CA) C++
The code segment will display “Pass” on the monitor if the value of marks is
greater than or equals to 40. If the marks are less than 40 (obviously the else
case), then the statement in the else section will be executed and will print “Fail”
on the monitor.
# include<iostream.h>
void main ()
{
int num;
cout << “\n Enter any number:”;
cin >> num;
if(num < 0)
cout << “\n Number is a negative number”;
else
cout << “\n Number is a positive number”;
}
The output of the program (run 1):
Enter any number : 45<ENTER>
Number is positive number
Note that we can have separate message for zero. But for this the logic of the
program requires some changes.
95
B.Com.(CA) C++
In the above segment of code, the inner if executes only if the expression1
evaluates to true. The other possible combination of nested if may take one of
the following form:
if (expression1)
{
if (expression2)
statement1;
}
Or
if (expression1)
{
if (expression 2)
statement1;
else
statement 2;
}
Or
if(expression1)
{
statement1;
}
else
{
if(exp2)
statement 2;
}
Or
if (exp 1)
{
statement1;
}
else
{
96
B.Com.(CA) C++
if (exp2)
statement 2;
else
statement3;
}
Let’s write a couple of programs to explore the various combination of nested if.
The following program not only prints the request after accepting marks from the
students but also print his/her grade.
# include<iostream.h>
void main ()
{
int marks;
cout << “\n Enter your marks:”;
cin >> marks”;
if (marks >=40)
{
cout << “\n Pass”;
if (marks > = 80)
cout << “ with distinction”;
}
else
cout << “\n Fail”;
}
Output of the program (run 1)
Enter your marks : 77<ENTER>
Pass
Note that the execution of the inner if takes place only if first expression
evaluates to true and the message “with distinction” will print only if both the
expressions evaluates to true.
The next program demonstrates the use of an if-else construct in if’s body as will
as in else’s body. We’ll write the same programs of marks and result with little
variations.
97
B.Com.(CA) C++
#include <iostream.h>
void main ()
{
int marks;
cout << “\n Enter your marks:”;
cin >> marks”;
if (marks >=40)
{
if (marks > = 75)
cout << “\n Very well done”;
else
cout << “\n Well done”;
}
else
{
if (marks > = 20)
cout << “\n Poor”;
else
cout << “\n Very poor”;
}
}
98
B.Com.(CA) C++
# include<iostream.h>
void main ()
{
int marks;
cout << “\n Enter your marks:”;
cin >> marks”;
if (marks > = 75)
cout << “\n Very well done”;
if (marks > = 40 && marks < 75)
cout << “\n Well done”;
if (marks > = 20 & & marks < 40)
cout << “\n Poor”;
if (marks < 20)
printf (“\n Very poor”);
}
Output of the program (run 1)
Enter your marks : 78<ENTER>
Very well done
Note that the statements that are associated with the expressions consist of
logical operator will executes only when both the sub expressions evaluates to
true , as in AND relation only true and true holds the value true. (i.e. 1 && 1 =
1)). Sometimes, the nested-ness of if constructs increases the complexity and
produces an ambiguous situation referred to as dangling else problem. This
problem may arise in a nested if statement in the following circumstances:
• Improper use of braces in nested if statements.
• Number of if’s are more than the number of else clauses.
Imagine a situation where you have to test number of conditions to get the
desired results. These types of particular situations require nested-ness of if-else
statements up to a deeper level and it may looks like as:
if (expression 1)
statement 1;
else
if (expression 2)
99
B.Com.(CA) C++
statement 2;
else
if(expression 3)
statement 3;
else
:
Statement n;
The following program demonstrates the use of nested if-else statement up to a
deeper level. This program will accept the marks of a student and will display
the grade accordingly.
# include<iostream.h>
void main ()
{
int marks;
char grade;
printf (“\n Enter your marks:”);
scanf (“% d”, & marks”);
if (marks > = 90)
grade = ‘0’;
else
if (marks > = 80)
grade = ‘D’;
else
if( marks > =75)
grade = ‘M’;
else
if (marks > = 60)
grade = ‘I’;
else
if (marks > =50)
grade = ‘II’;
else
if (marks > 40)
100
B.Com.(CA) C++
grade = ‘III’;
else
grade = ‘F’;
cout << “\n Your grade is : “ << grade;
}
Output of the program (run 1)
Enter your marks : 77<ENTER>
Your grade : M
Note that, this whole section of code is actually one statement that is comprised
of six hierarchically nested is else constructs, so there is no need to put them in
the braces. At any time during the general top to bottom execution of these
expressions, if an expression evaluates to true, then the associated statement
will be executed and control flow will pass to the statement immediately
following the entire nested chain.
Although, the indentation scheme presented in this program is technically
correct and there is nothing wrong with the program. However, this style of
programming is not recommended as nested-ness up to a deeper level is difficult
to read. An Alternate way to represent these nested if-else constructs is by using
else-if construct.
As mentioned earlier, the expressions are evaluated in top-down approach. If
any expression evaluates to true, then the statement associated with it is
executed and control passes to the statement next. If none of the expression
evaluates to true then the statement in the last else (i.e. statement x) will be
executed and then control will pass to statement next. Though this construct
involves nothing new, it only utilizes the free-form nature of C++ to represent
constructs. An else-if construct is nothing, but a well indented nested if-else
constructs only.
The above situation could also be handled using simple if with logical operator
&& (AND). The following program shows the same.
#include<iostream.h>
void main ()
{
int marks;
char grade;
cout << “\n Enter your marks.”;
cin >> marks;
if (marks > = 90) grade = ‘O’;
if (marks > = 80 & & marks < 90) grade = ‘D’;
101
B.Com.(CA) C++
The goto statement causes the execution to jump to a specified line of code. The
target line of code is specified using a statement label as explained in the
following program.
#include <iostream>
int main()
{
double x;
ComeHere:
cout << “Enter a non-negative number”;
cin >> x;
if (x < 0.0)
goto ComeHere; // this is the goto statement
cout << “The number is positive “;
}
102
B.Com.(CA) C++
There are some restrictions on goto use. For example, you can’t jump forward
over a variable that’s initialized in the same block as the goto as shown in the
following code.
int main()
{
goto skip; // invalid forward jump
int x = 5;
skip:
x += 3; // error: x is still not initialized or declared
return 0;
}
It is for this reason use of goto is avoided in C++ and most other high level
languages. There are better ways of achieving the same effect without using goto.
This you will learn in the looping section.
The switch statement is another convenient tool provided by C++ to handle the
situations in which multiple decisions to be made based on an expression that
can have multiple values. Switch is a multiple branch statement that
successively tests the value of an expression against a list of case values and
when a match is found, the statement associated with the particular case is
executed. The general form of a switch-case statement may book like as:
switch (expression)
{
case value1: statement1;
case value2: statement2;
case value3: statement3;
:
case valuen: statementn;
[default: statementx ;]
}
statementnext;
Where switch is a keyword and the expression is any expression that evaluates
to an Control Flow integer value, may be int type, or char, or long. The case is a
keyword followed by value1, value2, value n where value1, value2, .. value n may
be integer or character constant, normally referred to as case labels. And the
103
B.Com.(CA) C++
104
B.Com.(CA) C++
Note that there is no need to put braces with the individual case labels as they
each contains single statement, although a pair is required to group the entire
case section. You must have observed during the execution of the previous
program that the control continues to execute all the statements once a case has
been matched, irrespective of the fact whether those statements belong to the
case that has been matched or not. This flow procedure is known as “Fall
Through” execution. Generally the “Fall through” execution approach is not
derivable at all because at a particular instance one or only a few blocks of
statement one required. In order to overcome the problem of “Fall Through”, the
following C++ statements can be used:
• goto
• if-else
• break
The use of goto statement is discouraged as detailed earlier. The use of if-else is
not recommended as the next approach is more simplified. Though the break
statement is discussed in detail in the coming section, but it is worth
mentioning over here that the use of break statement causes an exit from the
switch statement and the control passes to the statement next without executing
the statements of the other case labels.
In general it is advisable to use the break statement whenever exclusion of case
statement is required. However, a break statement does not require to be put in
the default case as the control moves to the statement next automatically after
executing the last statement of switch construct.
The following program shows the use of break statement in the switch case
construct. This program does a similar job as in the above program, but this
time output would not be same as break statement in used as and when
required.
#include<iostream.h>
void main ()
{
int num;
cout<<“\n Enter any number between 1 and 5 : “;
cin>>num;
switch (num)
{
case 1 : cout<<“\n One”;
break;
case 2 : cout<<“\n Two”;
break;
105
B.Com.(CA) C++
Note that in a switch statement, braces are not needed to group the statements
with in an individual case as control continuously executes the statements
following the selected case until the break statement or the end of the switch
statement is reached.
106
B.Com.(CA) C++
#include<stdio.h>
void main ()
{
char vowel ;
cout<<“\n Enter any vowel :”;
cin>>vowel;
switch (vowel)
{
case ‘A’ :
case ‘a’ : cout<<“\n The A”; break;
case ‘E’ :
case ‘e’ : cout<<“\n The E”; break;
case ‘I’ :
case ‘i’ : cout<<“\n The I”; break;
case ‘O’ :
case ‘o’ : cout<<“\n The O”; break;
case ‘U’ :
case ‘u’ : cout<<“\n The U”; break;
default : cout<<“\n Not a vowel”;
}
}
The output of the program (run 1):
Enter any vowel : i<ENTER>
The I
Note that as soon as the expression matches any of the case labels, execution will “Fall
Though” the following statement until it reaches to the break statement.
Besides the above-mentioned usages of switch case construct, various other
possibilities also exists. The following segment of codes not only provide you a
few useful tips about the usage of switch but also some important points that
should be taken care while using it.
The case labels must be an int constant or a char constant as the switch
statement can only marks for equality compressions. One cannot have a case
label consist of relational or logical expression, the following case label
case a < = 2:
is not allowed in a switch statement.
107
B.Com.(CA) C++
A switch statement can also be put within another switch statement, called as
nested switch statement. For example, the following snippet of code is absolutely
right in C++.
switch (outer)
{
case 1 : switch (inner)
{
case ‘a’ : ————
case ‘b’ : ————
:
}
case 2: break ;
:
}
The case labels must not be a floating point value as given below:
switch (value)
{
case 1.1: _
_
case 1.2: _
_
:
}
The case labels must not be a string as given below:
switch (value)
{
case “string1”: _
_
case “string2”: _
_
:
}
108
B.Com.(CA) C++
The default case may appear anywhere in the switch case construct. But may
required a break statement if used somewhere else than the end point of a
switch case construct. For example, the following code fragment is allowed in
C++.
switch (exp)
{
default : _
break;
case 1 : _
_
case 2 : _
_
:
}
No two case labels in the same switch can have similar values. However, this is
allowed in case of nested switch statement i.e. outer case label and the inner
case label may have same values. Though it is not necessary to put the case
labels in a particular order, they may appear according to the user specifications
as shown below:
switch (value)
{
case 4 : _
_
case 1 : _
_
default : _
_
case 2 : _
_
:
}
The Conditional Operator
Conditional operator, denoted by (? : ), is a ternary operator (requiring three
operands) which could be used as an alternate to the if-else statement as both of
them provide a control flow capacity. Its syntax is,
<conditional_expression> ? statement1 : statement2;
109
B.Com.(CA) C++
110
B.Com.(CA) C++
8.3 LOOPING
Looping statements are also known as iterations because the program execution
typically iterates through the statement more than once. In this category C++
provide the following statement or you call loops.
• for loop
• while loop
• do- while loop
Looping must not continue indefinitely as an analogy to real life you would not
like to crack the same joke again and again, so a mechanism is required to
break out the loop and to allow the executives of the next set of statements.
Therefore, a general structure has been devised for the implementation of a loop
statement. Which can be more understood by understanding the various
elements/parts /components of a loop that controls the number of repetitions as
given below:
• Initial Expression(s): Initial expression(s) is usually an assignment
expression(s) which initializes the control variable(s) of a loop, as they must
be initialized before entering in a loop. The initial expression(s) is executed
only once, in the beginning of the loop. But if this expression(s) occurs in
the loop body, control variable(s) would be reassigned to initial values with
every loop pass, and the condition expression would never fail.
• Condition Expression: Conditional expression is typically a relational
expression that is set up to terminate the execution of a loop. If the
condition expression evaluate, to true i.e. 1, the loop body gets executed,
otherwise the loop is terminated. A condition expression may be evaluated
before entering in to a loop or before exiting from the loop called as entry-
controlled loop and exit controlled loop respectively. In C++, the for loop
and while loop are entry-controlled loops where as do while loop is exit-
controlled loop.
• Update Expression(s): The update expression(s) is essentially an increment
expression or decrement expression that changes the value(s) of loop
variable(s), so that they could come to the boundary values.
The update expression(s) normally execute at the end of the loop body. It may
appear in the body of loop as it is an updating expression that assigns the
variable a new updated value every time the loop passes.
• The Loop Body: The loop body consists of statement(s) that is suppose to
be executed again and again as long as the condition expression evaluator
to true i.e.
1. In an entry-controlled loop, the condition expression evaluated first and if it
evaluates to true, the loop-body is executed and if it evaluate to false, the
loop-body is terminated. Where as, in exit controlled loop, the loop body
executed first and Control Flow then the condition expression is evaluated.
It is evaluate to false i.e. o, the loop is terminated, otherwise repeated.
111
B.Com.(CA) C++
The for loop in C++ is the simplest, fixed and entry controlled loop. It is simplest
as the structure of for loop is divided into two segments i.e. control statement
and the body of the loop. All its loop control elements are placed together in the
control statement where as body of the loop consists of statements to be
executed repeatedly.
It is fixed as number of repetitions is known is advance and can be useful in a
situation when you want to do something a fixed number of times.
It is an entry controlled loop as the control statement placed before the loop
body i.e. condition expression will be evaluated first. The general form of the far
loop is:
for( initial expression(s) ; condition expression ; update expression(s))
loop-body;
For example, consider the following statement:
for(i=1; i<= 10; ++I)
cout<<”\n Example of FOR loop”;
where i is an integer variable declared already.
i=1;
is an initial expression.
i <= 10;
is a conditional expression.
++i;
is an update expression. And the statement
cout<<“\n Example of FOR loop”) ;
is the body of the loop.
When the above statement is encountered during program execution, the
following events occur:
• Initial expression is evaluated first and i will be assigned an initial value 1
i.e.i =1.
• Then the condition expression is evaluated i.e. i<=10 and the result will be
true as 1<=10 is true.
112
B.Com.(CA) C++
• Since the condition expression is true, the statement in the loop body is
executed i.e. cout<<“\n Example of FOR loop”; which prints the message
“Example of FOR loop” on the screen.
• After the execution of the loop body, the update expression i.e. ++i is
executed which increment the value of i by 1. In this way after the first
execution of the loop the value of i becomes 2 as initially it was 1.
• After the execution of the update expression the condition expression is
again evaluated. If it evaluates to true the sequence is repeated from step
no. 3, otherwise the loop terminates.
Note that after a certain repetition the condition expression evaluates to false, as
the value of i will be greater then 10, then loop will be terminated and the output
of the code may appear as:
Let’s write a complete program that demonstrates the use of for loop.
#include<iostream.h>
void main()
{
int i ; //declaring variable
for ( i=-1; i<=5; ++i)
cout<<“\n “<< i; }
Output:
1
2
3
4
5
Note that the control statement (for(i = 1,i<=5; ++i)) should not end with the
semicolon, Control Flow otherwise is will be treated as an empty loop disused
later in this unit. Here’s another program another which gives you an idea about
the for loop capabilities. This program
will print the sum of first 5 natural numbers.
#include<iostream.h>
void main()
{
int i , sum = 0; // the variable sum and I is declared of type int
// sum is initialized to 0
for(i = 1; i<=5;++ i)
113
B.Com.(CA) C++
{
sum = sum + i ;
}
cout<<“\n The sum of first 5 natural numbers is “<<sum;
}
Output:
The sum of first 5 natural numbers is 15
What should be the contents of a loop body, is totally depends upon the logic.
Let’s write the previous program of printing the largest value among four
numbers once again by using simple if with for loop. This approach is more
desirable as the algorithm is quite simple, resultant a less complex code.
#include<iostream.h>
void main()
{
int i, num, max = 0 ;
cout<<“\n Enter any four numbers \n”;
for (i = 0; i < =3; i ++)
{
cout<<num;
if (num > max)
max = num ;
}
cout<<“\n highest = “<< max;
}
Output:
Enter any four numbers
5
4
3
8
highest = 8
Note that here the variable i is used as a counter variable which counts the
repetition of the loop 4 times as initially i = 0 to i < =3. In order to receive four
number we have to repeat the loop 4 times and the counter variable may have
114
B.Com.(CA) C++
initially assigned with any value. And so the condition expression can also be
set. For instance, the control statement
may be written as:
for ( i =10; i < = 13 ; i++)
Let’s explore the different possibilities of using for loop as C++ offer several
variations that increase the flexibility and applicability of for loop. The following
segment of code not only provides you a better understanding of the concept but
also give you some guidelines for using for loop.
• In the previous examples the for loop is used to count up i.e. incrementing
a counter from one value to another. You also can use it to countdown i.e.
decrementing the counter variable . For e.g.,
• You can also update the counter by a value other than 1, say by 5 as given
below:
• The for loop is quite flexible you can skip any of these (initialization
expression, conditional expression or update expression) or all of these
from the control statement. For example, you can skip the initialization
expression if the particular variable has been initialized previously in the
program, but you must use the semi colon separator as shown below:
int i = 1;
• Similarly you can also omit the updation expression as shown below:
int i = 1;
for ( ; i < = 10; )
{
++i;
}
Consider another example as
for ( i =1, i ! = 99; )
cin>>num;
According to the above statement the loop will execute until the user enter 99.
This approach of coding can be apply to user the for loop as a variable loop
rather than fixed.
115
B.Com.(CA) C++
• As you know the initialization expression executed once when the for
statement in first reached. After that it doesn’t required for the rest of
process. If the particular variable has been declared and initialized
previously in the program, then this place can be used for any valid C++
expression. For example, the code segment
i=1;
for (cout<<“\n Output ); i < = 10; ++ i)
cout<< i;
Will produce the same output i.e. printing of first 10 natural numbers.
• Another example of missing updation expression could be as given below.
These statements will also cout first ten natural number on the monitor.
int i = 1 ;
for (i = 1; i < = 10; )
cout<<i++;
• An infinite for loop can be created by skipping the conditional expression as
show below:
for (i = 100; ; — i)
cout<<“ \n Infinite loop”;
• An infinite for loop can also be written as given below:
for ( ; ; )
cout<<“ Infinite loop”;
• Following is also the example of infinite loop as it accepts the numbers
continuously from the user.
for ( cin>>i; ; i ++)
• First ten natural numbers could also be print as the monitor by using the
following code:
for ( i = 1; i++ < 10; )
cout<<i;
• If a for loop doesn’t contain even a single statement in the loop body is
called an empty loop. For example, the following loop
for (i = 0; i < 10000 ; i ++);
is an empty loop and can be used as time delay loop, which are often used
in programs.
• By even writing an empty loop still you can print first ten natural number
on the monitor by mentioning all the work to be done in the for statement
itself, as given below:
for (i = 1; i < = 10; cout<<i++ ));
116
B.Com.(CA) C++
• A for loop may contain multiple expressions in initialization section and /or
updation section, must be separated by commas. The following code
demonstrate the use of multiple expression in initialization sections.
for ( i = 1, j = 10; i < = j ; + + i.)
cout<< i;
The output of the above code is to similar as printf first 10 natural numbers.
• The following for statement illustrates the use of multiple expressions in
updation section:
for (i = 1, j = 10 ; i < = j ; ++i, - - j)
cout<<”\ni = ”<<i<< “ j = “<< j;
The output of the above code is as follow:
i = 1 j = 10
i=2j=9
i=}j=8
i=4j=7
i=5j=6
• A conditional expression can not have multiple expression like initialization
and updation expression, but it may contain several conditions linked
together using logical operators. For example, consider the following for
loop:
int i = 1;
int j = 10;
for ( ; (i < = j) & & (j > = i) ; )
cout<<“\ni = “<<i++<< “ j = “<<j—;
The execution of the loop body in depends upon the individual values of both the
sub expressions as they both are true then only cout statement will be executed.
In case any sub expression evaluates to false the loop will be terminated as both
the sub expressions are link together using && (AND) relationship.
• An infinite loop can also be configured by missing the updation expression
as shown below:
for (i = 1 ; i < = 10; )
cout<<“\n”<<i;
• In all the examples given above, the control variables of the loop has been
assigned with integer values. However, it is not necessary as control
variable can even be a float. Following is the example of incrementing a
counter using floating point value:
for (i = 0.0; i < 0.9; i = i + 0.1)
cout<<i;
117
B.Com.(CA) C++
The second type of loop, the while loop is an entry controlled loop as it tests the
conditions first and if the condition is true, then only the control will enter into
the loop body. When each iteration of the loop is finished, the control returns to
the while statement which perform the condition test again as so on. But if the
condition in false the first time, no iteration of the loop executes and control
passes to the statement next to loop statement. In this way it is a sort of variable
loop as we do not know the exact number of iteration. The statements repeats
over and over until certain specified conditions are met. The while loop has the
following form:
while (condition expression)
loop_body;
The while loop doesn’t explicitly contain the initialization expression and update
expressions of the loop. These two expressions are normally provided by the
programmers as the initialization expression(s) should be placed before the loop
begins and updation expression(s) should be inside the loop body. By using all
these expressions the general farm of while loop may looks like as:
:
initialization expression(s);
while (conditional expression)
{
:
Loop Body
updation expression;
}
For example, consider the following segment of code:
i = 1;
while(i <= 10)
{
cout<<“\n Welcome to SDE, BU”;
++i;
}
where i is an integer variable declared already
118
B.Com.(CA) C++
i = 1; is an initial expression
i <= 10; is a conditional expression
++i; is an update expression.
The statements between the { and } form the body of the loop. But the braces can
be discarded, if there is only one statement in the loop body. When the program
executes the while statement, the following events occur:
• First of all the conditional expression is evaluated i.e. i < 10.
• The conditional expression is evaluated to true as i was 1 initially and 1 <
10 is true. But if it evaluate to false, the loop will be terminated and the
control moves to the first statement following loop body.
• Since the condition expression is true, the loop body will be executed i.e.
the cout statement and the updation expression.
• With the closing braces ( } ), it is assumed that the loop is finished and the
control moves back to the while statement, which repeats the test again
and proceeds accordingly.
Note that next time due to the updation expression the value of i will be 2 as
previously it was 1. With the every next execution the value of I will be
increased. After a certain repetitions the conditional expression evaluates to
false as the value of i will be greater than 10. Then this loop will be terminated.
The output as this code may appear as:
SDE, BU
SDE, BU
.
.
SDE, BU (10 times)
Here’s another program which gives you an idea about the while loop
capabilities. This program will print the sum of as many numbers as user wants.
#include<iostream.h>
void main ()
{
int num, sum = 0;
char reply = ‘y’;
while ( reply == ‘y’)
{
cout<<“\n Enter the number to add:”;
cin>>num;
119
B.Com.(CA) C++
• The while loop can also be written without the initialization expression and
the updation expression. However, this is the real use of while loop. For
example.
120
B.Com.(CA) C++
• A while loop can also be implemented using floating point values. For
example, consider the following code:
i=0.0 ;
while ( i< =0.9)
121
B.Com.(CA) C++
{
cout<<”\n “<<i;
i = i + 0.1 ;
}
The above code will print the numbers from 0.0 to 0.9 on the monitor.
The do-while loop is an exit controlled loop i.e. it tests the conditions after
having executed the statement with in loop body. This means unlike the for and
while loops, a do-while loop always executes at least once. The statement of the
do-while loop is as follows:
do
{
loop-body ;
} while (conditional expression);
The braces { } can be discarded when the loop-body contains a single statement.
The do-while loop iterates the loop body as long as the specified condition is true
while testing the condition at the end of the loop each time, rather than at the
beginning, as is done by the for and the while loop.
Like while loop, do-while loop also doesn’t contain the initialization and updation
expression as part of loop statement. However, these expressions can be
associated with do-while loop by the programmer according to required logic.
Then the new form of do-while loop may look like as:
Initialization expression(s);
For example consider the following code segment:
int i=1;
do
{
cout<<“\n Welcome to SDE”;
++i;
} while (i<=10);
122
B.Com.(CA) C++
When the program control reaches a do while loop, the following events occur.
• The loop-body will be executed, i.e., the cout statement and the updation
statement.
• The conditional expression will be evaluated i.e. i <=10.
• The conditional expression will evaluates to true as the value as i is 2 this
time (initial i=1).
• Since the condition expression is true, the control will move back to execute
the loop-body once again.
Note that after a certain repetition the condition expression will evaluates to
false as the value as i will be greater than 10, the loop will be terminated. The
output of the above code may look likes as:
Welcome to SDE
Welcome to SDE
:
Welcome to SDE (10 times)
The do-while loop is well suited for the problems where number of repetitions is
not known in advance. But this is sure that the loop will be executed at least
once. Let’s write a complete program that demonstrate the use of a do-while
loop. This program will print the first 10 natural number using do while loop.
#include<iostream.h>
void main()
{
int i = 1;
do
{
cout<<“\n “<<i;
++i ;
} while(i<=5); }
Output:
1
2
3
4
5
Note that the statement while (i<=10) must end with a semicolon. Otherwise
system may flag the compile time error.
123
B.Com.(CA) C++
While writing the program to print the sum of as many numbers as user wants,
using while loop, you must have observed that in order to evaluates the
condition expression as true the very first time, the control variable has been
initializes before the loop accordingly.(i.e. reply = ‘y’).
The break statement is used in a program to skip the particular part of program
code. The general format of the break statement is
break;
The break is a keyword in C++ and the semicolon must be placed after the break
statement. The break statement is normally used in the switch case and in the
loop statements. The use of a break statement in the switch-case has been
presented earlier in this unit. Let s see how the break statement affects the loop
s execution.
The break statement can be placed only in the body of a for loop, while loop, or
do-while Control Flow loop. When a break statement is encountered, execution
exits the loop. For example inside the following loop statement:
for(int i = 1; i < 10; ++i)
{
if ( i > 5 ) break;
cout<<“\n Welcome to SDE”);
}
The string “Welcome to SDE” would be displayed 5 times as when the value of i
will be greater than 5 (i.e. i = 6) , the break statement will be executed, causes
the for loop to terminate. Execution resumes at the statement immediately
following the for loop’s closing braces.
A loop may contain multiple break statements associated with different
conditions. But only one break statement may be executed in a particular
iteration. If no break is executed, the loop terminates normally. For examples
consider the following segment of code.
for (i = 1; i <= 10; ++i)
{
if (i < 5) break; // first break statement
if (i > 5) break; // second break statement
cout<<“\n”<<i;
}
In the above example, at any time, if possible only one break statement executes
and causes the control to break the loop by skipping rest of the statements in
the loop. This code prints only the number 5 in output.
124
B.Com.(CA) C++
Sometimes, instead of braking a loop, you want to stay in a loop but skip one or
some statements with in the loop. Another C++ keyword “continue” can be used
to serve the purpose.
Another jump statement “continue” is the compliment of the break statement.
Instead of forcing termination, it causes the control to jump to the beginning of
the loop. The statements between the continue statement and the end of the
loop aren’t executed. The general syntax of the continue statement is as follows:
continue ;
Unlike break, the continue keyword cannot be used in switch statement. The
continue statement can only be used in the body of a for loop, a whole loop, or a
do- while loop. Consider the following segment of code, which demonstrate the
working of a continue statement :
for(int i = 1; i <= 2; ++i)
{
if(i % 2 != 0) continue ;
cout<<“\n”<<i;
}
The above code will output the first 10 natural even numbers, instead of first 20
natural numbers. In case of an odd number, the conditional expression
evaluates to true. Thus the statement continues, forces the control to be move
back at the beginning of the loop without executing the rest of the statements in
the loop.
When a continue statement is encountered inside a nested loop, then the control
is passed to the beginning of the inner loop and all the subsequent statements
with in the inner loop are not executed. For example, consider the following
segment of code:
for(i = 1; i <= 10; ++i)
{
cout<<“\n”;
for(int j = 1; j <= 5; j++)
{
if(j > i) continue ;
cout<<j;
}
}
125
B.Com.(CA) C++
The output of the above code will be similar to the previous one as:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
But this time the inner loop is not terminated as in the case of break statement
rather it is continued with the next updated value. As soon as the value of j
becomes greater than i, the continue statement pass the control back to the
beginning of the enclosing loop by simply ignoring the rest of the statement in
the same loop. However using continue for this program is not desirable at all as
it iterates the loop even if it is not required.
An infinite loop can be caused by continue statement as shown below:
i=1;
while(i <= 10)
{
cout<<“\n”<<i;
continue;
++i;
}
In the above example, the value of i never get incremented as the continue
statement is placed before the updatation expression, which causes the control
back to the starting of the loop without executing the subsequent statements.
Therefore loop will be executed infinitely.
• The for loop in C++ is the simplest, fixed and entry controlled loop.
• An infinite for loop can be created by skipping the conditional expression.
• A conditional expression can not have multiple expression like initialization
and updation expression, but it may contain several conditions linked
together using logical operators.
• The while loop is an entry controlled loop as it tests the conditions first and
if the condition is true, then only the control will enter into the loop body.
• An empty loop can also be configured using while statement and could
used as a time delay loop.
126
B.Com.(CA) C++
• The do-while loop is an exit controlled loop i.e. it tests the conditions after
having Control Flow executed the statement with in loop body. Unlike the
for and while loops, a dowhile loop always executes at least once.
• The break statement is used in a program to skip the particular part of
program code.
• Continue is the compliment of the break statement. Instead of forcing
terminateon, it causes the control to jump to the beginning of the loop.
• The goto statement in C++ causes a program control to jump immediately
to an executed statement elsewhere in the function.
Check Your Progress
1. What is switch statement? Define.
............................................................................................................................
............................................................................................................................
2. Differentiate conditional operator and if-else construct?
............................................................................................................................
............................................................................................................................
8.5 KEYWORDS
127
B.Com.(CA) C++
128
B.Com.(CA) C++
LESSON-9
FUNCTIONS IN C++
CONTENTS
9.0 Aims and Objectives
9.1 Introduction
9.2 Function in C++
9.3 Function Components
9.3.1 Function Arguments
9.3.2 Default Arguments
9.4 Library Functions
9.4.1 Function Invocation Methods
9.4.2 Call by Value
9.4.3 Call by Reference
9.4.4 Recursion
9.5 Inline Functions
9.6 Let us Sum up
9.7 Keywords
9.8 Questions for Discussion
9.9 Suggested Readings
Function is the main action module in C++ programming. This chapter deals
with different aspects of functions. At the conclusion of this chapter you should
be able to:
• Describe functions
• Explain the purposes of each component of a function
• Use library functions of C++
• Use inline function
9.1 INTRODUCTION
The programs that solve real world problems are much larger than the programs
which we discussed yet. These large programs may raise the problems of
complex algorithm, implementation, debugging and increased errors in program.
129
B.Com.(CA) C++
Experience has shown that the best way to develop and maintain a large
program is to construct it from small piece or modules each of which itself is a
complete unit. Actually the heart of problem solving is the program
decomposition i.e. taking a problem and breaking it into small and manageable
pieces called functions. Functions are the building blocks of C++ and the place
where all program activity occurs. In C++, functions are used to implement the
'top-down' method of programming. In this unit, we'll discuss about functions
and its various types and also the technique to write our own functions.
Functions, once written, can be used just as its returned value. It can be used
anywhere its return value can be used. It can form, for example, a part of an
expression. Whenever a function name is mentioned it is said to be called to
which it returns the value it computes.
130
B.Com.(CA) C++
Individual inputs to a function are called its arguments or parameters. These are
the values on which the codes housed in the function body and churn out a
value from them. A function is defined in the following general form:
<returntype> <functionname> (<comma separated parameter list>)
{
Body_of_the_function
}
The returntype specify the type of data that the function returns. A function may
return Functions any type of data except an array. By default, the return type of
a function is int, if no explicit data type is specified for the function. Function-
name should follow the rule of naming in C++. The parameter list is a comma
separated list of variable names and their associated types. A function can also
be defined without parameters, in which case the parameter list is empty. While
passing the arguments, variable list should be written with their data types.
Everything before the first brace comprises the header of the function definition
and everything between the braces comprises the body of the function definition.
An example is,
// A function to calculate factorial of a number
int fact(int a)
{
int f = 1,i;
for(i = 1; i < = a ; i++)
f = f * i;
return(f);
}
We'll call the function as fact(5). The function takes this value (5), carries out the
compute its factorial and returns 120 as a result.
While dealing with user defined functions, there are three important points to
remember:
1. Function prototype
2. Function definition
3. Function calling
A function prototype is a model for a function that will appear later in a
program. A function proto type contains the name of the function, a list of
variables that must be passed to it and the types of variable it returns if any.
131
B.Com.(CA) C++
The purpose of function proto type is to help the compiler check whether the
data types of arguments passed to a function match what the function expects.
The compiler issues an error message if the data types do not match. Optionally
it can contain the names of variables that will be passed. A proto type should
always end with a semicolon.
The first line of function definition (is function header) should be identical to the
function prototype. A function header should not end with a semicolon. If the
function return type is anything other than void then return statement should
be included in the function definition.
A function can be called as many as times as needed and the function can be
called in any order.
132
B.Com.(CA) C++
• In the above example a1, a2, a3, a4 are the formal arguments and p, q, r, s,
k are the actual parameters.
• Lets conclude what we've learnt so far:
• Every C++ program contains at least one function i.e. main().
• There can be any number of functions in a program but the program
execution will start with main.
• A function can be called any number of times in main() or in any other
function.
• While dealing with functions, two different types of arguments are there i.e.
formal and actual.
• The order of execution of functions depends on the order of function call.
Lets consider one complete example Functions
// Program to find the given number is prime or not.
// A prime number is divisible by 1 and number only
#include<iostream.h>
void prime(int n); // prototype of prime function
void main()
{
int p;
cout<<"\n Enter the number:");
cin>>p;
prime(p) ; //calling prime function;
}
void prime(int n)
{
int i, flag = 0;
for (i = 2; i<= n/2 ; i++)
{
if(n %i == 0)
{
flag = 1; break;
}
if(flag == 0)
cout<<"Given number is prime";
else
cout<<" Number is composite";
}
133
B.Com.(CA) C++
Till now each program we have presented has consisted of a function called
main that called standard library function to accomplish its task. The functions
allow the programmer to modularize the program. There are various benefits for
using functions.
• The divide and conquer approach makes program development more
manageable.
• It avoids the repetition of code in a program.
• Program becomes less prone to errors and hence easy debugging.
C++ functions can have arguments having default values. The default values are
given in the function prototype declaration. Whenever a call is made to a
function without specifying an argument, the program automatically assigns
values to the parameters as specified in the default function prototype
declaration.
134
B.Com.(CA) C++
The function rchar() is called 10 times in the main( ) function with different
number of arguments passed to it. This is allowed in C++.
The first function call to rchar() takes no arguments in the main() function. The
function declaration provides default values for the two arguments required by
rchar(). When values are not provided, the compiler supplies the defaults '*' and
10. In the second call, one argument is missing which is assumed to be the last
argument. rchar() assigns the single argument '=' to the ch parameter and uses
the default value 10 for num.
In the third case, both arguments are present and no defaults are considered. A
few points worth remembering here.
The missing or default arguments must be the trailing arguments, those at the
end of the argument list. The compiler will flag an error when you leave
something out. Default arguments may be useful when an argument has the
same value.
void abc (int a, float b, int c = 10, char d = 'P'); //correct defaulting!
void abc (int a, float b = 2.5, int c, char d = 'P'); //incorrect defaulting!
135
B.Com.(CA) C++
A program is made up of one or more function definitions with one of these being
main(). Program execution always begins with main(). When program control
encounters a function name, the function is called or invoked. This means that
program control passes to that function. After the function does its work,
program control is passed back to the calling environment, which then
continues with its work. Functions are invoked by writing their name and an
appropriate list of arguments within parenthesis. These are two ways to invoke
functions:
• Call by Value
• Call by Reference
Call by Reference method needs introduction of pointers, which we will cover in
coming section.
136
B.Com.(CA) C++
argument must match the parameters in the function header and prototype. If
you try to pass a function an incorrect number or type of argument, the compiler
will detect it, based on the information provided in function prototype.
If a function has multiple arguments, the first actual argument value will pass to
first formal argument and so on.
In call by value method the values are being copied into the formal arguments
from the actual arguments.
Function call func(a, b) ;
Function header void func(int m, int n)
a b
6 8 actual arguments
6 7 formal arguments
137
B.Com.(CA) C++
swap(p, q);
cout<<"\n The nos. after swapping "<<p<<" "<<q;
}
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
Output:
Enter two numbers: 5 7
The nos. before swapping are 5 7
The nos. after swapping one 7 5
In above example the changes done in function are not reflected back in the
main. In such case, this type of requirement can be fulfilled by call by reference
method.
138
B.Com.(CA) C++
139
B.Com.(CA) C++
As you can see with this example, inside the function the pointers are used to
access the actual arguments used in the call. This means that changes made to
the parameter affect the argument. Reference parameters are not supported by
C. Whereas C++ uses reference parameter to implement call by reference.
9.4.4 RECURSION
The programs we have discussed are structured as functions that call one
another in a disciplined hierarchical manner. But for some type of problems, it is
required to have functions which call themselves only. This is called recursion
which is formed from the word recur means repetition.
When a procedure is called itself the function is said to be directly recursive. But
if function A() calls function B() and then B() calls function A(), this process is
said to be indirectly recursive. Indirect recursion is also called chain recursion.
Indeed, it takes a great deal of practice writing recursive programs before the
process will appear natural. To make our concepts more clear lets us take a
recursive program to perform a popular mathematical function i.e. factorial.
140
B.Com.(CA) C++
For example,
5! = 5 * 4 * 3 * 2 * 1 can be written as
5! = 5 × (4 × 3 × 2 × 1)
5! = 5 × 4!
The evaluation of 5! would proceed with product of 5 with 4! and product of 4
with 3!
and so on.
So definition of factorial function will be number * fact (number - 1); Check the
complete program listed below.
#include<iostream.h>
long fact(long);
int main()
{
int i = 5 ;
long result ;
result = fact(5);
cout<< "\n the factorial of 5 is "<<result;
return(0);
}
long fact (long number)
{
if(number == 1)
return(1);
else
return(number * fact(number - 1));
}
Although recursion seems to offer the possibility of improved efficiency, often
recursive routines do not significantly reduce code size or improve memory
utilization. Also the recursive version of most routines may execute a bit slower
than their iterative equivalents because of the overhead of repeated function
calls. In fact many recursive calls to a function could cause a stack overrun.
The main advantage of recursive function is that you can use them to create
clearer and simple version of several algorithms.
141
B.Com.(CA) C++
For another example, let us write a C++ program to generate fibonacci series.
The fibonacci series is given by:
0, 1, 1, 2, 3, 5, 8, 13, 21
It begins with 0 and 1 and has property that each subsequent fibonacci number
is sum of previous two fibonacci numbers.
i.e.
fibonacci (0) = 0
fibonacci (1) = 1
fibonacci (n) = fibonacci (n - 1) + fibonacci (n - 2)
Here is the program.
#include<iostream.h>
long fibonacci(long);
int main()
{
long result, numb;
cout<<"\n Enter an integer ";
cin>>numb;
result = fibonacci(numb);
cout<<"\n fibonacci("<<numb<<")="<<result;
return (0);
}
long fibonacci ( long n)
{
if (n = = 0 || n = = 1)
return (n);
else
return (fibonacci (n - 1) + fibonacci (n - 2) ) ;
}
Here is a dry run of the same program.
finonacci(4)
return(fibonacci(3) + fibonacci(2))
return(fibonacci (2) + fibonacci (1))
return fibonacci (1) + fibonacci (0))
return (1) return (0)
142
B.Com.(CA) C++
Instructions are executed step by step unless there are any loop or branching
instructions. When there is branch or jump instruction, some instructions are
skipped and forward or backward jump is made.
143
B.Com.(CA) C++
float b;
cout <<" Enter a number";
cin >> b;
a = square(b); .
cout << "\nThe square of " << b << "is " << a;
}
You should see the output as shown below.
Enter a number 1.2
The square of 1.2 is 1.44
C++ supports inline functions. An in-line function can be written in C++ like
this:
inline int max (int a, int b)
{
if (a > b)
return a;
else
return b;
}
a = max (x, y); // This is now equivalent to "a = (x > y ? x : y);"
• Functions are the building blocks of C++ and the place where all program
activity occurs. In C++, functions are used to implement the 'top-down'
method of programming. A function is a named, independent section of C++
code that performs a specific task and optionally returns a value to the
calling program. A function represents a unit of processing and therefore it
forms the basis of any procedural programming language.
• Functions, once written, can be used just as its returned value. It can be
used anywhere its return value can be used. It can form, for example, a
part of an expression.
• The return type specify the type of data that the function returns. A
function may return any type of data except an array. By default, the
return type of a function is int, if no explicit data type is specified for the
function.
144
B.Com.(CA) C++
• Function-name should follow the rule of naming in C++. The parameter list
is a comma separated list of variable names and their associated types. A
function can also be defined without parameters, in which case the
parameter list is empty.
9.7 KEYWORDS
145
B.Com.(CA) C++
146
B.Com.(CA) C++
LESSON-10
CLASSES AND OBJECTS
CONTENTS
10.0 Aims and Objectives
10.1 Introduction
10.2 Class Specification
10.3 Accessing Class Members
10.4 Defining Member Functions
10.5 Data Hiding
10.5.1 A C++ Program with Class
10.5.2 Nesting of Member Functions
10.5.3 Static Data Members
10.5.4 Static Member Functions
10.6 Let us Sum up
10.7 Keywords
10.8 Questions for Discussion
10.9 Suggested Readings
Classes and objects are at the heart of OOP which is the topic of discussion in
this chapter. At the conclusion of this unit you should be able to:
• Describe the features of OOP
• Describe a class
• Describe various class relationships
• Define base class and derived class
10.1 INTRODUCTION
147
B.Com.(CA) C++
As has been explained earlier at various places, classes and objects are at the
core of object-oriented programming in general and programming C++ in
particular. Writing programs in C++ essentially means writing classes and
creating objects from them. In this chapter you will learn to work with the same.
It is important to note the subtle differences between a class and an object, here.
A class is a template that specifies different aspects of the object it models. It
has no physical existence. It occupies no memory. It only defines various
members (data and/or methods) that constitute the class.
You can think of a class as a data type; and it behaves like one. Just as a data
type like int, for example, does not have a physical existence and does not
occupy any memory until a variable of that type is declared or created; a class
also does not exist physically and occupies no memory until an object of that
class is created.
car
reg_no = DL2C2245
no_wheels = 4
fuel_type= PETROL
make = MARUTI
color = WHITE
scooter
Vehicle reg_no= DL2A1056
reg_no; no_wheels = 2
no_wheels; fuel_type = PETROL
fuel_type; make = BAJAJ
make; color = CREAM
Class
truck
reg_no = DL3D2259
no_wheels = 6
fuel_type = DIESEL
make = TATA
color=DARK
ORANGE
Objects
148
B.Com.(CA) C++
In this example vehicle is a class while car, scooter and truck are instances of
the class vehicle and hence are objects of vehicle class. Each instance of the
class vehicle - car, scooter and truck - are allocated individual memory spaces
for the variables - reg_no, no_wheels, fuel_type, make and, color - so that they
all have their own copies of these variables.
How was the TV made? The management of the TV company decided that it
should have certain attributes and behave in a certain way. These decisions
were documented vehicleas blueprint, which was used to make TV. The
blueprint in OOP is called class. All Classes and Objects objects belong to some
class that defines their attributes and behaviors. An object is an instance of a
class. In OOP, classes have attributes represented by data members. For
example, a TV has an attribute called size, which may have value 14 inches and
a state (on/off).
The attributes distinguish an object of the class. Classes have behaviors, which
are represented as methods. The methods define how an object acts or reacts.
Let us see with this example how OOP features are emulated by a TV class
below:
1. Real world: The real world consists of objects like books, tables, chairs and
TV. The same concept has been introduced into programming, bringing it
closer to real life.
149
B.Com.(CA) C++
C++ offers a data type called class. The user defined data type, class,
distinguishes C++ from traditional procedural language. A class is a new data
type that is created to solve a particular kind of problem. Once a class is created
anyone can use it, without knowing the specifics of how it works or even how a
class is built.
Class is the core building block of a C++ program. It represents a real world
object template concealing data and revealing member functions to be used by
other classes. It resembles a C structure but has a number of extended features
that make it an object oriented programming entity. A class may be defined as
follows.
150
B.Com.(CA) C++
In either case an object of class abc type named pqr is created. Just what
happens when an object of a class is created is discussed in what follows.
The class keyword is used to declare a class. The braces are used to indicate the
start and end of a class body. Member variables and member functions are
declared inside the class body. A semicolon is used to end the declaration.
Example
# include <iostream.h>
class car
{
...
};
int main()
{
car ford;
...
return (0);
}
Note that C++ is case-sensitive language meaning that upper case letters are
different from lower case letters. Thus, Class is different from class.
Class members belong to one of the three categories - Public or Private or Friend.
Private members are not accessible from outside the class. Privatizing the class
members is the fundamental way of implementing OOP's data hiding. Public
members, however, are accessible from outside the class. Friend members are
discussed later. Consider, for instance, the following class.
class employee
{
private: int EmpNum;
char name[20];
public: int batchNum;
};
int main()
{
employee one; //create an object -one- of class employee
151
B.Com.(CA) C++
The example describes how a member can be referred to using dot (.) operator.
The employee class, as defined here, has two private data members - EmpNum
and name.
Since these are private to the class they cannot be accessed from outside the
class. Classes and Objects Point to be noted here is that once you specify the
public (or private keyword) with a colon, all the following members will be
defined public (or private) until private (or public) keyword appears. If you do not
mention either keyword the default remains private as shown below.
class employee
{
int EmpNum; //private member
char name[20]; //private member
public: int batchNum;
};
Similar to data members private and public keywords are also applicable on the
class functions (also called methods in some literatures) with identical meaning
as shown in the following C++ program.
#include <iostream.h>
class employee
{
private: int EmpNum;
char name[10];
int StoreInEmpNum(int);
public: int batchNum;
int ReadEmpNum()
{
cout << EmpNum;
return 0;
};
};
152
B.Com.(CA) C++
int main()
{
employee one;
one.StoreInEmpNum(200); //Incorrect! Accessing private member
//from outside the class
one.ReadEmpNum(); //Correct! Public members are accessible
//from outside the class
return 0;
}
As you must have noticed, a member function can be defined either as public or
private. Moreover a member function can be coded inside the class definition as
shown above or it can be coded outside the class definition using double-colon
(::) de-referencing mechanism as shown below.
#include <iostream.h>
class employee
{
private: int EmpNum;
char name[10];
int StoreInEmpNum(int);
public: int batchNum;
int ReadEmpNum();
};
Int employee::ReadEmpNum()
{
cout << EmpNum;
return 0;
}
int main()
{
employee one;
one.StoreInEmpNum(200); //Incorrect! Accessing private member
//from outside the class
one.ReadEmpNum(); //Correct! Public members are accessible
//from outside the class
return 0;
}
153
B.Com.(CA) C++
Moreover, the members can be coded anywhere in the file provided proper de-
referencing is employed. In the following program for example, the member is
coded after the main function.
#include <iostream.h>
class employee
{
private: int EmpNum;
char name[10];
int StoreInEmpNum(int);
public: int batchNum;
int ReadEmpNum();
};
int main()
{
employee one;
one.StoreInEmpNum(200); //Incorrect! Accessing private member
//from outside the class
one.ReadEmpNum(); //Correct! Public members are accessible
//from outside the class
return 0;
}
Int employee::ReadEmpNum()
{
cout << EmpNum;
return 0;
}
Private data members are visible inside the class therefore they can be accessed
inside the class as shown in the following program.
class employee
{
private: int EmpNum;
char name[20];
public: int batchNum;
int StoreInEmpNum(int e)
154
B.Com.(CA) C++
{
EmpNum=e;
};
};
155
B.Com.(CA) C++
};
void MyNumber::MyPrint();
{
cout << "Output from MyPrint member";
return 0;
};
int MyNumber::StoreInOne(int e)
{
one=e;
return 0;
};
The definitions of the member functions can be all at one place or may be
dispersed anywhere in the file.
156
B.Com.(CA) C++
The data members - EmpNum and name - being private to the class are hidden
from outside world. Thus, the following is incorrect.
int main()
{
employee one;
one.EmpNum = 200; //Incorrect! Accessing private member
//from outside the class
return 0;
}
However, the private members can be accessed by the member function –
ReadEmpNum and StoreInEmpNum - as shown below.
int main()
{
employee one;
one.StoreInEmpNum(200); //Correct!
cout << one.ReadEmpNUm(); //Correct!
return 0;
}
Care must be taken, however, to define the member functions themselves as
public otherwise they cannot be accessed from outside as shown below.
class employee
{
private: int EmpNum; //cannot be ever accessed from outside
char name[10];
int StoreInEmpNum(int e)
{
EmpNum = e;
return 0;
};
int ReadEmpNum()
{
return EmpNum;
};
};
157
B.Com.(CA) C++
Let us now have a look at a C++ program with a class. The following program
shows how the member function getdata() is defined within the class. The class
date in the program represents the day, month and year of a date. The function
written to initialize the same is defined within the class.
#include<iostream.h>
#include<conio.h>
class date
{
private :
int day, mth, yr;
public:
void getdata(int dl, int ml, int yl)
{
day = dl;
mth = ml;
yr = y1 ;
}
void disp(void)
{
cout<<"Today's date is-" << day << "/" << mth << "/" << yr << "\n";
} };
void main()
{
class date today;
today.getdata(15,8,2004);
today.disp();
getche();
}
You should see the output as:
Today's date is-15/8/2004
A member function may call another member function. This is called nesting of
functions. A member function can access not only the public functions but also
the private functions of the class it belongs to.
158
B.Com.(CA) C++
Member data items of a class can be static. Static data members are data objects
that are common to all objects of a class. They exist only once in all objects of
this class. The static members are used when the information is to be shared.
They can be public or private data. The main advantage of using a static
member is to declare the global data which should be updated while the
program lives in memory.
When a static member is declared private, the non-member functions cannot
access these members. But a public static member can be accessed by any
member of the class. The static data member should be created and initialized
before the main function Classes and Objects control block begins.
For example, consider the class account as follows:
class account
{
private:
159
B.Com.(CA) C++
160
B.Com.(CA) C++
Just as data members can be static, member functions can also be static. A
static function is a member function of a class and it manipulates only static
data member of the class. It acts as global for members of its class without
affecting the rest of the program. Static members serve the purpose of reducing
the need for global variables by providing alternatives that are local to a class.
A static member function is not a part of objects of class. It is instance
dependent and can be accessed directly by using the class name and scope
resolution operator. If it is declared and defined in a class, the keyword static
should be used only in declaration part.
The following program demonstrates the use of static member function which
accesses static data. The data member count and the function disp( ) are
declared static in the class counter. But the variable count is initialized to 0
outside the class.
#lnclude <iostream.h>
#lnclude <conin.h>
class counter
{
private:
static int count;
public:
counter()
{
++count;
}
static void disp();
};
int counter::count=0;
void counter::disp()
161
B.Com.(CA) C++
{
cout << count << "\n";
}
main()
{
cout << " Number of objects created before=";
counter::disp(); //Calling function disp() belonging to class counter
counter cntl, cnt2, cnt3, cnt4, cnt5;
cout << " Number of objects created recently=";
counter::disp();
getche();
}
You should get the following output on running the program.
Number of objects created before=0
Number of objects created recently=5
In defining static functions you should take some precautions. A static member
functionscannot be a virtual function. Virtual functions will be discussed in
detail later. A static or non-static member function cannot have the same name
and same arguments type.
• Class represents a group of similar objects broadly. A class in C++ binds data
and associated functions together. A class in C++ makes a data type using
which objects of this type can be created. Classes can represent the real-
world object which have characteristics and associated behavior.
• While declaring a class, four attributes are declare data members, member
functions program access levels (private public, and protected,) and class tag
name. While defining a class its member functions can be either defined
within -the class definition of outside the class definition. The public member
of a class can be accessed outside the data directly by using object of this
class type. Private and prototyped members can be accessed with in the class
by the member function only. H member function of a class is also called a
method. The qualified name of a class member is a class name: class member
name.
• A global object can be declared only from a global class where as a local
object Classes and Objects can be declared from a global as well as a local
class. The object are created separately to store their data member. They can
be passed to as well as returned from functions. The ordinary member
functions can access both static as well as ordinary member of a class.
162
B.Com.(CA) C++
10.7 KEYWORDS
163
B.Com.(CA) C++
164
B.Com.(CA) C++
UNIT – III
165
B.Com.(CA) C++
166
B.Com.(CA) C++
LESSON-11
ARRAY OF OBJECTS
CONTENTS
11.0 Aims and Objectives
11.1 Introduction
11.2 Array of Objects
11.3 Objects as Function Arguments
11.4 Returning Objects
11.5 Friend Functions
11.6 Class Relationship
11.7 Types of Relationships
11.7.1 Types of Relationships
11.7.2 Base Class and Derived Class (Super class and Sub class)
11.8 Let us Sum up
11.9 Keywords
11.10 Questions for Discussion
11.11 Suggested Readings
Classes and objects are at the heart of OOP which is the topic of discussion in
this chapter. At the conclusion of this unit you should be able to:
• Describe the features of OOP
• Describe a class
• Describe various class relationships
• Define base class and derived class
11.1 INTRODUCTION
As has been explained earlier at various places, classes and objects are at the
core of object-oriented programming in general and programming C++ in
167
B.Com.(CA) C++
It is important to note the subtle differences between a class and an object, here.
A class is a template that specifies different aspects of the object it models. It
has no physical existence. It occupies no memory. It only defines various
members (data and/or methods) that constitute the class.
You can think of a class as a data type; and it behaves like one. Just as a data
type like int, for example, does not have a physical existence and does not
occupy any memory until a variable of that type is declared or created; a class
also does not exist physically and occupies no memory until an object of that
class is created.
An array is a user defined data type whose members are of the same type and
stored in continuous memory locations. Just as one can create an array of any
basic data type, one can also create arrays of objects.
168
B.Com.(CA) C++
char designation[20];
char address[30];
float salary;
int age;
public:
void salary( );
void gecinfo( );
void display_info( );
};
employee obj[200]
The following program illustrates the use of array of objects to store information
of students. The program declares a class student having data members - roll
no., age, height and weight, and two functions to get and display this
information. Since information of more than one student is stored, an array of
objects that is std[max] is created.
//array of class objects
# include <iostream.h>
# include <conio.h>
#define max 30
class student
{
private:
int rollno;
int age;
float height, weight;
public:
void getinfo( )
{
cout << "roll no: ";
cin >> rollno;
cout << "age: ";
cin >> age;
cout << "Height: ";
cin >> height;
cout << "Weight: ";
cin >> weight;
169
B.Com.(CA) C++
}
void disinfo( )
{
cout << endl;
cout <<" Roll no ="<< rollno<< endl;
cout << " Age ="<< age << endl;
cout << " Height =" << height << endl;
cout <<" Weight = " << weight << endl;.
}
};
void main ( )
{
student std[max]; // arrary of objects having max = 30
int i, n;
cout << "How many students? \n" << endl;
cin >> n;
cout << "enter the student details \n" << endl;
for(i=0; i < n; ++i)
{.
cout << endl;
std[i].getinfo();
}
cout <<" The list of student's is as follows \n";
for (i = 0; i < n; ++i)
std[i].disinfo();
getche();
}
You should see the following when you run the program.
How many students?
1
roll no: 1
age: 18
Height: 134
Weight: 45
170
B.Com.(CA) C++
Like any other data type argument, objects can also be passed to a function. As
you know arguments are passed to a function in two ways:
• by value
• by reference
Objects can also be passed as arguments to the function in these two ways. In
the firstmethod, a copy of the object is passed to the function. Any modification
made to the object in the function does not affect the object used to call the
function. The following Program illustrates the calling of functions by value. The
program declares a class integer representing a integer variable x. Only the
values of the objects are passed to the function written to swap them.
#include <iostream.h>
#include <conio.h>
class integer
{
int x;
public:
void getdata()
{
cout << "Enter a value for x";
cin >> x;
}
void disp()
{
cout << x;
}
void swap(integer a1 , integer a2)
{
int temp;
temp = a2.x;
171
B.Com.(CA) C++
a2.x = al.x;
a1.x = temp;
}
};
main()
{
integer int1, int2;
int1.getdata();
int2.getdata();
cout <<"\nthe value of x belonging to object int1 is ";
int1.disp();
cout <<"\nthe value of x belonging to object int2 is ";
int2.disp() ;
integer int3; .
int3.swap(int1, int2); //int3 is just used to invoke the function
cout <<" \nafter swapping ";
cout <<"\nthe value ofxbelonging to object intI is ";
intl.disp();
cout <<"\nthe value of x belonging to object int2 is ";
int2.disp() ;
cout<< "\n";
getche();
}
You should get the following output.
Enter a value for x 15
Enter a value for x 50
the value of x belonging to object inti is 15
the value of x belonging to object int2 is 50
after swapping
the value of x belonging to object inti is 15
the value of x belonging to object int2 is 50
In the second method, the address of the object is passed to the function instead
of a copy of the object. The called function directly makes changes on the actual
object used in the call. As against the first method any manipulations made on
the object inside the function will occur in the actual object. The second method
is more efficient as only the address of the object is passed and not the entire
object.
172
B.Com.(CA) C++
173
B.Com.(CA) C++
Just as a function takes an object as its argument, it can also return an object.
The following program illustrates how objects are returned. The program
declares a class integer representing an integer variable x and defines a function
to calculate the sum of two integer values. This function finally returns an object
which stores the sum in its data member x.
#include <iostream.h>
#include <conio.h>
class integer
{
int x;
public:
void getdata(int x1)
{
x = x1;
}
void disp()
{
cout << x;
}
174
B.Com.(CA) C++
Object oriented programming paradigm secures data because of the data hiding
and data encapsulation features. Data members declared as private in a class
are restricted from access by non-member functions. The private data values
can be neither read nor written by non-member functions. Any attempt made
directly to access these members, will result in an error message as "inaccessible
data-type" during compilation.
175
B.Com.(CA) C++
176
B.Com.(CA) C++
Since private data members are available only to the particular class and not to
any other part of the program, a non-member function cannot access these
private data. Therefore, the friend function is a special type of function which is
used to access the private data of any class. In other words, they are defined as
non-member functions with the ability to modify data directly or to call function
members that are not part of the public interface. The friend class has the right
to access as many members of its class. As a result the level of privacy of the
data encapsulation gets reduced. Only if it is necessary to access the private
data by non-member functions, then a class may have a friend function,
otherwise it is not necessary.
Let us look at a sample program given below to access the private data of a class
by non-member functions through friend function. The program declares a
private class example representing variable x and function to input the value for
the same. The friend function to display the value of x takes an object as
argument with the help of which private variable x can be accessed.
#include <iostream.h>
#include <conio.h>
class example
{
private:
int x; .
public:
void getdata()
{
cout << "Enter the value ofx"<< "\n";
cin >> x;
}
friend void disp(example);
};
177
B.Com.(CA) C++
There are also other areas of application for friend function. The friend function
can also Classes and Objects be defined within the scope of a class definition
itself. Friend function may also have inline member functions. If the friend
function is defined in the class, then the inline code substitution is done
automatically. But if defined outside the class, then it is necessary to precede
the return type with the keyword inline to make the inline code substitution. The
following program accesses the private data of a class through a friend function
where the friend function is defined with inline code substitution.
#include <conio.h>
class example
{
private:
int x;
public:
inline void getdata();
friend void disp(example);
};
inline void example::getdata()
{
cout <<"Enter the value of x " << "\n";
178
B.Com.(CA) C++
cin >> x;
}
inline void disp(example eg) //Note the use of the keyword inline
{
cout << "Display the entered number" << eg.x << "\n";
}
main()
{
example eg1 ;
eg1.getdata();
disp(eg1);
getche();
}
You should see the output as shown below:
Enter the value of x
20
Display the entered number 20
One class can be friendly with another class. Consider two classes, first and
second. If the class first is friendly with the other class second, then the private
data members of the class first are permitted to be accessed by the public
members of the class second. But on the other hand, the public member
functions of the class first cannot access the private members of the class
second.
The general syntax of declaring the same friend function with more than one
class is:
class second;
class first
{
private:
//data members;
//member functions;
public: .
167
179
B.Com.(CA) C++
The following program demonstrates the use of the friend function which is
friendly to two classes. The function seems to calculate the sum of two objects is
declared friendly in both the classes.
#include <iostream.h>
#include <conio.h>
class two;
class one
{
intx;
public:
void getdata()
{
cout <<"Enter the value for x ";
cin >>x;
}
void disp()
{
cout<< "The value of x entered is "<< x <<"\n".
}
friend int sum( one,two);
};
class two
{
180
B.Com.(CA) C++
inty;
public:
void getdata()
{
cout <<"Enter the value for y ";
cin>>y;
}
void disp()
{
cout<< "The value of y entered is"<< y<< "\n";}
friend int sum(one, two);
};
int sum(one obj1,two obj2)
{
return(objl.x + obj2.y);
}
void main()
{
one obj11;
two obj22;
obj11.getdata();
obj11.disp();
obj22.getdata();
obj22.disp();
cout<< "the sum of two private data variables x and y is";
int tot = sum(obj 11,obj22);
cout <<tot;
getche(); .
}
You should see the output as shown below.
Enter the value for x 20
The value of x entered is 20
Enter the value for y 11
Note the forward declaration of class second. The non-member function sum() is
declared friendly to class first and class second.
181
B.Com.(CA) C++
You need to be an expert carpenter to design a wooden bridge, but you need to
known the fundamentals of wooden construction and the properties of the wood
and the carpenters who will construct the bridge. Similarly, to design a piece of
software successfully, you need fairly detailed knowledge of the chosen
programming language. A good bridge designer considers and respects the
properties of the material and resources. Similarly, a good programmer builds on
the strengths of the implementation language.
As most of the real world objects are related to each other in a variety of ways,
classes that abstract real world objects are also expected to be related to each
other. Classes, in particular, may have following types of relationships.
Mammal
Attributes: Eyes, Limbs, memory
glands Behavior: Walks
Kind of Kind of
Human Elephant
Attributes: Eyes, Limbs, memory Attributes: Eyes, Limbs, memory
glands Behavior: Walks glands Behavior: Walks
Figure 11.1
2. "Is a" relationship: The previous example depicts the relationship between
human beings and mammals. Let's take an instance of a human being and
therefore a mammal. In this case "Vibhor" (name of a gentleman) is related
to class mammal with "Is A" relation. The following figure depicts "Is A"
relationship:
182
B.Com.(CA) C++
Mammal
Attributes: Eyes, Limbs, memory
glands Behavior: Walks
Is A
Human
Attributes: Eyes, Limbs, memory
glands Behavior: Walks
Figure 11.2
Human
Attributes: Eyes, Limbs, memory
glands Behavior: Walks
Has a
Heart
Attributes: Number of chambers
Behavior: Beats
Figure 11.3
11.7.2 BASE CLASS AND DERIVED CLASS (SUPER CLASS AND SUB
CLASS)
Let us take the example of air tickets. Air tickets can be of two types - confirmed
and waiting. Both these tickets have a lot of common attributes, for example,
flight number, date, time and destination. However, a confirmed ticket would
also have a seat number, while a waiting ticket would have status.
183
B.Com.(CA) C++
Ticket
Attribute: Flight Number,
Date, Time, Destination
Behavior: Cancel
Figure 11.4
In the example above, we have incorporated the structure and behavior that is
common to the two classes to form a superclass. The superclass represents
generalized properties and the subclass represents specialization, in which
attributes and behavior from the super class are added, modified or hidden.
A super class is a class from which another classes inherit properties. A super
class shares its properties with its child classes. A sub class is a class that
inherits attributes and methods from super class.
Class represents a group of similar objects broadly. A class in C++ binds data
and associated functions together. A class in C++ makes a data type using which
objects of this type can be created. Classes can represent the real-world object
which have characteristics and associated behavior.
While declaring a class, four attributes are declare data members, member
functions program access levels (private public, and protected,) and class tag
name. While defining a class its member functions can be either defined within -
the class definition of outside the class definition. The public member of a class
can be accessed outside the data directly by using object of this class type.
Private and prototyped members can be accessed with in the class by the
member function only. H member function of a class is also called a method.
The qualified name of a class member is a class name: class member name.
A global object can be declared only from a global class where as a local object
Classes and Objects can be declared from a global as well as a local class. The
object are created separately to store their data member. They can be passed to
as well as returned from functions. The ordinary member functions can access
both static as well as ordinary member of a class.
184
B.Com.(CA) C++
11.9 KEYWORDS
185
B.Com.(CA) C++
LESSON-12
CONSTRUCTORS AND DESTRUCTORS
CONTENTS
12.0 Aims and Objectives
12.1 Introduction
12.2 Constructors
12.3 Parameterized Constructors
12.4 Constructors with Default Arguments
12.5 Copy Constructors
12.6 Dynamic Constructors
12.7 Destructors
12.8 Order of Constructor & Destructor calls
12.9 Let us Sum up
12.10 Keywords
12.11 Questions for Discussion
12.12 Suggested Readings
12.1 INTRODUCTION
When an object is created all the members of the object are allocated memory
spaces. Each object has its individual copy of member variables. However the
data members are not initialized automatically. If left uninitialized these
members contain garbage values. Therefore it is important that the data
members are initialized to meaningful values at the time of object creation.
Conventional methods of initializing data members have lot of limitations. In this
chapter you will learn alternative and more elegant ways initializing data
186
B.Com.(CA) C++
12.2 CONSTRUCTORS
A Programmer can also define constructor methods for a class if she so desires.
While writing a constructor function the following points must be kept in mind:
1. The name of constructor method must be the same as the class name in
which it is defined.
2. A constructor method must be a public method.
3. Constructor method does not return any value.
4. A constructor method may or may not have parameters.
Let us examine a few classes for illustration purpose. The class abc as defined
below does not have user defined constructor method.
class abc
{
int x,y;
}
main()
{
abc myabc;
…;
}
187
B.Com.(CA) C++
The main function above an object named myabc has been created which
belongs to abc class defined above. Since class abc does not have any
constructor method, the default constructor method of C++ will be called which
will initialize the member variables as:
myabc.x=0
and
myabc.y=0.
Let us now redefine myabc class and incorporate an explicit constructor method
as shown below:
class abc
{
int x,y;
public:
abc(int, int);
}
abc::abc(int a, int b)
{
x=a;
y=b;
}
Observed that myabc class has now a constructor defined to except two
parameters of integer type. We can now create an object of myabc class passing
two integer values for its construction, as listed below:
main()
{
abc myabc(100,200);
…;
}
In the main function myabc object is created value 100 is stored in data variable
x and 200 is stored in data variable y. There is another way of creating an object
as shown below.
main()
{
myabc=abc(100,200);
…;
}
188
B.Com.(CA) C++
Both the syntaxes for creating the class are identical in effect. The choice is left
to the programmer.
There are other possibilities as well. Consider the following class differentials:
class abc
{
int x,y;
public:
abc();
}
abc::abc()
{
x=100;
y=200;
}
In this class constructor has been defined to have no parameter. When an object
of this class is created the programmer does not have to pass any parameter and
yet the data variables x,y are initialized to 100 and 200 respectively. Finally, look
at the class differentials as given below:
class abc
{
int x,y;
public:
abc();
abc(int);
abc(int, int);
}
abc::abc()
{
x=100;
y=200;
}
abc::abc(int a)
{
x=a;
189
B.Com.(CA) C++
y=200;
}
abc::abc(int a)
{
x=100;
y=a;
}
Class myabc has three constructors having no parameter, one parameter and
two parameters respectively. When an object to this class is created depending
on number of parameters one of these constructors is selected and is
automatically executed. Note that C++ selects one constructor by matching the
signature of the method being called. Also, once you define a constructor
method, the default constructor is overridden and is not available to the class.
Therefore you must also define a constructor method resembling the default
constructor method having no parameters.
Check Your Progress
List points to be kept in mind, while writing a constructor function.
............................................................................................................................
............................................................................................................................
190
B.Com.(CA) C++
This method is used to initialize object with user defined parameters at the time
of creation. Consider the following Program that calculates simple interest. It
declares a class interest representing principal, rate and year. The constructor
function initializes the objects with principal and number of years. If rate of
interest is not passed as an argument to it the Simple Interest is calculated
taking the default value of rate of interest
#include<iostream.h>
#include<conio.h>
class interest
{ int principal, rate, year;
float amount;
public
interest (int p, int n, int r = 10);
void cal (void);
};
interest::interest (int p, int n, int r = 10)
{ principal = p; year = n; rate = r;
};
void interest::cal (void)
{
cout<< "Principal" <<principal;
cout << "\ Rate" <<rate;
cout<< "\ Year" <<year;
amount = (float) (p*n*r)/100;
cout<< "\Amount" <<amount;
};
main ( )
{
interest i1(1000,2);
interest i2(1000, 2,15);
clrscr( );
il.cal();
i2.cal();
}
Note the two objects created and initialized in the main( ) function.
191
B.Com.(CA) C++
interest i1(1000,2);
interest i2(1000,2, 15);
The data members principal and year of object i1 are initialized to 1000 and 2
respectively at the time when object i1 is created. The data member rate takes
the default value 10 whereas when the object 12 is created, principal, year and
rate are initialized to 1000,2 and 15 respectively. It is necessary to distinguish
between the default
constructor::construct();
and default argument constructor
construct : : construct (int = 0)
The default argument constructor can be called with one or no arguments. When
it is invoked with no arguments it becomes a default constructor. But when both
these forms are used in a class, it causes ambiguity for a declaration like
construct C1; The ambiguity is whether to invoke construct: : construct ( ) or
construct: : construct (int=O)
192
B.Com.(CA) C++
abc myabc1(1,2);
abc myabc2;
myabc2=myabc1;
Allocation of Memory during the creation of objects can be done by the con
structures too. The memory is saved as it allocates the right amount of memory
for each object (Objects are not of the same size). Allocation of memory to objects
at the time of their construction is known as dynamic construction of objects.
new operator is used to allocate memory. The following program concatenates
two strings. The constructor function initializes the strings using constructor
function which allocates memory during its creation.
#include <iostream.h>
#include <string.h>
class string
{
char * name;
intlength;
public:
string 0
{
length = 0;
name = new char [length = 1];
};
string (char*s)
{
length = strlen (s);
name = new char [length + 1];
strcpy(name,s );
};
void display (void)
{
cout<<"\n Name :- "<<name;
};
193
B.Com.(CA) C++
The above program uses new operator to allocate memory. The first constructor
is an empty constructor that allows us to declare an array of string. The second
constructor initializes length of the string, allocates necessary space for the
194
B.Com.(CA) C++
string to be stored and creates the string itself. The member function join ( )
concatenates 2 strings It actually adds the length of 2 strings and then allocates
the memory for the combined string. After that the join function uses inbuilt
string functions strcpy & strcat to fulfil the action.
The output of the program will be in Full Name and Half name That is Mohan
Singh Kumar and Ram Singh respectively. Another example of the dynamic
constructor is the matrix program. In two Dimensional matrix we need to
allocate the memory for the values to be stored in. Using constructor we can
allocate the memory for the matrix.
This program declares a class matrix to represent the number of rows and
columns of matrix as well as two dimensional array to store the contents of
matrix. the constructor function used to initialize the objects allocates the
required amount of memory for the matrix.
#include<iostream.h>
#include<conio.h>
//Class Definition
class matrix
{
int **p; //declaring two dimensional array
int dl,d2;
public:
matrix(intx,inty);
void get_value( void);
void dis_value( void);
void square(void);
void cube(void);
};
matrix: : matrix( int x,int y)
{
dl=x;
d2=y;
p= new int *[d1];
for (int i =0;i<d1 ;i++)
p[i]=new int[d2];
};
void matrix:: get_value(void)
{
for(int i = 0;i<d1;i++)
195
B.Com.(CA) C++
for(int j=0;j<d2;j++)
{
cout<<"Please Enter A No At"<<i<<j<< "Position :-";
cin>>p[i][j];
}
};
voidmatrix:: dis_value(void)
{
cout< <"The Matrix Entered";
for (int i = 0;i<d1 ;i++)
{
cout< <"\n";
for(int j=0;j<d2;j++)
cout<<"\t"<<p[i] [j];
}
};
void matrix:: square(void)
{
cout < <"\n The Squared Matrix";
for (int i = 0;i<d1 ;i++ )
{
cout<<"\n";. for(intj=0;j<d2;j++)
cout<<"\t" <<p[i][j]*p[i] [j];
}
};
void matrix:: cube(void) {
cout < <"\nThe Cubed Matrix";
for (int i = 0;i<d1;i++)
{
cout<<"\n";
for(int j=0;j<d2;j++ )
cout<<"\t"<<p[i][j] * p[im] * p[i][j];
}
};
//Start Of Main Program
main()
{
196
B.Com.(CA) C++
intm,n;
elrser();
cout<<"Enter Size Of Matrix :- ";
cin> >rn>>n;
matrix mat(m,n);
mat.get_value();
mat.dis_value();
getch();
mat.square();
mat.cube();
getch();
}
197
B.Com.(CA) C++
12.7 DESTRUCTORS
Constructors create an object, allocate memory space to the data members and
initialize the data members to appropriate values; at the time of object creation.
Another member method called destructor does just the opposite when the
program creating an object exits, thereby freeing the memory.
1. Name of the destructor method is the same as the name of the class
preceded by a tilde(~).
The following codes snippet shows the class abc with the destructor method;
class abc
{
int x,y;
public:
abc();
abc(int);
abc(int, int);
~abc()
{
cout << "Object being destroyed!!";
}
}
Whenever an object goes out of the scope of the method that created it, its
destructor method is invoked automatically. However if the object was created
using new operator, the destructor must be called explicitly using delete
operator. The syntax of delete operator is as follows:
delete(object);
Note that whenever you create an object using new keyword, you must explicitly
destroy it using delete keyword, failing which the object would remain homed in
the memory and in the course of program execution there may come a time
when sufficient memory is not available for creation of the more objects. This
phenomenon is referred to as memory leak. Programmers must consider memory
leak seriously while writing programs for the obvious reasons.
198
B.Com.(CA) C++
• A destructor does just the opposite when the program creating an object
exits, thereby freeing the memory.
12.10 KEYWORDS
199
B.Com.(CA) C++
(a) Write a C++ class having five data members and overloaded constructors.
(b) Consider the following class definition.
(c) Write a C++ program to create the following class hierarchy. Provide
constructors and destructors so that when an object of a subclass is
created the order of calling the constructors and destructors is printed.
(d) If there were no constructor or destructor mechanism in C++ what all
problems could have arisen? Discuss with suitable examples.
200
B.Com.(CA) C++
LESSON-13
OPERATOR OVERLOADING
CONTENTS
13.0 Aims and Objectives
13.1 Introduction
13.2 Overloading Unary Operators
13.3 Overloading Binary Operators using Friends
13.4 Manipulation of Strings using Operator Overloading
13.5 Rules for Overloading Operators
13.6 Let us Sum up
13.7 Keywords
13.8 Questions for Discussion
13.9 Suggested Readings
13.1 INTRODUCTION
C++ provides a rich collection of various operators. You have already seen the
meaning and uses of many such operators in previous chapters. One special
feature offered by C++ is operator overloading. This feature is necessary in a
programming language supporting objects oriented features.
201
B.Com.(CA) C++
You know that additional operator (+) is essentially a numeric operator and
therefore, requires two number operands and evaluates to a numeric value equal
to the sum of the two operands. Evidently this cannot be used in adding two
strings. We can extend the operation of addition operator to include string
concatenation. It implies that the addition operator would work as follows:
"COM" + "PUTER"
should produce a single string
"COMPUTER"
202
B.Com.(CA) C++
void disp(void);
void operator- (); // overload unary operator minus
};
void integer:: getdata (int a, int b, int c)
{
x=a;
y=b;
z=c;
}
void integer::disp (void)
{
cout << x << " ";
cout<< y<<" ";
cout<< z<< "\n";
}
void integer:: operator- () // Defining operator- ()
{
x = -x;
y =-y;
z = -z;
}
main 0
{
integer S;
S.getdata(11,-21,-31);
Cout<< "S: ";
S.disp ( );
-S;
cout<< "s : ";
S.disp ( );
getch( );
}
203
B.Com.(CA) C++
Note the function written to overload the operator is a member function. Hence
no argument is passed to the function. In the main() function, the statement -S
invokes the operator function which negates individual data elements of the
object S. The same program can be rewritten using friend function. This is
demonstrated in the following Program. In this program we define operator
function to perform unary subtraction using a friend function.
#include<iostream.h>
#include<conio.h>
class integer
{
intx;
int y;
intz;
public:
void getdata(int a, int b, int c);
void disp(void);
friend void operator- (integer &s ); // overload unary minus
};
void integer::getdata (int a, int b, int c)
{
x = a;
y = b;
z = c;
}
void integer::disp (void)
{
cout << x << " ";
cout << y <<" ";
cout << z << "\n";
}
void operator- (integer &s ) // Defining operator- ( )
204
B.Com.(CA) C++
{
s.x = -S.x;
s.y = -s.y;
s.z = -S.z;
}
main 0
{
integer S;
S.getdata(11 ,-21 ,-31);
Cout<< "S: ";
S.disp ( );
-S; //activates operator-( )
cout<< "S : ";
S.dis ( );
getch ( );
}
You should see the following output.
S: 11 -21 -31
S : -11 21 31
Binary Operators are operators which require two operands to perform the
operation. When they are overloaded by means of member function, the function
takes one argument, whereas it takes two arguments in case of friend function.
This will be better understood by means of the following program.
The following program creates two objects of class integer and overloads the +
operator to add two object values.
#include <iostream.h>
#include <como.h>
class integer
{
private :
int val;
public:
205
B.Com.(CA) C++
integer ();
integer(int one );
integer operator+ (integer objb);
void disp ();
};
integer :: integer ()
{
val = 0;
}
integer:: integer (int one)
{
val = one;
}
integer integer:: operator+ (integer objb)
{
integer objsum;
objsum.val = val+objb. val;
return (objsum);
}
void integer:: disp ( )
{
cout<< "value ="<< val<< endl;
}
void main ()
{
integer obj1 (11);
integer obj2 (22);
integer objsum;
objsum = objl +obj2;
obj1.disp ();
obj2.disp ( );
objsum.disp ( );
getch ( );
}
206
B.Com.(CA) C++
# include<iostream.h>
# include<conio.h>
class str
{
char *name;
public:
str ( );
str (char *);
void get ( );
void show ( );
str operator + (str);
};
str :: str ( )
{
name = new char [1];
}
str :: str (char *a)
207
B.Com.(CA) C++
{
int I = strlen (a);
name = new char [i + 1];
strcpy (name, a);
}
str str :: operator + (str b)
{
int I = strlen (name) + strlen (s. name);
str tmp;
tmp. Name = new char [i+1];
strcpy (tmp.name, name);
strcat (tmp.name, s.name);
return tmp;
}
void str :: get ( )
{
cin >> name;
}
void str :: show ( )
{
cout << name;
}
main ( )
{
clrscr ( );
str S3;
str S1 ("SDE");
str S2 ("Bharathiar University");
S3 = S1 + S2;
S3.show ( );
}
208
B.Com.(CA) C++
Operator Purpose
. Class member access
operator
.* Class member access
operator
:: Scope Resolution Operator
?: Conditional Operator
Sizeof Size in bytes operator
# Preprocessor Directive
= Assignment operator
0 Function call operator
0 Subscripting operator
-> Class member access
operator
• Overloading an operator does not change its basic meaning. For example
assume the + operator can be overloaded to subtract two objects. But the
code becomes unreachable.
class integer
{intx, y;
public:
int operator + ();
}
int integer: : operator + ( )
{
return (x-y);
}
209
B.Com.(CA) C++
Operator Purpose
= Assignment operator
() Function call operator
[] Subscripting operator
-> Class member access
operator
In this lesson, we have seen how the normal C++ operators can be given new
meanings when applied to user-defined data types. The key words operator is
used to overload an operator, and the resulting operator will adopt the meaning
supplied by the programmer. Closely related to operator overloading is the issue
of type conversion.
13.7 KEYWORDS
210
B.Com.(CA) C++
211
B.Com.(CA) C++
LESSON-14
TYPE CONVERSIONS
CONTENTS
14.0 Aims and Objectives
14.1 Introduction
14.2 Type Conversions
14.3 Basic to Class Type
14.4 Class to Basic Type
14.5 One Class to Another Class Type
14.6 Let us Sum up
14.7 Keywords
14.8 Questions for Discussion
14.9 Suggested Readings
14.1 INTRODUCTION
212
B.Com.(CA) C++
When the objects are of the same class type, the operations of addition and
assignment are carried out. In this case of class object, that the values of all the
data members of the right-hand object are simply copied into the corresponding
members of the object on the left hand. The user defined data types are
designed by us to suit our requirements, the compiler does not support
automatic type conversions for such data types.
In a mixed expression constants and variables are of different data types. The
assignment operations causes automatic type conversion between the operand
as per certain rules. The type of data to the right of an assignment operator is
automatically converted to the data type of variable on the left. Consider the
following example:
int x;
float y = 20.123;
x=y;
This converts float variable y to an integer before its value assigned to x. The
type conversion is automatic as far as data types involved are built in types. We
can also use the assignment operator in case of objects to copy values of all data
members of right hand object to the object on left hand. The objects in this case
are of same data type. But of objects are of different data types we must apply
conversion rules for assignment.
Three type of situations might arise in the data conversion between
uncompatible types.
• Conversion from basic type to class type
• Conversion from class type to basic type
• Conversion from one class type to another class type
A constructor was used to build a matrix object from an int type array. Similarly,
we used another constructor to build a string type object from a char* type
variable. In these examples constructors performed a defacto type conversion
from the argument's type to the constructor's class type.
This constructor builds a string type object from a char* type variable a. The
variables length and name are data members of the class string. Once you define
the constructor in the class string, it can be used for conversion from char* type
to string type.
Example
string s1 ,s2;
char* name1 = "SDE - BHARATHIAR UNIVERSITY";
213
B.Com.(CA) C++
214
B.Com.(CA) C++
The constructor functions do not support conversion from a class to basic type.
C++ allows us to define a overloaded casting operator that convert a class type
data to basic type. The general form of an overloaded casting operator function,
also referred to as a conversion function, is:
operator typename()
{
//Program statement
}
This function converts a class type data to typename. For example, the operator
double() converts a class object to type double, in the following conversion
function:
vector:: operator double()
{
double sum = 0;
for(int I = 0; i<size; i++)
sum = sum + v[i] * v[i ]; //scalar magnitude
return sqrt(sum);
}
The casting operator should satisfy the following conditions.
• It must be a class member
• It must not specify a return type.
• It must not have any arguments. Since it is a member function, it is
invoked by the object and therefore, the values used for, Conversion inside
the function belongs to the object that invoked the function. As a result
function does not need an argument.
In the string example discussed earlier, we can convert the object string to char*
as follows:
string:: operator char*()
{
retum(str);
}
215
B.Com.(CA) C++
We have just seen data conversion techniques from a basic to class type and a
class to basic type. But sometimes we would like to convert one class data type
to another class type.
Example
Objl = Obj2 ; //Obj1 and Obj2 are objects of different classes.
Obj1 is an object of class one and Obj2 is an object of class two. The class two
type data is converted to class one type data and the converted value is assigned
to the Obj1. Since the conversion takes place from class two to class one, two is
known as the source and one is known as the destination class.
Such conversion between objects of different classes can be carried out by either
a constructor or a conversion function. Which form to use, depends upon where
we want the type-conversion function to be located, whether in the source class
or in the destination class.
We studied that the casting operator function Operator typename() Converts the
class object of which it is a member to typename. The type name may be a built-
in type or a user defined one(another class type). In the case of conversions
between objects, typename refers to the destination class. Therefore, when a
class needs to be converted, a casting operator function can be used. The
conversion takes place in the source class and the result is given to the
destination class object.
Let us consider a single-argument constructor function which serves as an
instruction for converting the argument's type to the class type of which it is a
member. The argument belongs to the source class and is passed to the
destination class for conversion. Therefore the conversion constructor must be
placed in the destination class.
The following Figure illustrates the above two approaches.
Figure 14.1: Conversion between Objects
The table in Figure 14.1 summarizes all the three conversions. It shows that the
conversion from a class to any other type (or any other class) makes use of a
casting operator in the source class. To perform the conversion from any other
type or class to a class type, a constructor is used in the destination class.
216
B.Com.(CA) C++
217
B.Com.(CA) C++
{return price;}
operator float()
{
retum(item*price);
}
};
class stock2
{
int code;
float val;
public:
stock20
{
code=0;val=0;
}
stock2(int x,float y)
{
code=x;val=y;
}
void disp()
{
cout<< "code" <<code <<"\n";
cout<<"Total Value Rs." <<val <<"\n";
}
stock2(stockl p)
{
code=p.getcode();
val=p.getitem() * p.getprice();
}
};
void main()
{
stock1 i1(101, 10,125.0);
218
B.Com.(CA) C++
stock2 i2; .
float tot_val;
tot_val=i1 ;
i2=i1 ;
cout<<" Stock Details-stockl-type" <<"\n";
i1.disp();
cout<< " Stock value" << "\n";
cout<< tot_val<< "\n";
cout<< " Stock Details-stock2-type" << "\n";
i2.disp();
getch();
}
You should get the following output.
Stock Details-stock1-type
code 101
Items 10
Price per item Rs.125
Stock value
1250
Stock Details-stock2-type
code 10 1
Total Value Rs.1250
219
B.Com.(CA) C++
In this lesson, we have seen how the normal C++ operators can be given new
meanings when applied to user-defined data types. Closely related to operator
overloading is the issue of type conversion. Some conversions take place between
user defined types and basic types. Two approaches are used in such
conversion: A one argument constructor changes a basic type to a user defined
type, and a conversion operators converts a user-defined type is converted to
another, either approach can be used.
14.7 KEYWORDS
220
B.Com.(CA) C++
LESSON-15
FUNCTION OVERLOADING
CONTENTS
15.0 Aims and Objectives
15.1 Introduction
15.2 Overloading a Function
15.3 Restrictions for Overloading Operators
15.4 Let us Sum up
15.5 Keywords
15.6 Questions for Discussion
15.7 Suggested Readings
15.1 INTRODUCTION
The C++ compiler identifies a function by its signature (function signature). The
function signature is broken down into the following components in that order.
<return type>
<function label or name>
<parameters list>
221
B.Com.(CA) C++
The parameter list is further defined as <data type> parameter label or name. If
the order of the parameters (datatype name) changes, even if the function
name/label does not change, the signature is considered unique. So, in C++, it
is conceivable to have many different functions/methods with exact same label
name (for example Function1) so long as the entire signature is considered
unique. So, changing the number of parameters, their data types, the order of
them, or any combination of these can change the function signature.
Important Note: Changing the return type ALONE is NOT considered change in
signature.
Now, answering the actual question of overloading function vs. operator:
Function Overloading: When you define many different functions (unique
signatures) which have the exact label name, it is function overloading.
For example,
void Function_Foo();
void Function_Foo(int); // Overloaded
void Function_Foo(int, int); // Overloaded
int Function_Foo(); // Error - function redefined (because only return
type is different)
Operator Overloading: In C++, basic operators are also considered functions at
a compiler level. So, when you define a different operation for an operator by
changing the standard parameter list, it is operator overloading.
For example
MyClass operator+(MyClass& cls); //Add the data members of two instances of
the same class
Sometimes it might occur that you have 2 functions that have the same name
but each do something else. If the two functions accept different type of
arguments passed in you can apply something called Function Overloading.
With Function Overloading the compiler determines what function you're calling
for by checking it's name AND the type of arguments passed in.
A example of Function Overloading in action.
#include <iostream> // Include the newest input-output stream header
#include <conio.h>
using namespace std; // So we won't have to specify this namespace to use
it's functions
void PrintaNumber(int number) // Our first function
{
cout << number;
}
void PrintaNumber(float number) // Our second Function
222
B.Com.(CA) C++
{
cout << number;
}
Consider a function print, which displays an int. As shown in the following
example, you can overload the function print to display other types, for example,
double and char*. You can have three functions with the same name, each
performing a similar operation on a different data type:
#include <iostream>
using namespace std;
void print(int i) {
cout << " Here is int " << i << endl;
}
void print(double f) {
cout << " Here is float " << f << endl;
}
void print(char* c) {
cout << " Here is char* " << c << endl;
}
int main() {
print(10);
print(10.10);
print("ten");
}
The following is the output of the above example:
Here is int 10
Here is float 10.1
Here is char* ten
Function overloading based on vector parameter types is supported.
223
B.Com.(CA) C++
• Function declarations that differ only by return type. For example, you
cannot declare the following declarations:
int f();
float f();
• Member function declarations that have the same name and the same
parameter types, but one of these declarations is a static member function
declaration. For example, you cannot declare the following two member
function declarations of f():
struct A {
static int f();
int f();
}
• Member function template declarations that have the same name, the same
parameter types, and the same template parameter lists, but one of these
declarations is a static template member function declaration.
• Function declarations that have equivalent parameter declarations. These
declarations are not allowed because they would be declaring the same
function.
• Function declarations with parameters that differ only by the use of typedef
names that represent the same type. Note that a typedef is a synonym for
another type, not a separate type. For example, the following two
declarations of f() are declarations of the same function:
typedef int I;
void f(float, int);
void f(float, I);
• Function declarations with parameters that differ only because one is a
pointer and the other is an array. For example, the following are
declarations of the same function:
f(char*);
f(char[10]);
g(char(*)[20]);
g(char[5][20]);
g(char(*)[20]);
g(char(*)[40]);
224
B.Com.(CA) C++
225
B.Com.(CA) C++
int main(void)
{ // declare three variable of different types
int val1=4;
float val2=4.1;
double val3=4.123456;
// get the data from the user and call each version of function
cout << "Square of 4 is " << sqr(val1) << "\n";
cout << "Square of 4.1 is " << sqr(val2) << "\n";
cout << "Square of 4.123456 is" << sqr(val3) << "\n";
return(0);
}
// now declare the three function versions
int sqr(int x) {
return(x*x);
}
In this lesson, we have seen how the normal C++ functions can be given same
names when applied to user-defined data types. The key words function is used
to overload a function and the resulting will adopt the meaning supplied by the
programmer.
15.5 KEYWORDS
226
B.Com.(CA) C++
UNIT – IV
227
B.Com.(CA) C++
228
B.Com.(CA) C++
LESSON-16
INHERITANCE
CONTENTS
16.0 Aims and objectives
16.1 Introduction
16.2 Overview of inheritance
16.3 Motivation of Inheritance
16.4 Benefits of Inheritance
16.5 Advantages of Inheritance
16.6 Let us sum up
16.7 Keywords
16.8 Questions for discussions
16.9 Suggested Readings
The main aim of the inheritance concept in c++ programming language is that
reusability of something that already exists in program rather than trying to
create once again. It saves the time and other facts to be executed for longer
time. The reliability of the program is to be increased. General the child inherit
the property of parents like way in c++ the one class coding or statement be
reused by another class in easy way.
After completion of this unit, you should be able to:
• Define derived classes
• Define the term inheritance
• Discuss various classes of inheritance
• Make a private member inheritance
16.1 INTRODUCTION
229
B.Com.(CA) C++
Inheritance is the process by which new classes called derived classes are
created from existing classes called base classes. The derived classes have all the
features of the base class and the programmer can choose to add new features
specific to the newly created derived class. The existing class is referred to as the
base class and the new one is called as derived class or sub class.
For example, a programmer can create a base class named fruit and define
derived classes as mango, orange, banana, etc. Each of these derived classes,
(mango, orange, banana, etc.) has all the features of the base class (fruit) with
additional attributes or features specific to these newly created derived classes.
Mango would have its own defined features, orange would have its own defined
features, and banana would have its own defined features
The following are the types of inheritance exist in object oriented programming
language.
1. Single Inheritance
2. Multiple Inheritances
B
A
3. Multilevel Inheritance
230
B.Com.(CA) C++
4. Hierarchical Inheritance
B C D
5. Hybrid Inheritances
A A
A type (called a sub class or derived type) can inherit the characteristics of
another type (called a super class or base class). The term sub class is
equivalent to derived type.
A derived type acts just like the base type, expect for an explicit of
Specializations and generalizations.
231
B.Com.(CA) C++
Inheritance allows you to write code to handle certain cases and allows
other developers to write code that handles more specialized cases, while
user code continues to work.
Reusability:
Inheritance helps the code to be reused in many situations. The base class is
defined and once it is compiled, it need not be reworked. Using the concept of
inheritance, the programmer can create as many derived classes from the base
class as needed while adding specific features to each derived class as needed.
Saves Time and Effort:
The above concept of reusability achieved by inheritance saves the programmer
time and effort. Since the main code written can be reused in various situations
as needed. Increases Program Structure which results in greater reliability.
General Format for implementing the concept of Inheritance:
class derived_classname : access specifier base class name
{
……………..
……………. Members of derived class
};
232
B.Com.(CA) C++
Examples :
//Example using private access specifier
Class X : private XY
{
Members of X
};
//Example using public access specifier
Class X : public XY
{
Members of X
};
//Example using default access specifier is private
Class X : XY
{
Members of X
};
• When a class inherits from more than one base class, this is called multiple
inheritances. A class may contain objects of another class inside it. This
situation is called nesting of objects and in such a situation; the contained
objects are constructed first before constructing the objects of the enclosing
class.
Single Inheritance: Where a class inherits from a single base class, it is known
as single inheritance.
233
B.Com.(CA) C++
Multi level Inheritance: When the inheritance is such that the class. A serves
as a base class for a derived class B which is turn serves as a base class for the
derived class C. This type of inheritance is called 'Multilevel Inheritance.'
Multiple Inheritance: A class inherit the attributes of two or more classes. This
mechanism is known as Multiple Inheritance.'
Hybrid Inheritance: The combination of one or more types of the inheritance.
16.7 KEYWORDS
Abstract class: A class from which another class inherits. (Also called super
class)
Base class: A class from which another class inherits. (Also called super class)
Containership: The relationship of two classes such that the objects of a class
are enclosed within the other class.
Derived class: A class inheriting properties from another class. (also called sub
class)
Inheritance: Capability of one class to inherit properties from another class.
Inheritance Graph: The chain depicting relationship between a base class and
derived class.
Visibility mode: The public, private or protected specifier that controls the
visibility and availability of a member in a class.
Visibility Mode: The public, Private or protected specifier that controls that
controls the visibility and availability of a member in a class.
234
B.Com.(CA) C++
LESSON-17
TYPES OF INHERITANCE
CONTENTS
17.0 Aims and objectives
17.1 Introduction
17.2 Types of Inheritance
17.2.1 Single Inheritance
17.2.2 Multilevel Inheritance
17.2.3 Multiple Inheritances
17.2.4 Hierarchical Inheritance
17.2.5 Hybrid Inheritance
17.3 Let us sum up
17.4 Keywords
17.5 Questions for discussions
17.6 Suggested Readings
The main aim and objective of types of inheritance is to study about the various
types of inheritance and its relationship exits between each other. Each
inheritance types plays a major role in the object oriented programming.
After completion of this unit, you should be able to:
• Discuss various classes of inheritance
• Make a private member inheritance
17.1 INTRODUCTION
235
B.Com.(CA) C++
A derived class with only one base class is called single inheritance.
#include<iostream.h>
class X
{
int a; // private access specifier not inherited
void get();
{
cin>a;
cout<<”The value of A is”<<a;
}
public :
int b,c,d;
void get2()
{
cin>>b>>c; //Assume value of b=5 , c=15;
d=b+c;
cout<<”The sum of B and C is”<<d;
}
236
B.Com.(CA) C++
};
Class Y : public X // Public access specifier for class
{
int w,m;
public :
void mult()
{
cin>>w; // Assume value of w is 5;
m = w * 5;
cout<<”The value of M is”<<m;
}
};
Void main()
{
Y Obj;
Obj.mult();
Obj.get2();
Obj.get() // Is not accessible because is declared as private
}
The output of the program
The value od M is 25
The sum of B and C is 20
Class Y
Private section
a
Not inherited by class Y
Public section
b c d get2()
237
B.Com.(CA) C++
Mult()
Have a rights to access function
Note:
The class Y object obj have a right permission to access the methods of mult()
and have rights to access the methods of class X like get() and variable like b,c,d
and have no rights to access the variable a, due to it declared in private access
specifier.
The concept of deriving a class from another derived class is known as multilevel
inheritance.
Multilevel Inheritance
Base Class A
B
Intermediate
Class
Derived Class C
The class A serves as a base class for the derived class B, and then the class B
act as base class for the derived class C. So class B play as a intermediate class
for both class A and C.
238
B.Com.(CA) C++
…….. Statements
……… member functions
};
Example:
#include <iostream.h>
Class first
{
Protected :
int a;
public :
int b,sum1;
void get1()
{
cin>>a>>b;
}
void display1()
{
sum1= a + b;
cout<<sum1;
}
};
Class second : public first
{ Public
Access specifier
Protected :
int x;
public :
int y,sum2;
void get2()
{
cin>>x>>y;
}
239
B.Com.(CA) C++
void display2()
{
sum2= x * y;
cout<<sum2;
}
};
Class thrid : public second
{ Public
Access specifier
Protected :
int p;
public :
int q,sum3;
void get3()
{
cin>>p>>q;
}
void display3()
{
sum3= p/ q;
cout<<sum2;
}
};
From the above program is that have three classes of first, second, third and
multi level inheritance is applied. Due this concept with the help of derived class
object, user can access the member function of other base classes. So no need to
create a separate object for each class.
Note: The object of class third have rights to access the member functions of the
first and second class.
240
B.Com.(CA) C++
Class First
a
Protected : Accessed by
Object of third class
b, sum1() get( ),
public :
display1()
Class Second
Protected : Same as class first
x
y, sum2() get2( ),
public : display2()
Class Third
p
Protected :
q sum3() get3( ),
public : display3 ()
A B
241
B.Com.(CA) C++
A class can inherit the attributes of two or more classes is known as multiple
inheritance. Multiple inheritances allow us to combine the features of several
existing classes as a starting point for defining new classes. Like child inheriting
the property from parents and as well as from grandparents.
Syntax of Multiple inheritances
Class X : Public P, Q
{ Access specifier Private/Public
{
…………… Statements / Member function of X
};
Example:
# include<iostream.h>
class A
{
protected :
int a;
public :
void get1(int);
};
class B
{
protected :
int b;
public :
void get2(int);
};
class X : public A, Public B
{
public: Here class X inherit class A and B
void disp(void) (Multiple Inheritance)
};
void A :: get1 (int x) Function definition
{
242
B.Com.(CA) C++
a = x+10;
}
void B :: get2 (int y)
{
b = y+5;
}
void disp(void)
{
cout<<”The Value of a in Class A is”<<a;
cout<<”The Value of b in Class B is”<<b;
cout<<”The addition of A and B is<<a*b;
}
void main ( )
{
X obj;
obj.get1(5); calling the method with help of objects.
obj.get2(14);
obj.disp();
}
Note:
1. Here the class X has a right to access the class A and B with help of
inheritance property.
2. Each Class has a variable and member function.
3. Then each member function separately defined out side the class.
4. The object of Class X has a right to access the methods of class A and B
through the inheritance concept.
The Member functions of one class may be inherited by more than one class is
known as hierarchical inheritance.
243
B.Com.(CA) C++
B C D
Fruits
Classification of Fruits
From the above classification of course have a common is fruit and the fruit
Mango, Apple, Orange different feature, but it has common features name called
fruit. Different fruit have different taste and flavor but have a common name
called fruit as base.
In c++ programming language the problems can be easily converted into class
hierarchies. The base class will include all the features that are common to the
sub classes. A sub class can be constructed by inheriting the properties of the
base class. A sub class can serve as a base class for the lower level classes and
so on.
Example:
class root
{
public :
int a,b;
public :
void get1( )
{
244
B.Com.(CA) C++
245
B.Com.(CA) C++
obj1.dispB( );
}
Note:
1. The total number of classes declared is three. The classes are root, A and
class B.
2. The base class is root. The sub classes of different path is A and B.
3. The class A has a right to access the member functions of root class.
4. The class B also has a right to access the member function of root class
through inheritance.
5. But the one aspect is that the class A and B has interaction these classes.
6. Only the interaction between class root and their respective classes.
The hybrid type of inheritance is that combination of any one of the inheritance
exist in c++ programming. In some critical situation the standard type of
inheritance is not applicable for all the concepts. In such cases the user can use
the hybrid inheritance for their convenience. So user can easily execute any type
complex problems can be solved with the help of hybrid inheritance. This type of
inheritance can be play a role to some extent in c++ programming language.
The following the classification of the hybrid inheritance based on the user
requirements.
D B
246
B.Com.(CA) C++
Example:
Class A
{
public :
int a;
public :
void inputA( )
{
cin>>a;
}
};
Class B : public A // class B inherit the class A
{
public :
int b,sum;
public :
void inputB( )
{
cin>>b;
sum = a + b;
}
};
Class D
{
public :
int x;
public :
void dget( )
{
cin>> x;
}
};
247
B.Com.(CA) C++
Note:
The main aim of the hybrid inheritance is that combination of any type of
existing inheritance in c++. Due to this idea of formation of hybrid will help the
user to achieve, solution for any application. This type helps the user in many a
ways to get a particular solution in easies way and in short execution time. But
only one drawback is that user can’t use this hybrid inheritance for complex
problems and also in critical situations.
248
B.Com.(CA) C++
17.4 KEYWORDS
Base class: A class from which another class inherits. (Also called super class)
Containership: The relationship of two classes such that the objects of a class
are enclosed within the other class.
Derived class: A class inheriting properties from another class. (also called sub
class)
Inheritance: Capability of one class to inherit properties from another class.
249
B.Com.(CA) C++
LESSON-18
BASE CLASS AND DERIVED CLASS
CONTENTS
18.0 Aims and objectives
18.1 Introduction
18.2 Types of Base Classes
18.3 Direct Base Classes
18.4 Indirect Base Classes
18.5 Types of Derived Class
18.6 Public Inheritance
18.7 Private Inheritance
18.8 Protected Inheritance
18.8 Let us sum up
18.10 Keywords
18.11 Questions for discussions
18.12 Suggested Readings
The main aim of the inheritance concept in c++ programming language is that
reusability of something that already exists in program rather than trying to
create once again. It saves the time and other facts to be executed for longer
time. The reliability of the program is to be increased. General the child inherit
the property of parents like way in c++ the one class coding or statement be
reused by another class in easy way.
After completion of this unit, you should be able to:
• Define types of base classes and derived classes
• Define the term inheritance with secured data
• Make a private member inheritance
18.1 INTRODUCTION
250
B.Com.(CA) C++
'BASE' class and the new one is called 'DERIVED' class. Inheritance is the
process by which new classes called derived classes are created from existing
classes called base classes. The derived classes have all the features of the base
class and the programmer can choose to add new features specific to the newly
created derived class. The existing class is referred to as the base class and the
new one is called as derived class or sub class.
Normally the class consists of variables, member function and constructors and
the programming statements. Any type of class act as a base class for the
program. A class inherit the property from the root we called it as a derived
class. The same way the derived class act as a base class to another class.The
base class divided into two types, direct base and indirect base class. Each type
of base class has its own property and characteristics.
The following is the example for direct base class. A base class is called a direct
base it declared in main base level.
Example1:
Class A
{
Statements for the class A
…………..
…………..
};
Class B : Public A
{
Statements for the class B
…………..
…………..
};
Note:
From the above example1 the class A is the direct base for other classes.
Example2:
Class X
{
Statements for the class X
251
B.Com.(CA) C++
…………..
…………..
};
Class Y
{
Statements for the class Y
…………..
…………..
};
Class Z : public X, public Y
{
Statements for the class Z
…………..
…………..
};
Note:
From the above example2 is that class Z is a derived class and it’s derived the
concept from the base different base classes called class X and Y. So here the
class X and Y act as both base classes.
Example3:
Class X
{
Statements for the class X
…………..
…………..
};
Class Y
{
Statements for the class Y
…………..
…………..
};
Class Z
252
B.Com.(CA) C++
{
Statements for the class Z
…………..
…………..
};
Class D : public X, public Y, public Z
{
Statements for the class D
…………..
…………..
};
Note:
From the above example3 the base class D acts as derived class. But there is no
restriction for creating base classes. So here the class D inherits the property
from more than one base class in program.
The key idea behind the above concept is that user can create any number of
base classes for a program. Then any derived class inherits the property for their
requirements.
The above conditions are applicable in bases. But some of the following types are
invalid or not valid type in inheritance base classes.
Example1:
Class X Undeclared statements for class A
Class Y : public X
{
Statements
}
Note:
From the above type of example is that the statements for class X is not declared
or not defined, so is the user uses the inherit concept means lead to error
status.
Example2:
Class X
{
Statements for the class X
…………..
253
B.Com.(CA) C++
…………..
};
Class Y : public X, public X Multiple declaration.
{ Invalid type declaration
Statements for the class Y
…………..
…………..
};
When a derived class is declared as a base of another class, the newly derived
class inherits the properties of its base classes including its data members and
member functions. A class is called as an indirect base it is not direct base.
The following is the example for indirect base class. A base class is called a
indirect base it declared in derived class level.
Example1:
Class A
{
Statements for the class A
…………..
…………..
};
Class B : Public A
{
Statements for the class B
…………..
…………..
};
Class C : Public B
{
Statements for the class C
…………..
…………..
};
254
B.Com.(CA) C++
From the above example1 is that Class B inherit the class base class A, and also
the class C inherit the class B. From this concept is that the class B acts or
serves as a Indirect class.
Example2:
Class A
{
Statements for the class A
…………..
…………..
};
Class B : public A
{
Statements for the class B
…………..
…………..
};
Class C : public A
{
Statements for the class C
…………..
…………..
};
Class D : public B, public C
{
Statements for the class C
…………..
}
Note:
From the above example is that the class B and C inherit the base A. Also the
class D inherits the property of class B and C.
The key idea of inheritance is that creating a new class from the existing class.
While deriving the new classes, the access specifier plays an important role over
the data members and methods of the base classes. Through the access specifier
the control of execution of function or transfer is occur in programming
statements.
255
B.Com.(CA) C++
Among all the type of access specifier the public is important and useful for
many a situation. The following are the conditions are applicable to public
access specifier is applied.
Each public member in the base class is public in the derived class.
Each protected member in the base class is protected in the derived class.
Each private member in the base class remains private in the base class.
The general format of the public derivation is
Class base-class-name
{
Statements
};
Class derived-class-name : public base-class-name
{
Statements
}
256
B.Com.(CA) C++
Example:
Class A
{
Private :
int P;
protected :
int Q;
public :
float R;
void get( )
{
Statements to the member function get( )
}
};
Class B : public A
{
Here the class B inherits the class A
with Public access specifier.
Private :
int G;
Statements
}
From the above example is that the class B is derived class from the base class A
and the access specifier is public. The data members and member function of
the derived class B is as follows as.
int P;
int Q;
float R;
void get( );
int G;
The following table shows the access specifier of the data member of the base
class in the derived class.
257
B.Com.(CA) C++
The next access specifier is called private. From the name it is that private
access specifier is that local the class. It is not accessed by the external or global
classes.
Each public member in the base class is private in the derived class.
Each protected member in the base class is private in the derived class.
Each private member in the base class remains private in the base class and
hence it is visible only in the base class.
The general format of the public derivation is
Class base-class-name
{
Statements
};
Class derived-class-name : private base-class-name
{
Statements
}
Example:
Class A
{
Private :
int P;
protected :
int Q;
public:
int R;
};
258
B.Com.(CA) C++
Class B : private A
Private access specifier is used for base
{ Class A
private T;
}
From the above example is that the class B is a derived class from the base class
A. The data members of the derived class B is as follows.
int P;
int Q;
int R;
int T;
Note:
The above mentioned access specifier is private for derived class B. So the
derived class has no rights to access the data members of the base class A,
which is declared as private access specifier. But the other type of declaration
data members and member function can be access by the object of derived class.
Among the access specifier, the protected is an intermediate one between the
public and private. The protected access specifier is applicable in some complex
situation and it accessed only for that class have a rights to inherit another
class. The protected type have different features, compared to other type exist in
c++ programming.
The protected have some similar property like public access specifier, but it not
satisfies the whole as public. It also have some advantage over the private.
Each public member in the base class is protected in the derived class.
Each protected member in the base class is protected in the derived class.
Each private member in the base class remains private in the base class and
hence it is visible only in the base class.
259
B.Com.(CA) C++
260
B.Com.(CA) C++
The following table displays the access specifier of the data member of the base
class in the derived class.
• Each public member in the base class is protected in the derived class.
• Each protected member in the base class is protected in the derived class.
• Each private member in the base class remains private in the base class
and hence it is visible only in the base class.
Single Inheritance: Where a class inherits from a single base class, it is known
as single inheritance.
Multi level Inheritance: When the inheritance is such that the class. A serves
as a base class for a derived class B which is turn serves as a base class for the
derived class C. This type of inheritance is called 'Multilevel Inheritance.'
Multiple Inheritance: A class inherit the attributes of two or more classes. This
mechanism is known as Multiple Inheritance.'
Hybrid Inheritance: The combination of one or more types of the inheritance.
18.10 KEYWORDS
Base class: A class from which another class inherits. (Also called super class)
Containership: The relationship of two classes such that the objects of a class
are enclosed within the other class.
Derived class: A class inheriting properties from another class. (also called sub class)
Inheritance: Capability of one class to inherit properties from another class.
261
B.Com.(CA) C++
262
B.Com.(CA) C++
LESSON-19
POLYMORPHISM
CONTENTS
19.0 Aims and Objectives
19.1 Introduction
19.2 Polymorphism
19.3 Let us sum up
19.4 Keywords
19.5 Questions for discussions
19.6 Suggested Readings
The main aim and objective is to study about the Polymorphism and its
relationship exits in the concept. Each of this plays a major role in the object
oriented programming. Familiar with the concept of polymorphism and how
invoke these in object oriented programming.
After completion of this unit, you should be able to:
• Discuss the polymorphism
19.1 INTRODUCTION
19.2 POLYMORPHISM
263
B.Com.(CA) C++
Polymorphism
Compile time
Polymorphism Run time
Polymorphism
Virtual
Function Operator Function
Overloading Overloading
Example:
The following is an example consist compile time polymorphism. The compile
time polymorphism is divided into two types is
1. Function overloading
2. Operator overloading
1. Function overloading
Class P
{
public :
int a;
public :
void get( )
264
B.Com.(CA) C++
{
cout<<”No arguments”;
}
void get( int a)
{
cout<<”One arguments “<<a;
}
};
Class Q : public P
{
public :
int b;
public :
void get2( )
{
cout<<”Derived class No arguments”;
}
void get2( int b)
{
cout<<”Derived class with One arguments “<<b;
}
};
void main( )
{
Q obj;
obj.get2( ); calling the function in derived class without
argument
obj.get2( 4); calling the function in derived class with
argument
obj.get( ); calling the function in base class with
argument
obj.get( 5); calling the function in base class with
argument
}
265
B.Com.(CA) C++
Note:
From the above example is that object of derived class object call the function
based on arguments and nil arguments. So polymorphism concept execute on
number of arguments.
2. Operator overloading
The same as function overloading the operator overloading concept is executed
buy the help of operator. The operator may be of two types are
1. Unary operator
2. Binary operator
Both Unary operator and Binary operator discuss in latter chapters.
19.4 KEYWORDS
1. What is polymorphism?
2. What is operator overloading?
3. Write about function overloading.
266
B.Com.(CA) C++
LESSON-20
VIRTUAL FUNCTIONS AND POINTER TO DERIVED CLASSES
CONTENTS
20.0 Aims and Objectives
20.1 Introduction
20.2 Virtual Functions
20.3 Pure Virtual Function
20.4 Pointer to Derived Classes.
20.5 Let us sum up
20.6 Keywords
20.7 Questions for discussions
20.8 Suggested Readings
The main aim and objective is to study about the Virtual Functions and Pointer
to derived classes and its relationship exits between each other. Each of this
plays a major role in the object oriented programming. Familiar with the concept
of virtual function and how invoke these in object oriented programming.
After completion of this unit, you should be able to:
• Discuss the Virtual Functions and Pointer to Derived Classes
• Make a Virtual Function and Pointer to Derived Classes
20.1 INTRODUCTION
The virtual function concept will plays a vital role in programming language. The
key idea is that use of virtual function is nothing but, to differentiate the
member function of same name to execute by the help of keyword is introduced
before the function name.
267
B.Com.(CA) C++
In such cases we use pointer to base class refers to all the derived objects. But
we create that a base class pointer and even when it is made to contain the
address of the derived class and it always execute the function in the base class.
So such a condition the complier simply ignores the contents of the pointer ad
choose the member function that matches the type of the pointer.
The virtual function concept will plays a vital role in programming language. The
key idea is that use of virtual function is nothing but, to differentiate the
member function of same name to execute by the help of keyword is introduced
before the function name.
The user declaring the function with same name in different classes in that
situation the concept of virtual function is used in base class. The keyword
virtual is used I the base class function.
The following is the general format for using virtual function.
Class A
{
public :
Member function
Virtual void test( )
};
The virtual keyword is used in the base class
class B
{
public :
member function
void test( )
};
Example:
Class X
{
public :
int a;
void output( )
{
cout<<”Base class”;
268
B.Com.(CA) C++
}
virtual void print( )
{
cout<<Base class executed”;
}
};
Class Y : public X
{ public :
int b;
void output( )
{
cout<<”Derived class”;
}
void print( )
{
cout<<Derived class executed”;
}
};
void main( )
{
X obj1; Object creation for base and derived classes.
Y obj2;
X *ptr; Pointer variable declaration.
Cout<<”The pointer points to base class”;
Ptr = & X;
Ptr Æ output( ); The Pointer points to the member function in
Ptr Æprint( ); base class function. It calls base functions.
Cout<<”The pointer points to derived class”;
Ptr = & Y;
Ptr Æ output( ); It calls base class function.
Ptr Æprint( ); It calls derived class function.
}
269
B.Com.(CA) C++
Note:
The above concept is that virtual function changes the flow of execution of
member function of same name exist in different level of classes in program.
Rules for Virtual function
The following are the basics rule that satisfy the complier requirements.
6. The prototypes of the base class are of virtual function and all the derived
class is also same. If two member functions with the same name have
different prototypes, in object oriented programming in c++ will consider as
overloading functions, and the virtual function concept is completely
ignored.
7. The virtual constructor is not allowed, but the one option is that the virtual
destructor is allowed in programming c++.
8. The pointers of base can able or allow to point the derived class object, and
the same time the opposite side path is not possible. i.e that the pointers of
derived class is not able to point the object of base class object.
9. The possible way of base class pointer points to derived class the
incremental or decremented to point the next object of the derived class.
The key idea is not possible to point the pointer to next object.
10. In case the virtual function is defined in base class, then no need to declare
again in the derived class.
270
B.Com.(CA) C++
The pointers concept is applied for base class and also the pointer is
applicable to derived class also.
Pointers to objects of a base class are type compatible with pointers to
objects of a derived class.
A single pointer variable can be made to point to objects belonging to
different classes.
The pointer variable or pointer declared to the base class, then the pointer
acts as a pointer to base class.
The following type of declaration is valid pointer type
Example:
X * ptr; pointer variable
X obj ; obj creation for base class X
Y obj1; obj creation for base class Y
ptr = & obj; Ptr points to object obj;
ptr = & obj2; Ptr pointe to object obj1
Example:
Class B
{ public :
int x;
void disp( )
271
B.Com.(CA) C++
{
cout <<”The value of x is”<x;
}
};
class D : public B
{ derived class
int y;
void disp( )
{
cout<<”The value of y is”<<y;
}
};
void main( )
{
B * ptr; // base class pointer
B obj; // object for base class B
ptr = & obj; // base address
ptr Æ x = 35; // access B through base pointer
cout<<”Ptr points to the base object”;
ptr Æ disp( ); // displays output / value of x
D obj1; // derived class object
ptr = & obj1
ptr Æ x = 35; // access D through base class pointer
cout<<”Ptr points to the derived class”;
ptr Æ disp( ); // output is displayed using base pointer in derived //
class
}
272
B.Com.(CA) C++
• The pointers concept is applied for base class and also the pointer is
applicable to derived class also.
20.6 KEYWORDS
273
B.Com.(CA) C++
274
B.Com.(CA) C++
UNIT – V
275
B.Com.(CA) C++
276
B.Com.(CA) C++
LESSON-21
MANAGING CONSOLE I/O OPERATIONS
CONTENTS
21.0 Aims and Objectives
21.1 Introduction
21.2 C++ Streams
21.3 C++ Stream Classes
21.4 Let us Sum up
21.5 Keywords
21.6 Questions for Discussion
21.7 Suggested Readings
In this unit we shall discuss the topics related to Managing Console I/O
operations in C++. At the conclusion of this unit you should be able to:
• Describe the features of Console operations
• Describe a C++ Streams
• Describe various C++ Stream Classes
21.1 INTRODUCTION
Each and Every program takes some data as input and it generates processed
data as output. C++ supports set of I/O functions and functioning to console
I/O Operations. These functions like classes. Derived classes and virtual
functions etc.,. Any of the functions we can apply in the C++ programs with two
reasons. I/O method in C++ supports the concepts of Object Oriented
Programming and I/O Methods in C cannot handle the user defined data types
such as class objects. Approaches in C++ are to the concept of stream and
stream class to implement its I/O operations with the console and data files
available at disks.
277
B.Com.(CA) C++
I/O system in C++ is designed to work with a wide range of devices including
disks, tape drives and terminals. The I/O system supplies an interface to the
programming that is independent of the actual device being accessed. This type
of interface is known as stream.
A stream is a sequence of bytes. It acts either as a source from which the input
data can be getting or destination to the output data can be delivered. The
source stream that provides data to the program is called Input stream and the
destination stream that received output is called output stream.
The data in the input stream can come from the input device or any storage
device. The data in the output stream can go to the Monitor or any storage
device. A stream acts as an interface between the program and the devices are
using to input / output. These devices are used in independent operations in
C++ Programs.
C++ having several pre-defined streams that are automatically opened when the
program begins its execution includes cin and cout. cin represent input stream
and cout represent output stream. The keyboard and monitor are default
options.
Program
Insertion
Into output stream
Output Device Output Stream
The C++ I/O system contains a hierarchy of classes that are used to define
various streams to deal with the console and disk files. These classes are called
stream classes. Figure 21.2 shows the hierarchy of the stream classes used for
input and output operations with the console unit. These classes are declared in
the header file called iostream. This file should be included in all the programs
that communicate with the console unit i.e Keyboard and Monitor.
278
B.Com.(CA) C++
ios
Pointer
istream steambuf ostream
Input Output
iostream
ios is the base class for the istream (i.e. input stream) and ostream (i.e. output
stream) which are, in turn, base classes for iostream (i.e input / output stream).
The class ios is declared as the virtual base class so that only one copy of its
members are inherited by the iostream.
The class ios provides the basic support for formatted and unformatted Input
operations in the programs. The class ostream though inheritance, provides the
facilities for formatted output. The class iostream provides the facilities for
handling both the input and output streams. Three classes namely
istream,_withassign, ostream_withassign and iostream_withassign add
assignment operators to these classes.
ios (General input/output stream class)
• Contains basic facilities that are provided by all other input and output
classes.
• Also contains a pointer to a buffer object (streambuf object)
• Declares constants and functions that are necessary for handling formatted
input and output operations.
istream (input stream)
• Inherits the properties of ios
• Declares input functions such as get(), getline() and read()
• Contains overload extraction operator >>
279
B.Com.(CA) C++
ostream(output stream)
• Inherits the properties of ios
• Declares output functions such as put() and write()
• Contains overload insertion operator <<
iostream(input / output stream)
• Inherits the properties of ios istream and ostream through multiple
inheritance and thus contains all the input and output functions.
streambuf
• Provides an inheritance to physical devices through buffers
• Acts as a base for filebuf class used ios files.
filebuf
• Its purpose is to set the file buffers to read and write.
• Contains Openprot constant used in the open() of file stream classes.
• Also contain close() as members
ifstream
• Provide input operations.
• Contains open() with default input mode.
• Inherits the functions get(), getline(), read(), seekg() and tellg() functions
istream
ofstream
• Provides output operations
• Contains open() with default output mode
• Inherits put(), seekp(), tellp() and write(), functions from ostream
fstream
• Provides support for simultaneous input and output operations.
• Contains open() with default input mode.
• Inherits all the functions from istream and ostream classes through
iostream
Check Your Progress
1. Write console stream classes associated with input devices?
............................................................................................................................
............................................................................................................................
2. Write console stream classes associated with I/O devices?
............................................................................................................................
............................................................................................................................
280
B.Com.(CA) C++
• The << operator is a predefined operator. This line puts the text in the file
or an output stream.
• C++ offers a host of different opening modes for the input file each offering
different types of reading control over the opened file. The file opening
modes have been implemented in C++ as enumerated type called ios.
• Binary files provide a better way of storing structures into a data file on the
disk using read() and write() functions. Classes are also created in the
memory just like structures and hence are lost at the termination of the
program that created them.
21.5 KEYWORDS
1. How is C++ streams able to control all the input and output operations?
2. Write short note on
a). ios
b). streambuf
c). iostream
281
B.Com.(CA) C++
LESSON-22
FORMATTED AND UNFORMATTED I/O OPERATIONS
CONTENTS
22.0 Aims and Objectives
22.1 Introduction
22.2 Formatted I/O operations
22.2.1 ios Format functions
22.2.2 Manipulators
22.3 Unformatted I/O operations
22.4 Let us Sum up
22.5 Keywords
22.6 Questions for Discussion
22.7 Suggested Readings
In this unit we shall discuss the topics related to Formatted I/O operations and
Unformatted I/O operations in C++. At the conclusion of this unit you should be
able to:
• Describe the features of Console operations
• Describe the Formatted I/O operations
• Describe the Unformatted I/O Operations
22.1 INTRODUCTION
C++ supports a number of features that could be used for formatting the output.
These features include ios class functions and flags, manipulators and user
defined output functions. The ios class contains a large number of member
functions that would help us to format the output in a number of ways. C++
supports that could be used for unformatted I/O operations with overloaded
Operators. This could be more useful to some of the programs in the C++.
Formatted console I/O operations helps to giving output with formatted. These
features include
• ios class functions and flags.
• Manipulators
• User defined output functions.
282
B.Com.(CA) C++
width()
To specify the required field size for displaying an output value. Width() function
do define the width of a field necessary for the output of an item. Since, it is a
member functions,
cout.width(w);
where w is the field width i.e number in columns. The output will be printed in a
field of w characters wide at the right end of the field.. Remember that the field
width should be specified for each item separately. C++ never truncates the
values and therefore.
precision()
To specify the number of digits to be displayed after the decimal point of a float
value. By default the floating numbers are printed with six digits after the
decimal point. This can be done by sing the precision() member function is
cout.precesion(d);
where d is the number of digits to the right of the decimal point for example
cout.precision(3);
cout<<3.142634<<”\n”;
output
.143 (rounded to the nearest )
Not that, unlike the function width(), precision() retains the setting in effect until
it is reset. That is why we have declared only one and it acted at all the
statements.
fill()
To specify a character that is used to fill the unused portion of a field., Printing
the values using much larger field widths than required by the values. The
unused positions of the field are filled with white spaces by default. Function
fill() is to used to fill the unused positions by any desired character.
cout.fill(c);
Where, c represents the character which is used for filling the unused positions.
cout.fill(“*”);
cout.width(8);
cout<<”12133”<<”\n”;
output
* * * 12133
283
B.Com.(CA) C++
setf()
To specify format flags that can control the form of output display like left
justification and right justification. The setf(), a member function of the ios class,
can provide results to these and many other formatting questions. The setf()
stands for set flags
cout.setf(a1, a2);
The a1 is one of the formatting flags defined in the class ios. The formatting flag
specifies the format action required for the output. Another ios constant, a2,
known as bit field specifies the group to which the formatting flag belongs. Table
22.1 shows some of the flags.
Flag Meaning
ios :: showbase Use base indicator on output
ios :: showpos Print + before positive numbers
ios :: Show trailing decimal point and zeroes
showpoint
ios :: Use uppercase letters for hex output
uppercase
ios :: skipus Skip white space on input
ios :: unitbuf Flush all streams after insertion
ios :: stdio Flush stdout and stderr after insertion
Table 22.2 : Flags that do not have bit fields
unsetf()
To clear the flags specified.
284
B.Com.(CA) C++
22.2.2 MANIPULATORS
Manipulators are special functions that can be included in the I/O statements to
alter the format parameters of a stream. To access the manipulators, the fil
iomanip should be included in the program.
The header file iomanip provides a set of functions called manipulators which
can be used to manipulate the output formats in the program. They provide the
same features of ios member functions and flags. Some of the manipulators are
more convenient to use than their counterparts in the class ios. Table 22.3
shows the manipulators and their meanings with equivalent functions in ios
member functions and flags.
Overloaded operators >> and <<, the objects cin and cout is predefined in the
iostream file for the input and output purpose of various data types. This can be
made possible by overloading the operators >> and to << to recognize al the
basic C++ types. The >> operator is overloaded in the istream class and << is
overloaded in the ostream class.
cin >> v1 >> v2>>…..>>vn;
v1, v2. …vn are valid C++ variables that have been declared already. This
statement causes the computer to stop the execution and look for input data
from the input device. The input data are separated by the white spaces and
should match the type of variable in the cin list. Spaces and newlines and tabs
will be skipped. The operator >> reads the data character by character and
assigns it to the indicated location. The reading for a variable will be terminated
at the encounter of ta white space or a character that does not match the
destination type.
int cs;
cin>> cs;
285
B.Com.(CA) C++
286
B.Com.(CA) C++
• C++ offers a host of different opening modes for the input file each offering
different types of reading control over the opened file. The file opening
modes have been implemented in C++ as enumerated type called ios.
• During a program execution structures are not created on a disk. Rather
they are created in the memory. The structures stored in the memory are
lost when the program terminates.
• Manipulators are special functions that can be included in the I/O
statements to alter the format parameters of a stream. To access the
manipulators, the fil iomanip should be included in the program.
22.5 KEYWORDS
1. How is C++ streams able to control all the input and output operations with
out format?
2. Write short note on
a). ios format functions
b). Manipulators
287
B.Com.(CA) C++
LESSON-23
FILE OPERATIONS IN C++
CONTENTS
23.0 Aims and Objectives
23.1 Introduction
23.2 Data File Operations
23.3 Opening a File
23.4 Closing an Opened File
23.5 Stream State Member Functions
23.6 Reading/Writing a Character from/into a File
23.7 Structures and File Operations
23.8 Classes and File Operations
23.9 Let us Sum up
23.10 Keywords
23.11 Questions for Discussion
23.12 Suggested Readings
In this unit we shall discuss the topics related to data file operations in C++. At
the conclusion of this unit you should be able to:
• Describe the features of OOPs in File operations
• Describe a Data file operations
• Describe various techniques using Files in C++
23.1 INTRODUCTION
Programs often input data from reading from a data file and output the result
into another (or same) data file. This unit will focus on issues related to
accessing data from a data file through a C++ program.
Programs would not be very useful if they cannot input and/or output data
from/to users. Some programs that require little or no input for their execution
are designed to be interactive through user console - keyboard for input and
288
B.Com.(CA) C++
monitor for output. However, when data volume is large it is generally not
convenient to enter the data through console. In such cases data can be stored
in a file and then the program can read the data from the data file rather than
from the console.
The data file itself can exist in many forms. It may contain textual data in ASCII
format or binary data. The data may be organized in fixed size record or may be
in free form text. The various operations possible on a data file using C++
programs are:
Reading data stored in the data file into various variables and objects in the
program
C++ treats each source of input and output uniformly. The abstraction of a data
source and data sink is what is termed as stream. A stream is a data abstraction
for input/output of data to and fro the program (Figures 21.1 to 21.5).
289
B.Com.(CA) C++
C++ library provides prefabricated classes for data streaming activities. In C++,
the file stream classes are designed with the idea that a file should simply be
viewed as a stream or array or sequence of bytes. Often the array representing a
data file is indexed from 0 to len-1, where len is the total number of bytes in the
entire file.
290
B.Com.(CA) C++
When you run this program the text This text will be saved in the file named
sdeub.dat in D:\ will be saved in a file named sdubu.dat in the root directory of
the D: drive. Let us run through each line of this program.
#include <fstream.h>
C++ file stream classes and functions have been defined in this file. Therefore,
you must include this header file in the beginning of your C++ program so that
these classes may be accessed.
ofstream filename ("d:\sdebu.dat");
This statement creates an object of class ofstream (acronym for output file
stream) named filename. This object acts as the output stream to write data in
the specified file. sdebu.dat is the name of the data file in which the program will
write its output. If this file does not exists in the specified directory, it is created
there.
Note that ofstream is a class. So, ofstream filename("d:\sdebu.dat"); creates an
object from this class. Here the file name d:\sdubu.dat is being passed to the
constructor of this class. In short we create an object from class ofstream, and
we pass the name of the file we want to create, as an argument to the class'
constructor. There are other things, too, that can be passed to the constructor.
More about this will be discussed later.
filename << "This text will be saved in the file named sdebu.dat in D:\";
The << operator is a predefined operator. This line puts the text in the file. As
mentioned before, filename is a handle to the opened file stream. So, we write
the handle name, << and after it we write the text in inverted commas. If we
want to pass variables instead of text in inverted commas, just pass it as a
regular use of the cout << as,
filename << variablename;
filename close();
Having finished with writing into the file the stream must be closed. Filename is
an object of class ofstream, and this class has a function close() that closes the
stream. Just write the name of the stream object, dot and close(), in order to
close the file stream. Note that once you close the file, you can't access it
anymore, until you reopen it. Before we take up the subject any further let us
quickly go through a program that reads from a data file and presents the same
on the monitor. Here is the program listing.
#include <fstream.h>
void main() //the program starts here
{
ifstream filename("d:\sdebu.dat");
char ch;
while(!filename.eof())
291
B.Com.(CA) C++
{
filename.get(ch);
cout << ch;
}
filename.close();
}
Let us run through this program line by line quickly to catch some salient
features.
ifstream filename("d:\sdebu.dat")
Similar to ofstream, ifstream is the input stream for a file. The term input and
output have been used with respect to the program. What goes to the program
from outside is the input while processed data coming out of the program is the
output. We here create an input file stream by the name - filename - to handle
the input file stream. The parameter passed to the constructor is the file we wish
to read into the program.
char ch;
This statement declares a variable of type char to hold one character at a time
while Data File Operations reading from the file. In this program we intend to
read one character at a time.
while(!filename.eof())
The class ifstream has a member function eof() that returns a nonzero value if
the end of the file has been reached. This value indicates that there are no more
characters in the file to be read further. This function is therefore used in the
while loop for stopping condition. The file is read a character at a time till the
last character has been successfully
read into the program when the while loop terminates.
filename.get(ch);
Another member function of the class ifstream is get() which returns the next
character to be read from the stream followed by moving the character pointer
to the next character in the stream.
cout << ch;
The character read in the variable ch is streamed to the standard output device
designated by cout (for console output, i.e., monitor) in this statement.
filename.close();
Since we reach at this statement when all the characters have been read and
processed in the while loop, we are done with the file and hence it is duly closed.
292
B.Com.(CA) C++
The example programs listed above are indeed very simple. A data file can be
opened in a program in many ways. These methods are described below.
ifstream filename("filename <with path>");
Or
ofstream filename("filename <with path>");
This is the form of opening an input file stream and attaching the file "filename
with path" in one single step. This statement accomplishes a number of actions
in one go:
• Creates an input or output file stream
• Looks for the specified file in the file system
• Attaches the file to the stream if the specified file is found otherwise returns
a NULL value
• In case the file has been successfully attached to the stream the pointer is
placed at the first position
The file stream created is accessible using the object's name. The specified file is
searched in the specified directory if a path is included otherwise the file is
searched only in the current directory. If the file is not found it is created in case
it is being opened for output. While opening a file for output if the specified file is
found then it is truncated before opening thereby loosing all there was in the file
before. Care should be taken to ensure that the program does not overwrite a file
unintentionally. In any case if the file is not found then a NULL value is returned
which we can check to ensure that we are not reading a file which was not
found. This will cause an error in the program if we attempt to read a file which
was not found.
ifstream filename;
filename.open("file name <with path>");
In this approach the input stream - filename - is created but no specific file is
attached to the stream just created. Once the stream has been created a file can
be attached to the stream using open() member function of the class ifstream or
ofstream as is exemplified by the following program snippet which defines a
function to read an input file.
#include <fstream.h>
void read(ifstream &ifstr) // file streams can be passed to functions
{
char ch;
while(!ifstr.eof())
{
293
B.Com.(CA) C++
ifstr.get(ch);
cout << ch;
}
cout << endl << "--------" << endl;
}
void main()
{
ifstream filename("data1.dat");
read(filename);
filename.close();
filename.open("data2.dat");
read(filename);
filename.close();
}
Note how the same input file stream can be attached to different files at different
times.
ifstream filename(char *fname, int open_mode);
In this form the ifstream constructor takes two parameters - a filename and
another the mode in which the input file would be read. C++ offers a host of
different opening modes for the input file each offering different types of reading
control over the opened file. The file opening modes have been implemented in
C++ as enumerated type called ios. The various file opening modes are listed
below.
294
B.Com.(CA) C++
Note that all these values are int constants from an enumerated type ios. The
following program demonstrates the usages of a file opening mode.
#include <fstream.h>
void main()
{
ofstream myfile("data1.dat", ios::ate);
myfile << "Save this text to the file";
myfile.close();
}
This program will write Save this text to the file at the end of the file data1.dat
without removing the previous content of the file. A file can also be opened in
mixed mode using OR (|) operator to combine the modes.
For example,
ios::ate | ios::binary
opens the file in binary mode for output at the current pointer position without
removing the previous contents of the file. Another example of mixed mode is
given below.
fstream myfile("data.dat",ios::in | ios::out);
Input file stream (ifstream) allows only reading from the file and output file
stream (ofstream) only for writing into the file. If you wish to open a file both for
writing and reading at the same time you should use file stream (fstream) with
specific opening mode as the following program demonstrates.
#include <fstream.h>
void main()
{
fstream myfile ("data.dat",ios::in | ios::out);
myfile << "Write this text"; //Writing into the file
static char TextRead[50]; //Create an array to hold what
is read from the file
myfile.seekg(ios::beg); //Get back to the beginning of the file
explained later
myfile >> TextRead;
cout << TeaxtRaed << endl;
myfile.close();
}
295
B.Com.(CA) C++
myfile.seekg(-4, ios::end) //Take the pointer 4 characters before the end of file
Most of the time it is necessary to check whether a specified file exists or not
while opening it. Opening of file may also fail due to other reasons. Remember
that if the file opening fails the open() function return a non-zero value. By
checking the return type of the function one can ensure whether the file was
opened successfully or not as demonstrated in the following program snippet.
fstream myfile("data.dat");
if (!myfile)
{
cout << "Error : File could not be opened\n";
exit(1); }
The ofstream class also provides a fail() function which return true if the opening
of file operation failed as shown in the following code snippet
ofstream myfile("data.dat", ios::nocreate);
if(myfile.fail())
{
cout << "Error : File could not be opened\n";
exit(1); }
binary files are unformatted and uninterpreted file of binary digits. It simply
contains binary numbers whose meaning is provided by the program that
manipulates the file contents. The functions that give you the possibility to
write/read unformatted files are get() and put(). To read a byte, you can use get()
296
B.Com.(CA) C++
and to write a byte, use put(). Both get() and put() functions take one parameter
- a char variable or character.
If you want to read/write whole blocks of data, then you can use the read() and
write() functions. Their prototypes are:
istream &read(char *buf, streamsize num);
ostream &write(const char *buf, streamsize num);
For the read() function, buf should be an array of chars, where the read block of
data will be put. For the write() function, buf is an array of chars, where is the
data you want to save in the file. For the both functions, num is a number, that
defines the amount of data (in symbols) to be read/written.
Another function that provides the number of symbols read so far - gcount(). It
simply function returns the number of read symbols for the last unformatted
input operation. You can specify that the file is going to be operated on in binary
mode in the open() function. The required mode is ios::binary.
Let us write a program that uses get() and put() functions for binary files. Data
File Operations
#include <fstream.h>
void main()
{
fstream myfile("data.dat",ios::out | ios::in | ios::binary); //open file in
binary mode
char ch;
ch='A';
myfile.put(ch); //put the content of ch to the file
myfile.seekg(ios::beg); //go to the beginning of the file
myfile.get(ch); //read one character
cout << ch << endl; //display it on console
myfile.close();
}
Check Your Progress
1. A file in open state file has two pointers associated with it. What are they?
............................................................................................................................
............................................................................................................................
2. Please quote two methods of opening a data file in a program.
…………...............................................................................................................
............................................................................................................................
297
B.Com.(CA) C++
Closing an opened data file is the simplest of all the data file operations. All you
have to do is to call the member function close() on the file stream hooked to the
opened file. Once the file is closed it cannot be read/written unless reopened.
The syntax for the same action is,
File_stream_name.close();
Many things can go wrong while operating on a data file through a program. The
file your program is attempting to open may not exist; the file may be locked by
some other program for some operation; for instance.
Fortunately, the I/O system in C++ provides information about the result of
every I/O operation performed with files. For this purpose C++ provides an
object of enumerated data class called ios::io_state. The object ios::io_state acts
as flag to indicate the state of result in the previous operation. It can take the
following values:
goodbit: This value indicates that the previous operation was successful without
any error.
eofbit: This value of ios::io_state indicates that end of file has been reached in
the previous operation.
failbit: This value of ios::io_state indicates that the previous operation resulted
in an non-fatal error meaning that the program can still work but the result may
not be as desired.
Badbit: This value of ios::io_state indicates that the previous operation resulted
in a fatal error and further operations are not possible.
Apart from these ios::io_state values there are corresponding functions defined
in the file stream object which can be conveniently called to check the status of
the file operations.
• rdstate(): This function returns the current status of the error-flags. For
example, the rdstate() function will return badbit if the last file operation
encountered a fatal error.
298
B.Com.(CA) C++
• clear(): This function sets the desired status bit. It takes a flag as
parameter and set that flag so that the program may behave according to
this state. It is frequently used in cases where the file operation failed and
yet the program must proceed. Data File Operations This can be done by
clearing the status with passing goodbit parameter to clear() function.
The following program snippet demonstrates the use of status check. The file
stream name has been assumed to be myfile.
if(myfile.rdstate() == ios::eofbit)
cout << "End of file has been reached!\n";
if(myfile.rdstate() == ios::badbit)
cout << "Encountered a fatal I/O error!\n";
if(myfile.rdstate() == ios::failbit)
cout << "Encountered a non-fatal I/O error!\n";
if(myfile.rdstate() == ios::goodbit)
cout << "Success without errors!\n";
Here is a complete program to show practical usages of these state functions.
#include <fstream.h>
void main()
{
ofstream myfile("data.dat"); //to create data.dat file
myfile.close();
ofstream checkState("data.dat",ios::noreplace);
//this statement will result into an I/O error because the file data.dat already
exists and the statement is trying to //create it without replacement. This will
set failbit
if(checkState.rdstate() == ios::failbit)
cout << "Error : File already exists!\n";
299
B.Com.(CA) C++
Reading and writing a character in a data file has been dealt with in the previous
sections
in detail. The general procedure of reading a file one character at a time is listed
below:
• Create an input file stream from <fstream.h> header file:
ifstream name_of_input_stream;
• Open the data file by passing the file name (optionally full name) to this
input stream:
name_of_input_stream.open("data.dat");
• Both the above statements can be combined in the following:
ifstream name_of_input_stream("data.dat");
• Set up a character type variable to hold the read character.
char ch;
• Read a character from the opened file using get() function:
name_of_input_stream.get(ch);
This way you can read the entire file in a loop stopping condition of the loop
being the end of file:
while(!filename.eof())
{
name_of_input_stream.get(ch);
//process the read character
}
When finished close the file using close() function:
name_of_input_stream.close();
300
B.Com.(CA) C++
The if stream class is defined in fstream.h header file. Therefore you must
include this file in your program. The complete program is listed below.
//reading a file one character at a time
#include <fstream.h>
void main() //the program starts here
{
ifstream filename("d:\sdebu.dat");
char ch;
while(!filename.eof())
{
filename.get(ch);
cout << ch;
}
filename.close();
}
The general procedure of writing one character at atime in a file is listed below:
• Create an output file stream from <fstream.h> header file:
ofstream name_of_output_stream;
• Open the data file by passing the file name (optionally full name) to this
output stream:
name_of_output_stream.open("data.dat");
• Both the above statements can be combined in the following:
ofstream name_of_output_stream("data.dat");
• Write a character in the opened file using << operator:
name_of_output_stream << 'A';
• When finished close the file using close() function: Data File Operations
name_of_output_stream.close();
The ofstream class is defined in fstream.h header file. Therefore you must
include this file in your program. The complete program is listed below.
//Writing a character in a data file
#include <fstream.h>
int main()
{
ofstream filename("data.dat");
filename << 'A';
filename.close();
return 0; }
301
B.Com.(CA) C++
302
B.Com.(CA) C++
peek()
This function returns the ASCII code of the current character from an input file
stream very much like get() function, however, without moving the pointer to the
next character. Therefore, any number of successive call to peek() function will
return the ASCII code of same character each time.
putback()
This function returns the last read character, and moves the pointer back. In
other words, if you use get() to read a char and move the pointer to next
character, then use putback(), it will show you the same character, but it will set
the pointer to previous character, so the next time you call get() again,
flush()
I/O streams are created and maintained in the RAM. Therefore, when dealing
with the output file stream, the data is not saved in the file as the program
enters them. A buffer in the memory holds the data until the time you close the
file or the buffer is full. When you close the file the data is actually saved in the
designated file on the disk. Once the data has been written to the disk the buffer
becomes empty again.
In case you want to force the data be saved even though the buffer is not full
without closing the file you can use the flush() function. A call to flush() function
forces the data
held in the buffer to be saved in the file on the disk and get the buffer empty.
During a program execution structures are not created on a disk. Rather they
are created in the memory. The structures stored in the memory are lost when
the program terminates. Very often you would like to save the structures in a
data file for later use. This can be done in the following manner.
struct abc
{
int num;
char ch;
} abcobj;
abcobj.num = 100;
abcobj.ch = 'W';
ofstream myfile("data.dat");
myfile << abcobj.num;
myfile << abcobj.ch;
myfile.close();
303
B.Com.(CA) C++
The problem with the above approach in storing structures in a data file is that
if the structure has many fields as many myfile<< statements are required to
accomplish the task. Couldn't there be a more efficient way of doing it?
Binary files provide a better way of storing structures into a data file on the disk
using read() and write functions. The following code snippet demonstrates just
the same.
struct abc
{
int num;
char ch;
} abcobj;
abcobj.num = 100;
abcobj.ch = 'W';
ofstream myfile("data.dat");
myfile.write((char *) (&abcobj), sizeof(abcobj));
myfile.close();
Classes are also created in the memory just like structures and hence are lost at
the termination of the program that created them. In order to store a class' data
in a data file the same approach is applied to classes as shown in the following
code snippet.
class MyAcc
{
public:
MyAcc(int accNoV, string lastNameV, string firstNameV, double balV)
{
setAccNo(accNoV);
setLastName(lastNameV);
setFirstName(firstNameV);
setBalance(balV);
}
int getAccNo() const
{
return accNo;
304
B.Com.(CA) C++
}
void setAccNo(int accNoV)
{
accNo = accNoV;
}
string getLastName() const
{
return lastName;
}
void setLastName(string lastNameS)
{
const char *firstNameV = lastNameS.data();
strcpy(lastName, lastNameV,10);
lastName[10] = '\0';
}
string getFirstName() const
{
return firstName;
}
void setFirstName(string firstNameS)
{
const char *firstNameV = firstNameS.data();
strncpy(firstName, firstNameV,10);
firstName[10] = '\0';
}
double getBalance() const
{
return balance;
}
void setBalance(double balanceV)
{
balance = balanceV;
}
305
B.Com.(CA) C++
private:
int accNo;
char lastName[20];
char firstName[20];
double balance;
};
int main()
{
fstream putCredit( "data.dat", ios::in | ios::out | ios::binary);
MyAcc one(100,"Mehta","Vibhor",10000.0);
// seek position in file of user-specified record
putCredit.seekp((one.getAccNo() - 1 ) * sizeof(MyAcc));
// write user-specified information in file
putCredit.write(reinterpret_cast< const char * >( &one ),sizeof(MyAcc));
putCredit.close();
return 0;
}
Classes are also created in the memory just like structures and hence are lost at
when you run this program the class data members will be stored in a disk file
named data.dat. In a similar manner you can read data from a disk file into the
class data members.
• C++ treats each source of input and output uniformly. The abstraction of a
data source and data sink is what is termed as stream. A stream is a data
abstraction for input/output of data to and fro the program.
• The << operator is a predefined operator. This line puts the text in the file
or an output stream.
306
B.Com.(CA) C++
• C++ offers a host of different opening modes for the input file each offering
different types of reading control over the opened file. The file opening
modes have been implemented in C++ as enumerated type called ios.
• Binary files provide a better way of storing structures into a data file on the
disk using read() and write() functions. Classes are also created in the
memory just like structures and hence are lost at the termination of the
program that created them.
23.10 KEYWORDS
Read pointer: This pointer always points to the next character in the file which
will be read if a read command is issued next. After execution of each read
command the read pointer moves to point to the next character in the file being
read.
Write pointer: The write pointer indicates the position in the opened file where
next character being written will go. After execution of each write command the
write pointer moves to the next location in the file being written.
File opening mode: An enumerated data type that determines what operations
can be applied on an opened file.
Goodbit: A file operation status flag that indicates that the previous operation
was successful without any error.
Eofbit: A file operation status flag that indicates that end of file has been
reached in the previous operation.
Failbit: A file operation status flag that indicates that the previous operation
resulted in an non-fatal error meaning that the program can still work but the
result may not be as desired.
Badbit: A file operation status flag that indicates that the previous operation
resulted in a fatal error and further operations are not possible.
307
B.Com.(CA) C++
1. How is C++ able to treat all the input and output operation uniformly?
2. Develop a simple C++ class that provides rudimentary functionalities of a
Database management system including:
a. Creating a table
b. Record insertion
c. Record updation
d. Record deletion
e. Report generation
3. Consider a data file ‘data.dat’ containing some text. Write a C++ program
to:
a. Print the number of characters in the file.
b. Print the number of capital letters.
c. Print the number of lines.
d. Print the number of vowels and consonants.
e. Print the frequency of each of the letters appearing in the text.
4. Write a C++ program to copy a given data file into another data file.
308