0% found this document useful (0 votes)
878 views308 pages

C.A - C - 308

The document discusses the object-oriented programming paradigm and introduces C++. It describes how C++ supports both procedural and object-oriented programming. Some key aspects of C++ include templates, multiple inheritance, and pointers, which allow for low-level memory manipulation. The document provides an overview of including header files in C++ programs and the differences between system header files and user-created header files. It also gives a brief introduction to objects and classes as fundamental concepts in object-oriented programming.

Uploaded by

KandukuriRamesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
878 views308 pages

C.A - C - 308

The document discusses the object-oriented programming paradigm and introduces C++. It describes how C++ supports both procedural and object-oriented programming. Some key aspects of C++ include templates, multiple inheritance, and pointers, which allow for low-level memory manipulation. The document provides an overview of including header files in C++ programs and the differences between system header files and user-created header files. It also gives a brief introduction to objects and classes as fundamental concepts in object-oriented programming.

Uploaded by

KandukuriRamesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 308

B.Com.

(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.0 AIMS AND OBJECTIVES

The concept of object-oriented programming approach to software development


has been discussed in this chapter. A comparison between procedural-oriented
and object-oriented approaches has also been drawn. At the conclusion of this
chapter you should be able to:
• Describe Procedure-Oriented and Object Oriented programming approach
• Describe the advantage of Object Oriented paradigm
• Describe basic concepts of object oriented programming

1.1 INTRODUCTION

Programming practices have evolved considerably over the past decades. As


more and more programmers gained experience problems unknown previously,
began to surface. The programming community became evermore concerned
about the thinking that they adopt in programming and approaches they
practice in program development. Factors like productivity, reliability, cost
effectiveness, reusability etc. started to become major concern. A lot of conscious
efforts were put to understand these problems and to seek possible solutions.
This is precisely the reason why more and more programming languages have
been developed and still continue to develop. In addition to this, approaches to
program development have also been under intense research thereby evolving
different frame works. One such, and probably the most popular one is object
oriented programming approach or simply OOP.

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"

1.2 C++ AT A GLANCE

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.

1.3 OBJECT ORIENTED PARADIGM

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.

• Object oriented analysis (OOA) refers to the methods of requirements of the


software in terms of real world objects, their behaviour, and their
interaction .

• Object Oriented design (OOD) turns the software requirements into


specifications for objects and derives class hierarchies from which the
objects can be created.

• Object oriented programming (OOP) refers to the implementation of the


program using objects in an object oriented programming language such as
C++.

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

• Understanding the problem


• Drawing the specifications of requirements of the user and the software
• Identifying the objects and their attributes
• Identifying the services that each object is expected to provide establishing
inter connections between the objects in terms of services required and
services rendered.

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

1.4 LET US SUM UP

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

• Software is not manufactured. It is evolved or developed after passing


through various developmental phases including study, analysis, design,
implementation, and maintenance.

• Conventional programming using high level languages such as COBOL,


FORTRAN and C is commonly known as procedures-oriented programming.
In order to solve a problem, a hierarchical decomposition has been used to
specify the tasks to be completed.

10
B.Com.(CA) C++

• OOP is a method of designing and implementing software. Since OOP


enables you to remain close to the conceptual, higher-level model of the real
world problem, you can manage the complexity better than with
approaches that force you to map the problem to fit the features of the
language. Some essential concepts that make a programming Object
Oriented Paradigm approach object-oriented are objects, classes, Data
abstraction, Data encapsulation, Inheritance, Polymorphism, dynamic
binding and message passing. The data and the operation of a class can be
declared public, protected or private. OOP provides greater programmer
productivity, better quality of software and lesser maintenance cost.
Depending upon the features they support, they are classified as object
based programming languages and object-oriented programming
languages.

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

Check Your Progress 1

1. What do you understand by Object-Oriented Programming?

..........................................................................................................................

..........................................................................................................................

2. What are the characteristics of procedure-Oriented Programming?

..........................................................................................................................

..........................................................................................................................

1.5 KEYWORDS

OOA : Object oriented Analysis

OOD : Object oriented Design

OOP : Object Oriented Programming

Analysis: A detailed study of the various operations performed by the proposed


software.

Design: The term design describes both a final software system and a process by
which is developed.

Implementation: This phase is primarily concerned with coding the software


design in to an appropriate programming language. Testing the programs and
installing the software.

11
B.Com.(CA) C++

Maintenance: In this phase the software is continuously evaluated and modified


to suit the changes as they occur.

Object: In the object-oriented model a combination of a small amount of data


and instructions about what to do with that data when the object is selected or
activated.

Class: A class represents a set of related object.

1.6 SUGGESTED TEXT BOOKS

Herbert Schildt, The complete Reference-C++, Tata Mc Graw Hill

Robert Lafore, Object Oriented Programming in Turbo C++, Galgotia


Publications.

E. Balagurusamy, Object Oriented Programming through C++, Tata McGraw


Hill.

Jan L. Harrington, C++ and the Object-Oriented Paradigm: An IS Perspective,


Wiley

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.0 AIMS AND OBJECTIVES

The concept of Evaluation of Programming Paradigm has been discussed in this


chapter. A comparison between procedural-oriented and object-oriented
approaches has also been discussed in this chapter. At the conclusion of this
chapter you should be able to:
• Describe Evaluation of Programming Paradigm.

2.1 INTRODUCTION

OOP has been adopted by several pre-existing programming languages with


varying capabilities. Yet, there exists a minimal set of features that must be
provided by a programming language to be classified as object-oriented
programming language. 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. In this chapter you
will learn about the basic features of OOP languages, their comparison and
applicability, and above all, you will write a C++ program to set the ball rolling.

2.1 EVALUATION OF PROGRAMMING PARADIGM

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++

In the modern programming parlance, at least in most of the commercial and


business applications areas, programming has been made independent of the
target machine. This machine independent characteristic of programming has
given rise to a number of different methodologies in which programs can now be
developed. We will particularly concern ourselves with two broad programming
approaches – or paradigm as they are called in the present context.

1. Procedure-oriented paradigm

2. Object-oriented paradigm

Exactly what gave birth to object oriented approach in programming couldn’t be


stated clearly. However, it is almost certain that by the end of last decade
millions and millions lines of codes have been designed and implemented all
over the world. The colossal efforts that went into developing this large
population of programs would be rendered useless if these codes could not be
reused.

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.

Software industry faced a set of problems that are encountered in the


development of computer software other than programs not functioning
properly. Surveys conducted time to time revealed that more and more software
development projects were failing to come to successful completion. Schedule
and cost overrun were more frequent than seemed to be. This situation has been
dubbed by various industry experts as “software crisis”.

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.

2.3 LET US SUM UP

• 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++

• An object-oriented programing language must support all the essential


features of object-oriented paradigm.
• Primarily two different flavors of OOP programming language exit - Object-
based and Object-oriented.
• Due to the dual nature C++ is considered to be a multi-paradigm language.
C++ is not a pure Object-Oriented language since a purely procedural
program is possible in C++. An OOP framework encompasses all the phases
of a system development like OOA (Object Oriented Analysis), OOD (Object
Oriented Design), OOT (Object Oriented Testing) etc.
• 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.
• OOP has been adopted by several pre-existing programming languages
such as C++, Java, Eiffel, Smalltalk, Ruby, C#, Python, Perl and VB.
• Eiffel, Smalltalk, and Ruby qualify for pure Object-Oriented languages,
supporting all six essential features of OOP.
• 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++ has been employed in development of conventional commercial
systems as well as cutting edge technologies like embedded systems.
• A line in a C++ program beginning with two slash (//) is ignored by the
compiler and hence acts as a comment line.
• Like many other programming languages C++ is also a free-form language,
meaning that the statements need not necessarily be written on separate
lines.
• 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.

Check Your Progress


1. Write five concepts that make a programming approach object-oriented.
..........................................................................................................................
..........................................................................................................................
2. Write Essential features of Object oriented paradigm
..........................................................................................................................
..........................................................................................................................

15
B.Com.(CA) C++

2.4 QUESTIONS FOR DISCUSSION

1. Write a note on various problems faced by the software industry.


2. Write a note on software evolution.
3. What do you mean by object oriented programming? What are its benefits?
4. What do you mean by dynamic binding?
5. What is the difference between data abstraction and data encapsulation?

6. Fill in the blanks:


(a) ——— are the basic run-time entities in an object-oriented system.
(b) The ability of a function or operator to act in different ways on different
data types is called——.
(c) The process of linking a procedure call to the code to be executed in
response to the call is called——-
(d) A——will invoke a function in the receiving object that generates the
desired result.
(e) It is possible to have ———of an object to co-exist without any interference.

2.5 KEYWORDS

OOA : Object oriented Analysis


OOD : Object oriented Design
OOP : Object Oriented Programming

2.6 SUGGESTED TEXT BOOKS

Herbert Schildt, The complete Reference-C++, Tata Mc Graw Hill


Robert Lafore, Object Oriented Programming in Turbo C++, Galgotia
Publications.
E. Balagurusamy, Object Oriented Programming through C++, Tata McGraw
Hill.

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

3.0 AIMS AND OBJECTIVE

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++

3.2 SOFTWARE EVOLUTION

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.

Object oriented Programming is an approach to program organization and


development that attempts to eliminate some of the pitfalls of conventional
programming methods by incorporating the best of structured programming
features with several powerful new concepts. It is a new way of organizing and
developing programs and has nothing to do with any particular language,
however, not all languages are suitable to implement the OOP concepts easily.

Before different programming paradigm may be compared and contrasted it is


imperative to get acquainted with the general phases through which software
development passes. Though the details of each phases and their respective
treatment is a subject of Software Engineering, a brief description is given here
to keep the relevance of the ongoing discussion. Unlike consumer products,
software is not manufactured. In this sense, software is not a passive entity
rather it behaves organically. It undergoes a series of evolutionary stages
throughout its lifetime – starting from a problem terminating into a solution.
That is why software is said to ‘develop’ or ‘evolve’ and not manufactured. In
other words, software is born, passes through various developmental phases,
gets established, undergoes maintenance and finally grows old before being
commissioned out of service.

Software engineers have developed a number of different ‘life styles’ through


which software passes. In general these life styles are known as software
development life cycle or SDLC in short.

Following are the developmental phases of software.

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

It is a detailed study of the various operations performed by the proposed


software. A key question that is considered in this phase of development
is – What must be done to solve the problem? One aspect of analysis is defining
the boundaries or interface of the software.

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?

Design phase is itself subdivided into sub-phases discussed below.

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

• Finally, details related to justification of the system and an estimate of the


impact of the software on the user are documented and evaluated before it
is implemented.

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.

3.3 A LOOK AT PROCEDURE-ORIENTED PROGRAMMING PARADIGM

Before you get into OOP, take a look at conventional procedure-oriented


programming in a language such as C. Using the procedure-oriented approach;
you view a problem as a sequence of things to do such as reading, calculating
and printing. Conventional programming using high-level languages such as
COBOL, FORTRAN and C is commonly known as procedure-oriented
programming. You organize the related data items into C structures and write
the necessary functions (procedures) to manipulate the data and, in the process,
complete the sequence of tasks that solve your problem.

Function 1 Function 6

Function 4

Main Program Function 2 Function 7

Function 5

Function 3 Function 8

Figure 3.1: Typical Structure of Procedure-oriented Programs

Although data may be organized into structures, the primary focus is on


functions. Each C function transforms data in some way. For example, you may
have a function that calculates the average value of a set of numbers, another
that computes the square root, and one that prints a string.

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.

A typical program structure for procedural programming is shown in Figure 3.1.


The technique of hierarchical decomposition has been used to specify the tasks
to be completed in order to solve a problem.

Procedure-oriented programming basically consists of writing a list of


instructions for the computer to following and organizing these instructions into
groups known as functions. We normally use a flowchart to organize these
actions and represent the flow of control from one action to another. While we
concentrate on the development of functions, very little attention is given to the
data that are being used by various functions. What happens to the data? How
are they affected by the functions that work on them? In a multi-function
program, many important data items are placed as global so that they may be
accessed by all the functions. Each function may have its own local data.

Function 1 Global Date Items Function 3

Function 2 Function 4

Function 3

Figure 3.2 : Relationship of Data and Functions in Procedural Programming


Figure 3.2 shows the relationship of data and functions in a procedure-oriented
program. Global data are more vulnerable to an inadvertent change by a
function. In a large program it is very difficult to identify what data is used by
which function. In case we need to revise an external data structure, we should
also revise all functions that access the data. This provides an opportunity for
bugs to creep in.
Another serious drawback with the procedural approach is that it does not
model real world problems very well. This is because functions are action-
oriented and do not really correspond to the elements of the problem.
Some characteristics exhibited by procedure-oriented programming are:
• Emphasis is on doing things (algorithms)
• Large programs are divided into smaller programs known as functions
• Most of the functions share global data
• Data move openly around the system from function to function.

21
B.Com.(CA) C++

3.4 OBJECT ORIENTED PROGRAMMING PARADIGM

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.

Secondly, OOP has nothing to do with any programming language, although a


programming language that supports OOP makes it easier to implement the
object-oriented techniques. As you will see shortly, with some discipline, you can
use objects even in C programs.

3.5 LET US SUM UP

• 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++

Check Your Progress


1. Write concepts of top-down approach.
..........................................................................................................................
..........................................................................................................................
2. Write Essential features of data hiding
..........................................................................................................................
..........................................................................................................................

3.6 KEYWORDS

Analysis: A detailed study of the various operations performed by the proposed


software.
Design: The term design describes both a final software system and a process by
which is developed.
Implementation: This phase is primarily concerned with coding the software
design in to an appropriate programming language. Testing the programs and
installing the software.
Maintenance: In this phase the software is continuously evaluated and modified
to suit the changes as they occur.
Object: In the object-oriented model a combination of a small amount of data
and instructions about what to do with that data when the object is selected or
activated.
Class: A class represents a set of related object.

3.7 QUESTIONS FOR DISCUSSION

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

3.8 SUGGESTED TEXT BOOKS

Herbert Schildt, The complete Reference-C++, Tata Mc Graw Hill


Robert Lafore, Object Oriented Programming in Turbo C++, Galgotia
Publications.
E. Balagurusamy, Object Oriented Programming through C++, Tata McGraw Hill.
Jan L. Harrington, C++ and the Object-Oriented Paradigm: An IS Perspective,
Wiley

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

4.0 AIMS AND OBJECTIVES

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

It is necessary to understand some of the concepts used extensively in object


oriented programming has been discussed in this section such as Basic
concepts of OOPS with Objects, Classes, Data abstraction and encapsulation,
Inheritance, Polymorphism, Dynamic Binding, and Message Communication.

4.2 BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING


Procedural programming deals with functional parts of the problem.
Programmers identify what actions must be taken to solve the problem at hand.

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.

Object : Candidate Candidate


Data Total
Name
Dob
Marks .. Percentage
Functions
Total
Result
Percentage
Result ..

Figure 4.1 Representing an Object (Two ways)

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.

4.2.3 DATA ABSTRACTION

Abstraction refers to the act of representing essential-features without including


the background details or explanations. Abstraction is indispensable part of the
design process and is essential for problem partitioning. Partitioning essentially
is the exercise in determining the components of the system. However, these
components are not isolated from each other, they interact with each other.
Since the classes use the concept of data abstraction, they are known as
Abstract Data Types (ADT).

4.2.4 DATA ENCAPSULATION

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

Employee Customer Student


Name Name Name
Dob Dob Dob
Gender Gender Gender
Emp.Code Customer Code Institution

Manager Swathi N.R. (Object)


Name Name Swathi N.R.
Dob Dob 03/10/1977
Gender Gender Female
Emp.Code Emp. Code : F2001
Section Section : Computer

Figure 4.2 : Property Inheritance

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.

If it is desired to allow an external function to access the internal resources


(private or public) of a class the external function can be declared as friend of
that class. The details of friend functions and friend classes are given in later
units. While inheriting member functions from a base class the derived classes
may wish to implement them differently individually. In this case the base class
cannot define what such a function must do and let the subclasses specify
themselves what these functions would do in their individual cases. Such
functions are known as virtual functions. Virtual functions have been addressed
in later units in more detail.

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

The process of making an operator to exhibit different behavior at different


instance is called operator overloading. Another example of polymorphisms is
function overloading, where a single function can perform various different types
of task.

4.2.7 DYNAMIC BINDING

Binding refers to the linking of a procedure call to the code to be executed in


response to the call. Dynamic binding means that the code associated with a
given procedure call is not known until the time of call at run-time. This is
associated with polymorphism and inheritance. A function call associated with a
polymorphic reference depends on the dynamic type of that reference. For
example in the above figure, by inheritance, every object will have this
procedure. Its algorithm is, however, unique to each object so the procedure will

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.2.8 MESSAGE COMMUNICATION

Message passing is another feature of object-oriented programming. An object-


oriented program consists of a set of objects that communicate with each other.
The concept of message passing makes it easier to talk about building systems
that directly model or simulate their real-world counter-parts.

A message for an object is a request for execution of a procedure, and therefore


will invoke a function in the receiving object that generates the desired result.
Message passing involves specifying the name of the object, the name of the
function (message) and the information to be sent.

Employee Remuneration (Name)

Object Message Information


Figure : 4.4

As is evident from the ongoing discussion, object-oriented approach deals with


objects that have data as well as functions rolled in one in contrast to series of
functions and actions adopted by procedural approach.
Check Your Progress
1. Write actions of Procedural approach.
..........................................................................................................................
..........................................................................................................................
2. What is operator overloading? Define.
..........................................................................................................................
..........................................................................................................................

4.4 KEYWORDS

Data encapsulation: As described above the capability of hiding data and/or


functions from being accessed directly in the form of classes.

Inheritance: The capability of creating (and therefore reusing existing classes)


new classes from existing classes. The capability of inheriting properties from
more than one class is termed as multiple-inheritance.

Polymorphism: Allowing a single function behave differently on different


occasions depending on the type of argument(s).

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.

4.5 QUESTIONS FOR DISCUSSION

1. Write short note on


a) Garbage Collection
b) Data encapsulation
c) Message Communication

4.6 SUGGESTED TEXT BOOKS

Herbert Schildt, The complete Reference-C++, Tata Mc Graw Hill


Robert Lafore, Object Oriented Programming in Turbo C++, Galgotia
Publications.
E. Balagurusamy, Object Oriented Programming through C++, Tata McGraw
Hill.
Jan L. Harrington, C++ and the Object-Oriented Paradigm: An IS Perspective,
Wiley

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.0 AIMS AND OBJECTIVES

The popular Object oriented programming languages, merits of object oriented


programming and Applications of Object oriented programming has been
discussed in this chapter. At the conclusion of this chapter you should be able to:
• Describe to ensure the popular OOPs Languages
• Describe to ensure the merits of the OOPs
• Describe to ensure the Applications of OOPs

5.1 INTRODUCTION

A language that is specially designed to support the OOP concepts makes it


easier to implement them. Developing software that is easy to use makes it hard
to build. It is hoped that the object-oriented programming tools would help
manage this problem. 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. Real business systems are often
much more complex and contain many more objects with complicated attributes
and methods. Applications of OOP technology has gained importance in almost
all areas of computing including real time business systems.

31
B.Com.(CA) C++

5.2 POPULAR OOPS LANGUAGES

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

Object based programming is the style of programming that primarily supports


encapsulation and identity of object. The features of Object based programming is
• Data encapsulation
• Data hiding and access mechanisms
• Automatic initialization and clear up of objects
• Operator overloading

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.

Object oriented programming incorporates all of object based programming


features along with two special and additional features, namely inheritance and
dynamic binding. This denoted by the following

Object based features + inheritance + dynamic binding

The list of features required by object-based programming includes:


1. Data encapsulation: As described above the capability of hiding data
and/or functions from being accessed directly in the form of classes.
2. Inheritance: The capability of creating (and therefore reusing existing
classes) new classes from existing classes. The capability of inheriting
properties from more than one class is termed as multiple-inheritance.
3. Polymorphism: Allowing a single function behave differently on different
occasions depending on the type of argument(s).
4. Pre-defined objects: The in-built units must be all object-oriented classes
and objects.
5. Garbage collection: The capability of removing the objects no more in use
and reclaiming the space occupied by them in the memory.
6. Messaging: The capability allowing classes to pass and share messages to
which they may respond.

32
B.Com.(CA) C++

Languages that support programming with objects are said to be object-based


programming languages. These languages do not support inheritance and
dynamic binding; ADA is a typical example Object-Oriented programming that
incorporates all of objects based programming features along with two additional
features, namely, inheritance and dynamic binding. Languages that support
these features include C++, Small talk, Java among others. A brief comparative
description of some of the popular OOP languages is given in Table 4.1.

Characteristic Eiffel Smalltalk Ruby Java C# C++ Perl VB


Encapsulation Yes Yes Yes Yes Yes Yes Yes Yes
Inheritance Yes Yes Yes Yes Yes Yes Yes Yes
Polymorphism Yes Yes Yes Yes Yes Yes Yes Yes
Pre-defined Yes Yes Yes No No No No No
types all object
All operations Yes Yes Yes No No No No No
Are message
User defined Yes Yes Yes Yes Yes No No No
types all
objects
Binding(Early/ Early Late Both Both Both Both Both Early
Late)
Garbage Yes Yes Yes Yes Yes No No No
Collection
Table 4.1: Characteristics of Some OOP Languages

As is clear Eiffel, Smalltalk, and Ruby qualify for pure Object-Oriented


languages, supporting all six qualities listed above. Though Java can claim to be
a pure Object-Oriented language its basic types are not objects. Moreover, it
implements basic arithmetic as built-in operators, rather than messages to
objects.

Due to the dual nature C++ is considered to be a multi-paradigm language. C++


is not a pure Object-Oriented language since a purely procedural program is
possible in C++.

5.3 MERITS OF OOPS

Object-orientation contributes to the solution of many problems associated with


the development and quality of software products. The technology provides
greater programmer productivity, better quality of software and lesser
maintenance cost. The principle advantages are:

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.

• It is possible to have multiple instances of an object to co-exist without any


interference.

• It is possible to map objects in the problem domain to those objects in the


program.

• It is easy partition the work in a project based on objects.

• The data-centered design approach enables us to capture more details of a


model in implementable form.

• Object-oriented systems can be easily upgraded from small to large


systems.

• Message passing techniques for communication between objects makes the


interface descriptions with external systems much simpler.

• Software complexity can be easily managed.

While it is possible to incorporate all these features in an object-oriented system,


their importance depends on the type of the project and the preference of the
programmer. There are a number of issues that need to be tackled to reap some
of the benefits stated above. For instance, object libraries must be available for
reuse. The technology is still developing and current products may be
superseded quickly. Strict controls and protocols need to be developed if reuse is
not to be compromised. Developing software that is easy to sue makes it hard to
build. It is hoped that the object-oriented programming tools would help manage
this problem.

5.4 APPLICATIONS OF OOPS

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

One important aspect of OOP that is particularly beneficial is the framework,


which encompasses all the phases of a system development. Thus, OOA (Object
Oriented Analysis), OOD (Object Oriented Design), OOT (Object Oriented Testing)
etc. are far more suitable tools than their non-object oriented counterparts.

Above all, the reusability feature of the Object Oriented approach has facilitated
the rapid growth of software both in variety and scope.

5.5 LET US SUM UP

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.

Software is not manufactured. It is evolved or developed after passing through


various developmental phases including study, analysis, design,
implementation, and maintenance. Conventional programming using high level
languages such as COBOL, FORTRAN and C is commonly known as procedures-
oriented programming. In order to solve a problem, a hierarchical
decomposition has been used to specify the tasks to be completed. OOP is a
method of designing and implementing software. Since OOP enables you to
remain close to the conceptual, higher-level model of the real world problem, you
can manage the complexity better than with approaches that force you to map
the problem to fit the features of the language. Some essential concepts that
make a programming Object Oriented Paradigm approach object-oriented are
objects, classes, Data abstraction, Data encapsulation,

35
B.Com.(CA) C++

Inheritance, Polymorphism, dynamic binding and message passing. The data


and the operation of a class can be declared public, protected or private. OOP
provides greater programmer productivity, better quality of software and lesser
maintenance cost. Depending upon the features they support, they are classified
as object based programming languages and object-oriented programming
languages.

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.

Check Your Progress


1. Write software complexity.
............................................................................................................................
............................................................................................................................
2. What is meant by hyper text and hyper media.
............................................................................................................................
............................................................................................................................

5.6 KEYWORDS

Analysis: A detailed study of the various operations performed by the proposed


software.

Design: The term design describes both a final software system and a process by
which is developed.

Implementation: This phase is primarily concerned with coding the software


design into an appropriate programming language. Testing the programs and
installing the software.

Maintenance: In this phase the software is continuously evaluated and modified


to suit the changes as they occur.

Object: In the object-oriented model a combination of a small amount of data


and instructions about what to do with that data when the object is selected or
activated.

Class: A class represents a set of related object.

Data abstraction: The act of representing essential features without including


the background details or exploitations.

Data encapsulation: The wrapping up of data and functions in a single unit


(class).

36
B.Com.(CA) C++

Inheritance: The process by which objects of same class acquire the properties
of object of another class.

Polymorphism: The ability to take more than one form.

Dynamic binding: The linking of a procedure call to the code to be executed in


response to the call.

5.7 QUESTIONS FOR DISCUSSION

1. What do you mean by dynamic binding?


2. What is the difference between data abstraction and data encapsulation?
3. What meant by
1. Data abstraction
2. Inheritance
3. Polymorphism

5.8 SUGGESTED TEXT BOOKS

Herbert Schildt, The complete Reference-C++, Tata Mc Graw Hill


Robert Lafore, Object Oriented Programming in Turbo C++, Galgotia
Publications.
E. Balagurusamy, Object Oriented Programming through C++, Tata McGraw
Hill.
Jan L. Harrington, C++ and the Object-Oriented Paradigm: An IS Perspective,
Wiley

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.0 AIMS AND OBJECTIVES

This chapter discusses about object-oriented programming languages in general


and about C++ in particular. At the conclusion of this chapter you should be
able to:
• Enumerate and explain the essential features of an object-oriented
programming language
• Compare and contrast between various popular object-oriented
programming languages
• Identify situations where you may or may not apply OOP
• Write a simple working C++ program

6.1 INTRODUCTION

OOP has been adopted by several pre-existing programming languages with


varying capabilities. Yet, there exists a minimal set of features that must be
provided by a programming language to be classified as object-oriented
programming language. 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. In this chapter you
will learn about the basic features of OOP languages, their comparison and
applicability, and above all, you will write a C++ program to set the ball rolling.
During the early 1990’s the language underwent a number of improvements and
changes. C++ is a superset of C. Most of what we already know about C applies
to C++ also. Therefore, almost all C programs are also C++ Programs. However,

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.

6.2 APPLICATIONS OF C++

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.

• C++ allows us to create hierarchy related objects, we can builds special


objects oriented libraries which can be used later by many programmers
such as drivers, library functions etc.

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

• It is expected that C++ will replace C as a general purpose language and


Object oriented programming language.

6.3 STRUCTURE OF A C++ PROGRAM

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++

enclose a list of parameters within them. Right after


these parentheses we can find the body of the main
function enclosed in braces ({}). What is contained within
these braces is what the function does when it is
executed.
cout << "Bharathiar This line is a C++ statement. A statement is a simple or
University SDE!!"; compound expression that can actually produce some
effect. In fact, this statement performs the only action
that generates a visible effect in our first program. cout
represents the standard output stream in C++, and the
meaning of the entire statement is to insert a sequence
of characters (in this case the “Wow it worked!!”) into the
standard output stream (which usually is the screen).
cout is declared in the iostream.h standard file, so that's
why we needed to include that specific file. Notice that
the statement ends with a semicolon character (;). This
character is used to mark the end of the statement and
in fact it must be included at the end of all expression
statements in all C++ programs (one of the most common
syntax errors is indeed to forget to include some
semicolon after a statement).
return 0; The return statement terminates the current function (in
this case the main function) and passes a return value
(in this case an integer 0) to the calling function. A
return code of 0 for the main function is generally
interpreted as the program worked as expected without
any errors during its execution. Remember that the
return value should be of the data type specified in the
definition of the function.

Like many other programming languages C++ is also a free-form language,


meaning that the statements need not necessarily be written on separate lines.
Thus, the same program can also be written as:
// a simple program in C++
#include <iostream.h>
int main () { cout << "Bharathiar University SDE!!"; return 0; }

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++

6.4 RUNNING C++ PROGRAM

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.

6.5 LET US SUM UP

• OOP has been adopted by several pre-existing programming languages


such as C++, Java, Eiffel, Smalltalk, Ruby, C#, Python, Perl and VB.

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

• An object-oriented programming language must support all the essential


features of object-oriented paradigm.

• Primarily two different flavors of OOP programming language exit - Object-


based and Object-oriented.

• Eiffel, Smalltalk, and Ruby qualify for pure Object-Oriented languages,


supporting all six essential features of OOP.

• Due to the dual nature C++ is considered to be a multi-paradigm language.


C++ is not a pure Object-Oriented language since a purely procedural
program is possible in C++.

• An OOP framework encompasses all the phases of a system development


like OOA (Object Oriented Analysis), OOD (Object Oriented Design), OOT
(Object Oriented Testing) etc.

• 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++ has been employed in development of conventional commercial


systems as well as cutting edge technologies like embedded systems.

• A line in a C++ program beginning with two slash (//) is ignored by the
compiler and hence acts as a comment line.

• Like many other programming languages C++ is also a free-form language,


meaning that the statements need not necessarily be written on separate
lines.

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.

Check Your Progress


Fill in the blanks:
(a) Languages that support programming with objects are said to be
...................... Programming languages.
(b) Due to the dual nature, C++ is considered to be a ...................... language.
(c) ...................... programming is not the right of any particular language.

6.6 KEYWORDS

Object-oriented programming (OOP) Language: Programming language that


encapsulates a small amount of data along with instructions about how to
manipulate that data; inheritance and reusability features provide functional
benefits.

Integrated development Environment (IDE): A collection of programs with a


single interface that provides all the necessary facilities for developing a program
in for a programming language.

Compiler: A utility program that translates a source program written in a higher


level programming language into target machine language.

Linker: A utility program that establishes associations with machine specific


library codes with the machine language code of a source program to make the
whole executable program.

Debugger: A utility program used to identify and fix errors in a program.

48
B.Com.(CA) C++

6.7 QUESTIONS FOR DISCUSSION

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.

2. At which stage of program development will you normally use debugger?


Explain.

3. When object file generated by a compiler contains machine language


program why cannot it be executed without linking? Explain with
appropriate example.

4. Modify the example program to print "SDE BHARATHIAR UNIVERSITY" as


the output on the monitor.

5. If you forget to write #include<iostream.h> as the first line in your program


will it generate any error? At which stage of development will this error be
caught? How will you correct it?

6.8 SUGGESTED TEXT BOOKS

Herbert Schildt, The complete Reference-C++, Tata Mc Graw Hill


Robert Lafore, Object Oriented Programming in Turbo C++, Galgotia
Publications.
E. Balagurusamy, Object Oriented Programming through C++, Tata McGraw
Hill.
Jan L. Harrington, C++ and the Object-Oriented Paradigm: An IS Perspective,
Wiley

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++

7.0 AIMS AND OBJECTIVES

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

C++ is a language in essence. It is made up of letters, words, sentences, and


constructs very much like English language. This unit discusses these elements
of the C++ language along with the operators applicable over them. During a
program execution data must be held somewhere accessible to the program. The
type of processing on data largely depends on the type of data available.
Therefore, C++ provides a rich variety of data types which can store compatible
type of data items in them. C++ also provides a large number of operators using
which large number of expressions can be generated. This chapter deals with
data types and their usage as well as operators and expressions.

7.2 C++ CHARACTER SET

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

( ) [ ] { } ~ ! # % & * - + = | \ / ? : ; ‘ , . SPACE TAB

All these characters are available on a standard keyboard. No other characters


(not listed above) may be used to write a C++ program. Sometimes a character
may be included and excluded depending on a specific implementation of C++.
We will restrict ourselves to the ANSI C++.

51
B.Com.(CA) C++

7.3 TOKEN, IDENTIFIER AND KEYWORDS

Token is like a word composed of the legal characters of a programming


language. It is the smallest individual units in a program. C++ has the following
tokens:
• Keywords
• Identifiers
• Constants
• Strings
• Operators

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

Asm Double New Switch


Auto Else Operator Template
Break enum Private This
Case Extern protected throw
Catch Float Public Try
Char For Register typedet
class Friend Return Union
Constant Goto Short unsigned
Continue If signed virtual
Default inline Size of void
Delete Int Static Volatile
do long struct while

Identifiers refer to the names of variables, functions, arrays, classes, etc.,


created by the programmer. They are the fundamental requirement of any
language. Each language has its own rules for naming these identifiers. The
following rules are common to both C and C++:

52
B.Com.(CA) C++

• Only alphabetic characters, digits and underscores are permitted.


• The name cannot start with a digit.
• Uppercase and lowercase letters are distinct.
• A declared keyword cannot be used as a variable name.

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.

7.4 CONSTANTS AND VARIABLES

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.

From a programmer's point of view a variable is a storage location in the memory


where a value of specific data type can be stored, read from and write into. The
range of values that a variable is allowed to store and the kind of operations
applicable on them is determined by the data type of the variable and/or
constant. Thus, data type is an attribute of constants and variables.

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

Input device Output device Constant

Figure 7.1: Program - Data storage Model


In the program model described in Figure 7.1 variables have been associated
with the program with double headed arrow indicating that programs can read
data from them and also write data into them. Values stored in constants can
only be read once they are written in them.

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.

7.5 DATA TYPES

A program is designed to process data. Different types of data require different


type of manipulation. Data type of a value to be processed determines what type
of values it can take, its magnitude and the kind of operations it can be
subjected to. Data types in C++ can be classified under various categories as
shown in Figure 7.2.

Main Program

User Defined Function 2 Derived type


Structure Array
Union function
Class Pointer
Enumeration

Integral type Void Floating type

Int Char Float Double

Figure 7.2 : DATA TYPES


Both C and C++ compilers support all the built-in (also known as basic-or
fundamental) C++ Data Types data types. With the exception of void, the basic
data types may have several modifiers preceding them to serve the needs of
various situations. The modifiers signed, unsigned, long, and short may be
applied to character and integer basic data types. However, the modifier long

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.

Type Bytes Range


char 1 -128 to 127
unsigned char 1 0 to 255
signed char 2 -128 to 127
int 2 -32768 to 32767
unsigned int 2 0 to 65535
signed int 2 32768 to 32767
short int 2 -32768 to 32767
unsigned short 2 0 to 65535
int
signed short int 4 -32768 to 32767
long int 4 -2147483648 to 2147483647
signed long int 4 2147483648 to 2147483647
unsigned long 4 0 to 4294967295
int
float 4 3.AE - 38 to 3.4E + 38
double 8 1.7E - 308 to 1.7E + 308
long double 10 3.4E - 4932 to 1.1E + 4932
Table 7.2 Basic data types
While rest of the data types means what they stand for, void is the data type that
means nothing. Two normal uses of void are (1) to specify the return type of a
function when it is not returning any value, and (2) to indicate an empty
argument list to a function. See the following example:
void funct1(void);
Another interesting use of void is in the declaration of generic pointers as shown
in the following example. Pointer are dealt with in later chapters.
void *gp; //gp becomes generic pointer
Having understood various data types it is time you should learn how to create
variable and constants in a C++ program.

7.5.1 CREATING CONSTANTS

Constants can be just written by their values as in the following:


3.79 100 -2.78 1.678E-6
"India" 'A'

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

1. Using the qualifier const.

2. Defining a set of integer constants using enum keyword.

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.

7.5.2 CREATING VARIABLES

Variables are created in a C++ program by declaring them. A variable declaration


takes the following general form.

<data type> <spaces(s)> <variable_name>;

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;

Some typical variable declarations are listed in the Table 7.3.

56
B.Com.(CA) C++

C++ Variable Declaration


Variable Name Variable Type Declaration
marks int int marks;
weight float float weight;
heighT float float heighT;
letter char char letter;
color short int short int color
distance double double distance;
abc unsigned int unsigned int abc;
Table 7.3: Some Example C++ variable Declarations

Once a variable is declared it can be used to store data by assignment operator =


as shown in the following statements.

float sum ; //declare sum as float variable

sum = 0.0; //store initial value into variable sum

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

float varsum; //declare varsum as float variable

varsum = sum + 3.6; //the value stored in varsum is now 6.1

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;

7.5.3 USER-DEFINED DATA TYPES

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.

7.5.4 ENUMERATED DATA TYPE

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:

enum shape {circle, square, triangle}; C++ Data Types

enum color {red, blue, green, yellow};

enum position {off, on};

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:

shape ellipse; //ellipse is of type shape

color background; // background is of type color

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,

enum color {red, blue = 4, green = 8};

enum color {red s 5, blue, green};

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.

We can also assign values to X, Y, and Z explicitly.


enum {X = 100, Y = 50, Z = 200};
C++ also permits the creation of anonymous enums (i.e., enums without tag
names). For example,
enum {off, on};
Here, off is 0 and on is 1. These constants may be referenced in the same
manner as regular constants. Examples:
int switch_1 = off;
int switch_2 = on;
In practice, enumeration is used to define symbolic constants for a switch
statement. Switch statement is explained in later sections. At this point it is
sufficient to state that a switch statement selects one of the group of statements
to be executed from a list of groups depending on the truth value of a condition.
Example:
enum shape
{
circle,
rectangle,
triangle
);

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.

7.5.6 DERIVED DATA TYPES

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++

7.6 OPERATORS AND EXPRESSIONS

All Computer languages provides some operators to perform predefined


operations as a progress is required to perform a lot more than just simple input
and output operations. C++ is very rich in built-in operators. In fact, C++ places
more significance on operators than most other computer language do.

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.

An operator is a mechanism, denoted by a symbol that takes one or more


parameters and produces a single value. C++ includes a large number of
operators which fall into several different categories. In this section we examine
some of these categories in details. Specifically, we will see how arithmetic
operators, unary operators, relational and logical operators, assignment
operators and the conditional operator are used to form expressions.

Expressions are combination of constants, variables, and operators of


compatible types generating one single value. The data items or parameters on
which operators act upon are called operands. Some operators require two
operands, while others act upon only one operand. Most operators allow the
individual operands to be expressions. A few operators take even three operands.

The primary purpose of operators is to compute and compare complex values.


For convenience they can be classified in the following broad categories:

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

7.6.1 ARITHMETIC OPERATORS

There are five basic arithmetic operators in C++. They are:

63
B.Com.(CA) C++

Operator Symbol What it means What it does

+ Addition Takes two compatible numeric operands and


produces their sum as a result

- Subtraction Takes two compatible numeric operands


and produces the difference of the second from the first
as a result

* Multiplication Takes two compatible numeric operands


and produces their product as a result

/ Division Takes two compatible operands and produces


the quotient when the first operand is divided by the
second operand

% Modulus Takes two compatible numeric operands and


produces the remainder when the first operand is
divided by the second operand

The operands acted upon by arithmetic operators must represent numeric


values. Thus, the operands can be integer quantities, floating-point quantities or
characters (remember that character constants represent integer values, as
determined by the computer's character set.) The remainder operator (%)
requires that both operands be integers and the second operand be nonzero.
Similarly, the division operator (/) requires that the second operand be nonzero.

Division of one integer quantity by another is referred to as integer division. This


operation always results in a truncated quotient (i.e., the decimal portion of the
quotient will be dropped). On the other hand, if a division operation is carried
out with two floating-point numbers, or with one floating-point number and one
integer, the result will be a floating pointing quotient.

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

If one or both operands represent negative values, then the addition,


subtraction, multiplication and division operations will result in values whose
signs are determined by the usual rules of algebra. Integer division will result in
truncation toward zero; i.e., the resultant will always be smaller in magnitude
than the true quotient.

64
B.Com.(CA) C++

The interpretation of the remainder operation is unclear when one of the


operands is negative. Most versions of C++ assign the sign of the first operand to
the remainder.

Thus, the condition: C++ Data Types

A = ((a/b) * b) + a % b)

will always be satisfied, regardless of the signs of the values represented by a


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

1. If both operands are floating-point types whose precision's differ (e.g., a


float and a double), the lower-precision operand will be converted to the
precision of the other operand, and the result will be expressed in this
higher precision. Thus, an operation between a float and double will result
in a double; a float and a long double will result in a long double; and a
double and a long double will result in a long double. (Note: In some
versions of C++, all operands of type float are automatically converted to
double.)

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.

4. If neither operand is a floating-point type or a long int, then both operands


will be converted to int (if necessary) and the result will be int. Thus, an
operation between a short into and an int will result in an int.

7.6.2 ASSIGNMENT OPERATORS

In the C++, the = operator is called an assignment operator which is used to


assign a value or result of an expression to a variable. If we write:
a = b;

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.

Operator Symbol Action Example Result


Addition += Value of LH variable will be .a+ = 1 Is
added to the value of RH equivalent
Assignment
and assign back to the to a
variable of LH.
=a+1
Subtraction -= Value of RH variable will be .a–=2 Is
subtracted from the value equivalent
Assignment
of LH and assign back to to a
the variable of LH.
=a–2
Multiplication *= Value of LH variable will be .a * = b Is
multiplied by the value of equivalent
Assignment
RH and assign back to the to a
variable of LH.
= a*b

66
B.Com.(CA) C++

Division /= Value of LH variable will be .a/=n+1 Is


divided by the value of RH equivalent
Assignment
and assign back to the to a
variable of LH.
= a/(n+1)
Modulo %= The remainder will be .a %=b Is
stored back to LH after equivalent
Assignment
integer division is carried to a
out between the LH variable
=a%b
and the RH variable

Table 3.4: Summary of assignment operators

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.

7.6.3 ASSIGNMENT EXPRESSION

The expression that makes uses of assignment operations is called as in


assignment expression. Assignment expression assigns the value of an
expression, a constant or a variable to an identifier. Assignment expressions are
often referred to as assignment statements, since they are usually written as
complete statement. The rules for writing assignment expressions are as follows:
• Don't confuse the assignment (=) with the relational operator (==). The
assignment C++ Data Types operator is used to assign a value to an
identifier, where as the equality operator is used to determine if two
expressions have the same value. This,
a=1
and
a == 1
are two different expressions.
• The sign (=) equal to is an operator and not an equation maker, so it can
appear anywhere in place of another operator. The following are legal
assignment expressions.
a = b = c + 4;
a = 2 * (b = 10/c);

67
B.Com.(CA) C++

• C++ allows to use of multiple assignment operators in a series, for example,


a = b = c = 2;
In such situation, the assignments are carried out from right to left. There are,
however, restrictions to the level to which these assignments can be chained.
For instance, Turbo C++ allows to chain maximum 70 assignment operators in a
statement i.e.
v1 = v2 = v3 = ………………… = v70 = 10;
where v1, v2, v3 are variable of similar type and are assumed to be pre declared.
When executed the value 10 will be assign to v70 and the value of v70 will be
assign to v69 and so on. Finally the variable v1 will be assigned with the value
10 as the value assignment operation carried out from right to left.
• With the compound assignment operators, compiler automatically supplies
parentheses - explicit parenthesis around the expression which is entirely
superfluous. For example, the following statement:
a + = b + 1;
is required to
a = a + (b+1);
• f the two operands in an assignment expression are of different data types,
then the value of the expression on the right will automatically be converted
to the type of the variable on the left. We'll learn more about type
conversion later in this chapter.
• Assignment operators have a lower precedence than any of the other
operators. Therefore, various operations like unary operations, arithmetic
operations, relational operations, equality operations and logical operations
are all carried out before assignment operations.
Unary Operators
Unary operators take a single operand to carry out their operation. C++ includes
a special class of unary operators called as increment and decrement operators.
These operators are very handy to use when you want to add or subtract 1 from
a variable. The symbol for the increment operator is ++ and for decrement
operator is - -.
Increment and Decrement Operators
C++ includes a special class of unary operators called as increment and
decrement operators. These operators are very handy to use when you want to
add or subtract 1 from a variable. The symbol for the increment operator is ++
and for decrement operator is - -.
The increment operator ++, as the name itself implies causes its operand to be
increased by 1, whereas the decrement operator - - causes its operand to be
decreased by 1. For instance, the statements
++a;
- - b;

68
B.Com.(CA) C++

are the equivalent of these statements respectively:


a = a + 1;
b = b - 1;
These operators can be utilized in the different ways, depending on whether the
operator is written before or after the operand. When these operators are placed
before their operand (as in ++a or - -a), they are termed prefix operators.
Placement after the operand qualifies them as postfix operators. The positioning
of the operator does not change the effect of the operator. Instead, it defines
when this operation will be performed. Let us discuss the working of prefix and
postfix versions in details.
The prefix version works on the following principle:
"The increment and decrement operators modify their operand before it is
utilized for its intended purpose with in the program." For example, in the
statement,
b = ++a;
b is assigned the modified value of a i.e. increment by 1, not the original value of
a. In other words, the evaluation of this prefix expression will take place in the
following way.
Step 1 : Add 1 to a so that a becomes a+1.
Step 2 : Assign this new value to b.
For instance, if the initial value of a = 1, then the value of b will be 2 because the
variable a is incremented before the assignment operation has been carried out.
The postfix version works on the following principle:
"The increment and decrement operators modify their operands after it is used
for its intended purpose with in the program."
For example, in the statement,
b = a++;
b is assigned the original value of a, not the one after a is increased by 1. In
other words, the evaluation of this postfix expression will take place in the
following way.
Step 1 : Assign the current value of a to b.
Step 2 : a is increased by 1 so that a becomes a+1.
For instance, if the initial value of a=1, then the value of b will also be 1 because
the C++ Data Types variable a is incremented only after the assignment
operation has been carried out. The decrement operator (pre decrement and post
decrement) has also a similar story. The following Table 7.5 summarized these
operations with their prefix and postfix versions.

69
B.Com.(CA) C++

Version Operator Symbol Action Example Result


Prefix Increment ++ Increment the a = ++b The value o f a
operand will be equal to
by 1 before it is the
used. incremented
value of b.
Decrement -- Decreased the a=––b The value o f a
operand by 1 w ill be equal to
before it the d ecreased
value of b.
is u sed.
Postfix Increment ++ Increased the a = b+ + The value o f a
operand w ill be equal to
by 1 afte r it is the o rig inal
used. value of b .
Decrement -- Decreased the a=b–– The value o f a
operand by 1 after w ill be equalto
it the o rig inal
value of b .
is u sed.
Table 7.5: Summary of increment and decrement operators

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++

Step 3 : ++a first increments a's value i.e. a become 3 now.


Step 4 : And then uses it as 3 + 1 = 4
Step 5 : b = 4
• Avoid using multiple increment/decrement operators on the same operand
as it produces different result on different system and is purely
implementation dependent.
For example:
b = (++a) - - ;
However, this statement could have been written as:
b = a + 1;

7.6.4 RELATIONAL OPERATORS (COMPARISON OPERATORS)

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

is termed as a relation expression as it contains a relational operator < and two


operands a and b. If the comparison is true, the relational expression results
into the value and to 0, if the comparison is false. C++ offers six relational
operators in all. Table 7.6 summarizes the action of these operators.

Operator Symbol Action Example Result


Equal == Is operand 1 equal to 5 = = 6 0 (False)
operand 2
Greaterthan > Is operand 1 greater than 5 > 6 0 (False)
operand 2
Lessthan < Is operand 1 less than 5 < 6 1 (True)
operand 2
Greaterthan >= Is operand 1 greater than 5 >= 6 0 (False)
or Equal to or equal to
operand 2
Less than or <= Is operand 1 less than or 5 <= 6 1 (True)
Equal to equal to
operand 2
Not Equal != Is operand 1 not equal to 5 != 6 1 (True)
operand 2
Table 7.6: Summary of relational operators

71
B.Com.(CA) C++

Note that these relational operators compare numbers and characters. But they
don't work with strings (sequence of characters).

7.6.5 LOGICAL OPERATORS

Logical operators are used to combine or negate expressions containing


relational operators. On combining logical operator with relational operators, we
can create more powerful data testing statements. For instance, if you want a
program to perform certain steps if the variable v1 = 2, and another variable, v2
> 9. To code this types of combine expression, the logical operator AND is used
in conjunction with the relational operator i.e. (v1 = = 2 AND v2 > 9). This
expression evaluates to true if all the individual conditions evaluate to true. C++
has the following three logical operators:
&& (Two consecutive ampersand symbol.) equivalent to logical AND
|| (Two consecutive pipe symbol). equivalent to logical OR
! (Bang symbol or sign of exclamation) equivalent to logical NOT
The way these logical operators work is experienced in the following Table 7.7

Operator Symbol Action Exampl Result


e
AND && Evaluates to true (1) (1= = 1) True (1)
only if both expressions because
&&
are true; false (0)
both operands
otherwise. (2 ! = 3)
are true.
OR || Evaluates to true (1) if (1= =1) True (1),
either of the expression || because one
is true; false (0) only if operand is true.
(2= =3)
both are false.
NOT ! Evaluate false (0) if ! True (1),
expression is true; true (1) because the
(1= =2)
if expression is false. operand is false.
Table 7.7: Summary of Logical Operators

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++

7.6.6 SHIFT OPERATORS

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

Table 7.11: Summary of Bitwise Operators

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

Table 7.12: Summary of Bitwise Assignment Operators


All the bitwise operators require operands of integer type i.e., those operator
work only on integer type operands. These operators are used in setting a
particular bit or group of bits to 1 or 0 as they work on the principles of Boolean
logic. The bitwise operators are most frequently used when a C++ program
interacts directly with system's hardware. In this context, it can be very
important in programming to know about these operators as programming
languages are byte oriented whereas hardware tends to be bit oriented.

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

7.6.7 SPECIAL OPERATORS

There are special operators used in C++ language to perform some particular
type of operation. The following Table 7.13 lists these operators.

Operator Symbol Meaning


Comma , Used to link the related expressions together.
Sizeof Sizeof() Return the size of the subsequent data type or
type in byte
Addressof & Yields the address of a variable
Indirection * Contents of the storage field which a pointer is
pointing.
Member Selection . Used to select member of a structure
Membership 2 Pointer to structure member reference
Paranthesis () For grouping expressions/function call
Membership [] Array element reference
Cast (type) Type cast (conversion)
Table 7.13: Summary of Special 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++

7.6.8 THE SIZE OF OPERATOR

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:

• sizeof var (where var is a declared variable)


• sizeof (type) (where type is a C++ data type)

For example, consider the following statements:

int a ;

char b ;

a = sizeof b ;

the value of a will be 1.

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 (data type)

Up to some extents, we can think sizeof as a function call as it work in a similar


way i.e. will return a value (length of data). But it is a unary operator indeed, as
in the following format it operates on a single value.

sizeof a ;

In this format parentheses are optional, if the expression is not a C data type,
the parentheses can be discarded.

7.6.9 OPERATOR PRECEDENCE AND ASSOCIATIVITY

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++

If an addition is performed first, the value of a will be 9 i.e.


a= 1 + 2 * 3;

(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

Second, if an expression contains more than one operator of the same


importance, than in which direction these operators will be evaluated i.e. from
left to right or from right to left. Consider the following expression:

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++

Logical AND && Left to right 11


Logical OR || Left to right 12
Conditional ?: Right to left 13
Assignments = Right to left 14
* = / = %
=
+=-=
^ = & = |
=
<< = >> =
Comma , Left to right 15
Table 7.14: Associativity and Precedence of C++ Operators

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

Operator Symbol Meaning


Binary multiplications * a * b is equivalent to b * a
Binary addition + a + b is equivalent to b + a
Equals to == a = = b is equivalent to b =
=a
Not equals to != a ! = b is equivalent to b ! =
a
Bit wise AND & a & b is equivalent to b & a
Bit wise OR | a | b is equivalent to b | a
Bit wise XOR ^ a ^ b is equivalent to b ^ a
Table 7.15: Commutative Operators of C++
An operator is said to be non-commutative such as division (/) if switching any
two of its operands would change the value of the resultant expression. For
instance, the expression
a = 5/2 ;
does not equivalent to

78
B.Com.(CA) C++

a = 2/5;
Hence, would be of non-commutative.

7.6.10 TYPE CONVERSIONS

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:

• Implicit type conversion or automated type conversion

• Explicit type conversion or conversion using cast operator

For instance, consider the following expression:

x=y;

Where x is an integer type and y is a floating-point type. This expression,


however, is a valid assignment, but we should be aware that transaction will
take place. As the name implies, automatic type conversions are performed
automatically by the C++ compiler without programmer's intervention. We know
that the computer considers one operator at a time, involving two operands. If
the operands are of different type, the lower type is automatically converted to
the 'higher' type before the operation proceeds. The result is of the higher type.
For instance, an expression containing an int and a char evaluates to type int.
This process of changing the data type from a 'lower' type to a 'higher' type, is
termed as type promotion. An example of the promotion of a character value is
shown below:
char ch = 'A' ;
int num = ch ;

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++

1. If either operand is a long double, the other will be converted to long


double; result will be a long double.

2. Else, if either operand is a double, the other will be converted to double;


result will be a double.

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.

5. Then, if either operand is unsigned long, the other will be converted to


unsigned long; result will be an unsigned long.

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.

8. Else, if either operand is unsigned, the other will be converted to unsigned;


result will be unsigned.

9. Else both operands are int.

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.

For example, consider the following statements:


char ch; int i ; float fl ; double db; long double fdb;
result = (ch / i) + ( fl * db) - (fl + i) + (fdb / fl) ;

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.

In C++, convention using assignment operator is not recommended as it


truncates the fractional part or may not produce the desired results. To avoid
this, there is a special way of converting one data type to the other data type by
using the cast operator. There are situations, when one may declare some
variable as an integer but sometimes one may require the result in a floating
point number. For example:
int i1, i2 ;
float f ;
f = i1 / i2 ;

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++

The general form of a casting expressions is:


(type) expression ;
where type name in parentheses is one of the standard C data type and the
expression may be a constant, variable or an expression. Therefore, so get the
correct result the above statement could be written as follows:
f = (float) i1 / i2 ;
In this way, if one of the variable is cast to float, the previous rules tell you that
the other variable is promoted automatically to type float and the result of the
expression is also of type float. Thus, the fractional part of the answer is
preserved. Some example of casts and their actions are shown in the following
Table 7.16.

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

7.7 LET US SUM UP

• An operator is a symbol that tells C++ to perform some operation, or action,


on one or more operands.
• C++ operator can be classified into these categories: Arithmetic operators,
Relational operators, Logical operators, Assignment operators, Increment
and decrement operators, Conditional operators, Bitwise operators, Special
operators.
• An expression is a formula consisting of one or more operations.
• The expression in C++ can be of the these types: Simple Expressions,
Complex Expressions.
• In the arithmetic expressions precedence of execution follows the same rule
as in mathematics i.e. division, multiplication, addition, subtraction.
Precedence can be changed using parenthesis.
• Do not confuse the = and the = = operators.

82
B.Com.(CA) C++

• C++ includes a special class of unary operators called as increment and


decrement operators.
• The bitwise operators are most frequently used when a C++ program
interacts directly with system's hardware.
• The precedence of an operator determine 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.
• 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 process of converting one predefined type into another is called type
conversion.
• A statement is a section of code which directs the computer to carry out
some task.
• Statement may be broadly divided, into two main categories: Executable
statements, Non-executable statements.
Check Your Progress
1. What will be the value of variable c in the following sets of codes?
a = 5; a = 5; b = 6; b = 6;
c = (a + 1 > b - 1) c = a + ( 1 > b ) -1
............................................................................................................................
2. What will be the value of variable a after the following assignment?
a = 23 + (-12 * 2 + 10 - 2 - (-3) * (2 + 1) / 12) -1
............................................................................................. ..... ..... ..... ............
3. What will be the value of the following expression?
a= 0; b = 1;
c = !a && b || (!(a && b));

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++

7.9 QUESTIONS FOR DISCUSSION

1. What are the different classes of operators available in C++?


2. Define the term "Expression". Explain the various types of expression in
C++.
3. What are the various logical and relational operators supported by C++?
Explain them with proper examples.
4. What do you mean by increment and decrement operators in C++.
Demonstrate the use of prefix and postfix version of these operators with
suitable examples.
5. List down the advantages and limitations of using conditional operator in a
C++ program.
6. List down the various special operators available in C++ with their
respective usage.
7. Draw a table that will provide a complete list of operators, their precedence
level and their rules of association.
8. Write short notes on:
(a) Shorthand assignment operators
(b) Bitwise operators
(c) Operator
(d) Operands

7.10 SUGGESTED READINGS

Peter Prinz, Tony Crawford, O'Reilly C in a Nutshell.


T. D. Brown, C for Basic Programmers, Silicon Press, 1987.
R. Johnsonbaugh and M. Kalin, Applications Programming in C, MacMillian, 1990.
E. Balaguruswamy, Introduction to C, Tata McGraw Hill.

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

8.0 AIMS AND OBJECTIVES

Program execution is essentially sequential. This chapter deals with the


mechanism through which the order in which given statements must be
executed are controlled. At the conclusion of this chapter you should be able to:
• Control which statement should be executed and which not
• Choose one among many alternative statements to be executed
• Jump to new statement from the current statement
• Execute a statement specified number of times
• Execute a statement until some condition becomes true
• Control the loop execution

85
B.Com.(CA) C++

8.1 INTRODUCTION

To write a realistic program doesn’t mean that collection of the statements


arranged in a particular sequence. It requires more than that. Just take an
analogy of our real life. Life doesn’t go straight all the way as:

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

In the sequence construct, as the name implies, statements are executed


sequentially i.e. one after the other. In this, neither the statement are repeated
nor in the order of execution changed as show in Figure 8.1 .

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++

following program shows the sequential execution of statement in a C++


program.
#include<iostream.h>
void main ()
{
cout << “\n Ist statement”;
cout < “\n IInd statement”;
cout << “\n IIIrd statement”;
cout << “\n IVth statement”;
cout << “\n Last statement”;
}
Output:
First Statement
Second Statement
Third Statement
Second Last Statement
Last Statement

8.2 STATEMENTS & BRANCHING

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.

Statement may be broadly divided, into two main categories:


• Executable statements C++ Data Types
• Non-executable statements

Executable statements are those statements which causes an action to be


performed. The compiler, after compiling these statements, produces machines
code that directs machine to perform the particular task. Executable statements
can be further categories as:

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

--

Control statements are discussed in this chapter. Non-executable statements are


those statements which causes no operation or action to be performed. These
statements are ignored by the compiler as they are used to assist the compiler
by specifying, describing or classifying the elements of the program, calls as
entry points, data or program units. Non-executable statements further
categories as:
• Comment Statement
• Declaration Statement
• Pre-processor Direction

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 */

Even an executable statement will be treated as a remark or non-executable


statement if followed by the /* and terminated by */. For example,

/* cout << "non-executable statement";*/

is a non-executable statement.

Most C++ compilers do not allow comments to be located with in statements.


Usage of comments in such a manner, as illustrated below, is inadvisable in any
circumstances.

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.

Followings are the example of preprocessor directives:


• # include <iostream.h>
• # define pi 3.14

The first directive statement is a null-directive that means no action. It replaces


the line with the content of the file named "iostream.h" which is a standard
library header file in which some classes have been defined. The angle-brackets
(< and >) indicate that the file is located in the default INCLUDE directory.
However, you can also specify the complete pathname but in that case you will
have to use double quotes and not anglebrackets as shown below.
#include "C:\Tcc\include\iostream.h"
The second directive statement includes the named file in the translation unit,
replacing the directive. You can have multiple levels of includes in a program.
The lost statement i.e. # define preprocessing directive defines a macro. A
macro's effect is to replace all occurrences of an identifier is the source code with
something else.

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.

True Condition False

Statement 1 Statement 1

Statement 2 Statement 2

Statement Statement

Stop

Figure 8.2: Branching Construct


Looping
The looping constructs are an efficient method of handling a series of statements
that must be repeated a variable number of times. Sometimes the required
number of repetitions is known in advance and sometimes the statements
repeats over and over until certain specified conditions on met, as shown in the
Figure 8.3.

True Condition False

Statement 1

Statement 2

Statement

Figure 8.3: The Looping Construct

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

8.2.1 SIMPLE IF 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”.

As mentioned earlier, an if statement can control the execution of multiple


statements, called as compound statement or a block. Where a block is a group
of two or more statements enclosed in braces. So if these multiple statements
are to be executed then they must be placed with in a pair of braces, as
illustrated by the following program.
# include<iostrem.h>
void main()
{
int marks;
cout << “\n Enter your marks: “;
cin >> marks;
if (marks > 39)
{
cout << “\n Pass”;
cout << “ \n Congratulation …”;
}
if (marks <40)
{

93
B.Com.(CA) C++

cout << “\n Fail”; Control Flow


cout << “\n Sorry. Good luck next time …”;
}
cout << “\n Thank you”;
}
The output of the program (run 1):
Enter your marks : 77<ENTER>
Pass
Congratulations…
Thank you

8.2.2 IF-ELSE STATEMENT

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.

However, if you want a statement or group of statements to be executed only


when an expression evaluate to false, you can mention this in else section, as
shown below the general format of if else statement.
if (expression)
statement1;
else
statement 2;

If expression evaluates to true, statement1 is executed. If expression evaluates to


false, statement2 is executed, but never both. Both statement1 and statement2,
as mentioned earlier, may be single statement, a compound statement, or an
empty statement. Actually, the simple if statement described in previous section
is a simplification of its parent statement i.e. If else statement, where the else
section in optional. Without it, however, an if-else construct look like a simple if
construct. If-else construct is particularly useful when you have the statements
to be executed in both the cases i.e. when the expression evaluates to true or
false. For example consider the following statements:
int marks;
cout << “\n enter your marks”;
cin >> marks;
if (marks >= 40) //if construct with test condition

94
B.Com.(CA) C++

cout << “\n Pass”; //statement associated with if


else
cout << “\n Fai””; //else statement
}

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.

8.2.3 NESTED IF-ELSE STATEMENT

A simple if or an if - else construct may be placed with in another if or if-else


construct. That is simple if or if-else construct may be nested within another if
in its if’s body or in its else’s body. The executions of the inner if depends upon
its location in the outer construct and upon the value of expression of the outer
construct. For instance, consider the following:
:
if (expression 1)
{
if (expression 2)
statement 1;
else
statement 2;

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”;
}
}

Output of the program (run 1)


Enter your marks : 45<ENTER>
Well done
Note that every opening brace must have corresponding closing braces. A
mismatch of Control Flow braces may give unexpected results.
As mentioned earlier, the if constructs also makes use of logical operators for
decision making. The following program demonstrates the use of logical
operators in if construct. We will write the same program of marks and result for
the same purpose.

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.

8.2.4 ELSE-IF STATEMENT

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++

if (marks > = 75 & & marks < 80) grade = ‘M’;


if (marks > = 60 & & marks < 75) grade = ‘I’;
if (marks > = 50 & & marks < 60) grade = ‘II’;
if (marks > = 40 & & marks < 50) grade = ‘III’;
if (marks < 40) grade = ‘F’;
cout << “\n Your grade is : “ << grade;
}
Output of the program (run 1)
Enter your marks : 77<ENTER>
Your grade : M
Note that all ifs are individual statement and there is no involvement of else. So
these ifs may appear in any order without affecting the result or the algorithm in
any way.

8.2.5 GOTO STATEMENT

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 “;
}

In this program, the user is asked to enter a non-negative number. However, if a


negative number is entered, the program utilizes a goto statement to jump back
to the ComeHere label. The user is then asked again to enter a new number. In
this way, we can continually ask the user for input until he or she enters
something valid.

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.

8.2.6 SWITCH STATEMENT

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++

statement1, statement2,.. statement n may be single statement or set of


statements, or may be an empty statement.
The switch statement evaluates the expression first and then compare the return
value against the values value1, value2,.. value n, and then one of the following
happens:
• If a case is found whose value matches with the value of the expression
then the statement associated with that case is executed.
• If no match is found then the statement followed by the keyword default is
executed.
• If no match is found and there is no default label as it is an optional case,
then no action takes place and control passes to the statement next which
is a statement immediately followed the switch statements closing braces,
Consider the program listed below, which gives you an example of using the
switch statement. This program will receive a number between 1 to 5 and
will display its English translation.
#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”;
case 2 : cout<<“\n Two”;
case 3 : cout<<“\n Three”;
case 4 : cout<<“\n Four”;
case 5 : cout<<“\n Five”;
default : cout<<“\n Wrong input”;
}
cout<<“\n Thank You”;
}
The output of the program (run 1):
Enter any number between 1 and 5 : 2<ENTER>
Two
Thank You

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++

case 3 : cout<<“\n Three”;


break;
case 4 : cout<<“\n Four”;
break;
case 5 : cout<<“\n Five”;
break;
default : cout<<“\n Wrong input”; Control Flow
}
cout<<“\n Thank You”;
}
The output of the program (run 1):
Enter any number between 1 and 5 : 2<ENTER>
Two
Thank You

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.

Although “Fall Through” execution is a problem, but it can be proved useful at


times. For instance, when you want the same statement is to be executed for
more than one value of the expression. Just simply omit the break statements
and put all possible case one after the other and then specify the appropriate
statement. In this way the general syntax of switch-case may look like as:
switch (Exp)
{
:
case value3:
case value4 :
case value5:
:
}
The following program not only demonstrates the use of character value in a
switch case but also shows how the problem of “Fall through” execution could be
proved beneficial.

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++

If the conditional_expression evaluates to true, statement1 is executed else


statement2 is executed as shown below:
(x > y) ? cout<<“X=”<<x; : cout<<“Y=”<< y;
The above statement can be interpreted as, is the expression evaluates to true
i.e. the value of x is greater than y then print the value of x on the monitor
otherwise print the value of y as the expression evaluator to false i.e. the value of
x is less than y.
The conditional operator defines an expression while the if-else construct defines
a statement. For example, the following in an expression
max = (x>y) ? x : y;
where as
if (x>y)
max = x ;
else
max = y;
is a complete conditional statement (construct).
The conditional operator can only contain one expression in each of the true and
false position whereas the if-else statement can have a virtually unlimited
number of statement as long as they are enclosed in a pair of braces. Nested
conditional operator statement are becomes more complex and difficult to
understand than nested if-else statement, as demonstrated by the following
statement:
grade = (m > = 40) ? ((m> = 80) ? ‘O’ : ‘P’) : ‘F’ ;
The above statement is equivalent to the following segment:
if (x > = 40)
if (x > = 80) grade = ‘O’;
else grade = ‘P’;
else
grade = ‘F’;
Check Your Progress
1. What is switch statement? Define.
............................................................................................................................
............................................................................................................................
2. Differentiate conditional operator and if-else construct?
............................................................................................................................
............................................................................................................................

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 above mentioned components are the essential component of a statement to


be called as a loop statement. Messing any of them may change the basic
meaning of a perfect loop. The for, while and do-while statements of C++,
comprises of all these essential components, hence referred to as loop
statements. Let’s discuss them in detail.

8.3.1 FOR LOOP

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

for ( i = 10 ; i> = 1; —i)

• You can also update the counter by a value other than 1, say by 5 as given
below:

for ( i = 5; i< = 50; i = i+5)

• 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;

for ( ; i < = 10 ; ++i)

• 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++

8.3.2 WHILE LOOP

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;

Where the loop_body may contains a single statement, a compound statement or


an empty statement. The while loop iterates the loop_body as long as the
specified condition expression evaluates to true.

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++

sum = sum + num;


cout<<“\n Continue (y/n):”);
cin>>reply;
}
cout<<“\n The sum of all the numbers is = “<<sum;
}
Output:
Enter number to add : 4<ENTER>
Continue (y/n) : y<ENTER>
Enter the number to add : 8<ENTER>
Continue (y/n): y<ENTER>
Enter the number to add: 8<ENTER>
Continue (y/n) : n<ENTER>
The sum of all the numbers is = 20
Note that reply is initialized with ‘y’ to get in side the loop body, the very first
time. The next iterations of the computer body will depend upon the user’s
response. Input must be provided in a required way, otherwise unexpected
results may appear.
C++ also allowed a while loop to be written in variations. As variations in while
loop no only increases the flexibility to use it but also increase your logic sense.
The following statement of code explores some of the variations of while loop.
• The while loop doesn’t care about the initialization expression and the
updation expression as it only has to deal with conditional expression. So
the particular variables may be initialized or updated according to the
programmer choice. For example the following statements will print first ten
natural numbers in reverse order.
i=10;
while ( i>=1)
{
cout<< “%d \n” <<I;
—i;
}

• 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++

while ( cin>>ch != EOF )


cout<<ch;
This loop reads a character from the keyboard and displays it on the
monitor, as long as the character in not a EOF (i.e. ^z).
• Missing an updation expression sometimes may cause while loop to be
executed infinitely, for example
i=1;
while(i<=10)
cout<<“\n”<<i;
• The following could also be the example of infinite while loop:
i=1;
j=2;
while (i++<=j++)
——
• First ten natural numbers could also be cout on the monitor by using the
following:
i=1;
while (i<=10)
cout<<“\n “<<i++;
• An empty loop can also be configured using while statement and could
used as a time delay loop for example.
i=1;
while (i++< 10000);
• The conditional expression in while loop may contain several conditions
linked together using logical operators. For example, consider the following
while loop:
i=1;
j=10;
while (i<=j && j>=i)
cout<<“\n i= “<< i++<<” j= “<<j—;

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

8.3.3 DO-WHILE LOOP

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

i=1; is an initial expression.


i < = 10; is a conditional expression.
++i; is an update expression.

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

8.3.4 BREAK STATEMENT

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++

8.3.5 CONTINUE STATEMENT

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.

8.4 LET US SUM UP

• 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

Do-while loop: A looping statement that executes the enclosed block of


statements as long as the condition remains true. It is executed at least once.
Goto statement: A jump statement that takes the execution of statement
pointer to a location in the program specified by a label.
Nested loop: A loop containing another loop inside.
While loop: A looping statement that executes the enclosed block of statements
as long as the condition remains true. It may not execute even once if the
condition is found false in the beginning itself.

8.6 QUESTIONS FOR DISCUSSION

1. What do you mean by a ‘Loop’. Explain the concept of looping in C++.


2. What are the various loop available in C++. Explain them with the help of
suitable programs.
3. What are the various jump statements available in C++. Explain them with
the help of suitable programs.
4. Write a program to print the first 10 terms of fibonacci series then directly
print the 21st term of fibonacci series.
5. Differentiate the followings:

127
B.Com.(CA) C++

(a) for loop and while loop


(b) while loop and do-while loop
(d) break and continue
6. Write short notes on:
(a) for loop variations
(b) while loop variations
(c) do-while loop variations
(d) empty loop
6. Write a program to summarize the conversion specifiers used to input all
types of data.
7. Write a program that prints the value 100.123456 rounded to the nearest
digit, tenth, hundredth, thousandth and ten thousandth.

8.7 SUGGESTED READINGS

Peter Prinz, Tony Crawford, O’Reilly, C in a Nutshell, .


T. D. Brown, C for Basic Programmers, Silicon Press, 1987.
Herbert Schildt, The complete Reference-C++, Tata Mc Graw Hill
Robert Lafore, Object Oriented Programming in Turbo C++, Galgotia
Publications.
E. Balaghrusamy, Object Oriented Programming through C++, Tata McGraw
Hill.

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

9.0 AIMS AND OBJECTIVES

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.

9.2 FUNCTION IN C++

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. Conceptually, a function may be represented as a
process that takes some (optional) inputs, processes the inputs, however,
produces a single output value. In some cases it may not produce any value at
all (Figure 9.1).

Optional Input List Function Single or no output value

Figure 9.1: A C++ function


For example, a product function may take two integer values as input and
produce its product as shown below.

Int a, Int b Product a*b

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.

9.3 FUNCTION COMPONENTS

Recall what a function looks like.

Optional Input List Function Single or no output value

As is evident, a function has three neat components:


1. optional input list
2. function body
3. returned value

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 call is an expression that can be used as a single statement or within


other statements. When a function call is made, the program execution jumps to
the function and finishes the task assigned to the function. The program
execution resumes after the function returns. Figure given below shows the
execution of functions.

A function can be called as many as times as needed and the function can be
called in any order.

9.3.1 FUNCTION ARGUMENTS

The parameters or the variables passed in a function are called arguments. An


argument is the program data, needed by function to accomplish its task. The
arguments given while defining a function are called the dummy/formal
arguments and the variables passed in function calling are called the actual
parameters. Consider the following program that defines and uses a function
called - sum().
float sum(int a1, int a2, float a3, float a4)
{
return (a1 + a2 + a3 + a4) ;
}
int main()
{
int p, q ; float r, s, k ;
cout<<"\n enter two integers";
cin>>p>>q;
cout<<r<<" "<<s);
k = sum(p, q, r, s);
cout<<"\n the sum of four numbers is "<<k;
return(0);
}

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.

9.3.2 DEFAULT ARGUMENTS

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.

Default arguments facility allows easy development and maintenance of


programs .To establish a default value, you have to use the function prototype.
Because the compiler looks at the prototype to see how many arguments a
function uses, the function prototype also has to alert the program to the
possibility of default arguments. The method is to assign a value to the
argument in the prototype.. The following program explains the use of default
arguments:
#include <iostream.h>
void rchar (char ch = '*', int num = 10); //default arguments with values
'*' and 10
void main (void)
{
rchar ( );
rchar ('=');
rchar ('+', 30);
}
void rchar (char ch, int num)
{
for (int j = 0; j < num; j ++)
cout << ch;
cout << endl;
}

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!

The above declaration is correct because no un-defaulted arguments appear


after defaulted arguments. For this reason the following declaration is incorrect.

void abc (int a, float b = 2.5, int c, char d = 'P'); //incorrect defaulting!

9.4 LIBRARY FUNCTIONS

Broadly, functions can be classified in two categories:


• Predefined functions
• User defined functions
Predefined functions are also called standard library function. The definition of
these functions is present in header files. To use these functions, you have to
include the proper header file. One can consult the reference manual to find out
which functions are available. We've tried to mention some common header files
and their functions.

header file math.h.


Function Meaning
acos(n) Arc cosine of n
abs() Returns absolute value of an integer
cos() calculate cosines
cosh() calculates hyperbolic cosine
exp(x) Raise exponential e to the xth power
log() calculates natural log Functions

135
B.Com.(CA) C++

sin() calculates sin


sinh() calculates hyperbolic sine
tan() calculates tangent
tanh() calculates hyperbolic tangent
header file ctype.h
isalnum() checks for alphanumeric char
isalpha() checks for alphabetic char
isdigit() checks for decimal digit
islower() checks for lower case character
tolower() converts to lower case if uppercase
toupper() converts to uppercase if lowercase
header file string.h
strcat() appends one string to another
strcmp() compares two strings
strcmpi() compares two strings without regard to case
strlen() calculates length of a string
strcpy() copies one string to another
strupr() converts a string to uppercase

9.4.1 FUNCTION INVOCATION METHODS

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.

9.4.2 CALL BY VALUE

To pass arguments to a function, you list them in parenthesis following the


function name while calling. The number of arguments and the type of each

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

m n data moves from actual to


formal arguments

6 7 formal arguments

Figure 9.2: Relation between Actual and Formal Parameters


When arguments are passed call by value, a copy of the argument's value is
made and passed to the called function. Changes to the copy do not affect an
original variable's value in the caller. Call by value should be used whenever the
called function does not need to modify the value of the caller's original
variables.
// Program to swap two numbers
#include<iostream.h>
void swap(int a, int b); //prototype of swap function
void main()
{
int p, q;
cout<<"\n Enter two numbers";
cin>>p>>&q;
cout<<"\n The nos. before swapping are : "<<p<<" "<<q;

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.

9.4.3 CALL BY REFERENCE FUNCTIONS

It is another method of passing variables in a function. In this method, address


of the argument is passed to the function, instead of passing the arguments
directly. This can be done by the pointers. So lets understand little of pointers.
While declaring a variable, we write
<data type> <name-of-variable> = value;
e.g. int a = 5 ;
This statement convey the following information
1. Name of the variable
2. Number of bytes required for variable
3. Value of the variable
4. And the address i.e. memory location of the variable
a Name
5 Value
0 × 1025 Address
A pointer is a special variable, used to store the address of one variable. A
pointer can be declared as

138
B.Com.(CA) C++

< data type> *name_of_pointer_variable;


e.g. int *b; float *p;
Since pointer can store the address only which are in hexadecimal number, the
significance of int *or float *etc. is that the given pointer can store the address of
one int variable or float variable or any other given data type.
Address of any variable can be initialized to a pointer by giving '&' (ampersand)
sign as & means 'Address of '. Consider the following example.
void main()
{
int a = 5;
int *ptr;
ptr = &a;
cout<<" Address of a is "<<&a;
cout<<" \nAddress of a through pointer is "<<ptr;
cout<<" \nValue of a is "<<a;
cout<<" \nValue of a through pointer is "<<*ptr;
}

With pointers, you've to keep two notations in your mind i.e.


1. & means Address of
2. * means value of
The pointers may have any declaration like
float *p;
char *ch;
double *n;
In call by reference method, pointers are used to pass address of variable as
arguments. When the function is called, the addresses of variables are passed as
arguments instead of values. To change the value of variable in calling
environment, the effect of call by reference is used with the help of pointers.
Let us see one complete example to swap the value of variables in calling
environment.
#includes<iostream.h>
void swap(int*, int*);
int main()
{
int i, j;

139
B.Com.(CA) C++

cout<<"\n Enter the values of two variables";


cin>>i>>j;
cout<<"\n Before swapping i = "<<i<<" j = "<<j;
swap(&i, &j);
cout<<"\n After swapping i = "<<i<<" j = "<<j;
return(0);
}
int swap(int *p, int *q)
{
int temp;
temp = *p;
*p = *q;
*q = temp;
}

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.

A recursive function is a function that calls itself either directly or indirectly


through another function. We consider recursion conceptually first and then
examine several other recursive function.

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.

Factorial of a non-negative integer is the product of


n! = n * (n - 1) * (n - 2) * ------- 1

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++

Functions help programmer to write efficient programs. As a function takes in


one or more arguments and returns a single value, so it can be embedded in an
expression. There is no need to write entire code, only the name of function is
sufficient. So this feature helps a lot in writing programs.

9.5 INLINE FUNCTIONS

C++ provides facility of inline function which is designed to speed up the


program execution. This is done by the C++ compiler which incorporates it into a
program.

When any program is compiled the output of compilation is a set of machine


language Functions instructions which is in executable program. When a
program is run, this complied copy of program is put into memory. Each
instruction gets a memory address which is used to refer that instruction. These
instructions are executed as per the logic in the program.

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.

In normal function call, the control of execution is transferred to the location


where the function is loaded in memory that is the starting executable
instruction of the function. When all the instructions of the function are
executed the control returns back to main program from where left. Now the
next instruction in the main program will get executed. Jumping back and forth
keeping track of where to jump means that there is an overhead in elapsed time
to functions. When the function is declared inline the compiler replaces the
function call with the corresponding function code. As a result the program does
not have to spend time to jump to another location to execute the function and
then come back. But there is a memory overhead. If the function is called n
times in the program then it is copied n times making the program code or in
particular executable code large. If the value of n is large, there is a lot of
memory overhead.

The following program demonstrates the use of inline function to calculate


square of an input number.
#include <iostream.h>
#include <conio.h>
inline float square(float a)
{
retum (a * a);
}
void main()
{

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);"

9.6 LET US SUM UP

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

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

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

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

• A function call is an expression that can be used as a single statement or


within other statements. When a function call is made, the program
execution jumps to the function and finishes the task assigned to the
function.

• The parameters or the variables passed in a function are called arguments. An


argument is the program data, needed by function to accomplish its task.

• Every C++ program contains at least one function i.e. main().

• Predefined functions are also called standard library function. The


definition of Functions these functions is present in header files. To use
these functions, you have to include the proper header file.
Check Your Progress
Fill in the blanks:
(a) In C++, functions are used to implement the .............................. method of
programming.
(b) Predefined functions are also called standard .............................. function.
(c) A ........................... function is a function that calls itself either directly on
indirectly through another function.

9.7 KEYWORDS

Actual parameter: The formal parameters holding values when a function is


called.
Call by reference: A function call where the addresses of the variables (rather
than the value themselves) are passed to the function being called.
Formal parameter: The parameters declared within the scope of a function
having no value as yet.
Function: A named unit of statements that accepts specified number of values
and returns a single computed value to the caller.
Recursion: An act of a function calling itself repeatedly directly or indirectly
until some condition becomes false.

145
B.Com.(CA) C++

9.8 QUESTIONS FOR DISCUSSION

1. Differentiate the following:


(a) Function prototyping and function definition
(b) Function definition and function calling
(c) Global function and local function
(d) Inbuilt and User-defined function
2. Write short notes on:
(a) Function Arguments
(b) Inline function
(c) Call by value
(d) Call by reference
3. Write a C++ function for each of the following:
(a) power(int a, int b, int c) returning (a to the power b) to the power c.
(b) Write a C++ function to generate sum of cubes of first N natural numbers,
where N is the parameter to be passed.

9.9 SUGGESTED READINGS

Peter Prinz, Tony Crawford, O'Reilly, C in a Nutshell.


T. D. Brown, C for Basic Programmers, Silicon Press, 1987.

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

10.0 AIMS AND OBJECTIVES

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

Object-Oriented Programs (OOPs) attempt to emulate real world in software


system. The real world consists of objects, categorized in classes. For example,
you're using an object categorized as a book to learn about programming. OOP
describes a software system in terms of real world objects.

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.

An object, on the other hand, is an instance of a class. It has physical existence


and hence occupies memory. You can create as many objects from a class once
you have defined a 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.

To understand the difference clearly, consider a class of vehicle and a few


objects of this type as depicted below:

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.

Consider a 14 inch television - an object. It has certain attributes - a 14 inch


screen and controls for adjusting volume, brightness and color. It also has
certain behaviors – it shows moving pictures and allows a viewer to change
channels. Finally, it has an identity - a serial number that distinguishes it from
other televisions.

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.

2. Information encapsulation (Hiding): Objects provide the benefit of


information hiding. Electrical wiring in a TV should not be tampered with
and should be hidden from the user. OOP allows you to encapsulate data
that you do not want users of the object to access. Typically attributes of a
class are encapsulated.

3. Abstraction: It allows us to focus only on those parts of an object that


concern us. To continue the example given above, a person operating the
TV does not need to know the intricacies of how it works. The person just
needs to know how to switch it on, change channels and adjust the volume.
All the details that are unnecessary to the user are encapsulated, leaving
only a simple interface to interact with. Providing only the users what they
need to know is an abstraction. Abstraction lets us ignore the irrelevant
details and concentrate on the essentials.

149
B.Com.(CA) C++

4. Inheritance: A TV has certain common attributes and functionality. For


example, you expect a TV to have a screen. Companies add more features
to the basic functionality of TVs to create their own brand or class of TVs.
This means they've added new functionality to the existing class without
creating a new one from the scratch. For example, a color TV has been
derived from TV class. The child class, color TV, inherits the properties of
the parent class, TV. Similarly, programmers can reuse code rather than
rewrite it. You can use the existing features of the class and add more
functionality to it. This is known as inheritance. Using inheritance you can
extend the scope of classes and at the same time, reduce the amount of
code to be written. Through inheritance you can provide the reusability of
code.

10.2 CLASS SPECIFICATION

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.

Class syntax Class example


class < class_name> class abc
{ {
private : private :
data members; int a;
member functions; void addit();
public : public:
data members; int b;
member functions; void printit();
}; };
Once the class in defined, an instance of this class (object) may be created as
follows:
class abc pqr;
Or,
class pqr = abc;

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.

10.3 ACCESSING CLASS MEMBERS

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++

one.EmpNum = 100; //incorrect! Trying to access private member of


//employee class /from outside the class
one.batchNum = 200; //Correct! Public member accessible from
//outside the class
}

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;
};
};

10.4 DEFINING MEMBER FUNCTIONS

As explained in the previous section member functions can be either private or


public or friend. Member functions can be either coded where they are declared
inside the class definition or outside the class definition using double-colon de-
referencing.
The following program template defines member functions inside the class
definition.
class MyNumber
{
private: int one;
void MyPrint()
{
cout << "Output from MyPrint member";
return 0;
};
public: char batchNum;
int StoreInOneint e)
{
one =e;
return 0;
};
};
Alternatively, the same can be accomplished with the following code.
class MyNumber
{
private: int one;
void MyPrint();
public: char batchNum;
int StoreInOne(int);

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.

10.5 DATA HIDING

As described earlier, making data members private in a class is an effective way


of hiding data from outside world. However, sometimes you may wish to access
and manipulate a private data member somewhere from outside the class. You
can do so by creating a member function in the class to access the private data
member. However, you must declare the member function as public so that the
same could be accessed from outside the class definition. The following code
snippets illustrate this concept.
class employee
{
private: int EmpNum;
char name[10];
public: int StoreInEmpNum(int e)
{
EmpNum = e;
return 0;
};
int ReadEmpNum()
{
return EmpNum;
};
};

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++

10.5.1 A C++ PROGRAM WITH CLASS

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

10.5.2 NESTING OF MEMBER FUNCTIONS

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++

Consider a class as shown below:


class abc
{
private:
//private data members
void function1();
int function2(int, int);
//other private member functions
public:
//public data members
void function3();
int function4(int, int);
//other public member functions
}
void function1()
{
//other statements
x = function2(2, 10); //nesting function
}

10.5.3 STATIC DATA MEMBERS

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++

int acc _no;


static int balance; //static data declaration
public:
void disp(int acc _no);
void getinfo( );
};
The static variable balance is initialized outside main() as follows:
int account::balance = 0; //static data definition
Consider the following Program which demonstrates the use of static data
member count. The variable count is declared static in the class but initialized to
0 outside the class.
#include <iostream.h>
#include <conio.h>
class counter
{
private:
static int count;
public:
void disp();
};
int counter::count = 0;
void counter::disp()
{
count++
cout << "The present value of count is " << count << "\n";
}
main()
{
counter cntl ;
for(int i=0; i<5; i++)
cnt1.disp();
getche();
}

160
B.Com.(CA) C++

You should get the following output from this program.


The present value of count is 1
The present value of count is 2
The present value of count is 3
The present value of count is 4
The present value of count is 5

10.5.4 STATIC MEMBER FUNCTIONS

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.

10.6 LET US SUM UP

• 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++

Check Your Progress


1. Describe the "kind of" class relationship. Give an example.
............................................................................................................................
............................................................................................................................
2. Describe "Is a" class relationship. Give an example.
............................................................................................................................
............................................................................................................................

10.7 KEYWORDS

Abstraction: The act of representing essential features without including the


background details or exploitations.
Encapsulation: The wrapping up of data and functions in a single unit (class).
Inheritance: The process by which objects of some class acquire the properties
of object of another class.
Class: A new data type that is created to solve a particular kind of problem.

10.8 QUESTIONS FOR DISCUSSION

1. What is object-oriented programming? List down its features and functions.


2. Define Object Oriented programming
3. Distinguish between Base class and Derived class
4. Fill in the blanks:
(a) A ______is a new data type that is created to solve a particular kind of
problem.
(b) A______is used to end the declaration.
5. State (T)rue or (f)alse:
(a) The attributes distinguish an object of the class.
(b) Behaviours of classes are represented by methods.

10.9 SUGGESTED READINGS

Herbert Schildt, The complete Reference-C++, Tata Mc Graw Hill


Robert Lafore, Object Oriented Programming in Turbo C++, Galgotia Publications.
E. Balagurusamy, Object Oriented Programming through C++, Tata McGraw Hill.

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

11.0 AIMS AND OBJECTIVES

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

Object-Oriented Programs (OOPs) attempt to emulate real world in software


system. The real world consists of objects, categorized in classes. For example,
you're using an object categorized as a book to learn about programming. OOP
describes a software system in terms of real world objects.

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++

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.

An object, on the other hand, is an instance of a class. It has physical existence


and hence occupies memory. You can create as many objects from a class once
you have defined a 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.

11.2 ARRAY OF OBJECTS

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.

The general syntax of the array of objects of a class is:


class class_name
{
private:
// data
// functions
public:
//data
// functions
};
class_name object [MAX]
where, MAX is a user defined size of the array of class objects e.g. 20 as shown
in example given below.
class employee
{
private:
char name[20];
int code;

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++

The list of student's is as follows


Roll no= 1
Age = 18
Height = 134
Weight = 45

11.3 OBJECTS AS FUNCTION ARGUMENTS

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++

The following Program illustrates calling of a function by reference. The program


declares a class integer to represent the variable x and defines functions to input
and display the value. The function written to swap the integer values of the
object takes the addresses of the objects.
#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)
{
int temp;
temp = x;
x = a1->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();
int1.swap(&int2);

173
B.Com.(CA) C++

cout << "\nafter swapping ";


cout <<"\nthe value of x belonging to object int1 is ";
int1.disp();
cout <<"\nthe value of x belonging to object int2 is ";
int2.disp();
cout << "\n";
getche();
}
You should see the following output.
Enter a value for x 15
Enter a value for x 50
the value of x belonging to object int1 is 15
the value of x belonging to object int2 is 50
after swapping
the value of x belonging to object int1 is 50
the value of x belonging to object int2 is 15

11.4 RETURNING OBJECTS

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++

integer sum(integer int2)


{
integer int3;
int3.x = x + int2.x;
return(int3);
}
};
main()
{
integer int1 ,int2,int3;
int1.getdata(15);
int2.getdata(25);
cout << "\nthe value of x for object int1 ";
int1.disp();
cout << "\nthe value of x for object int2 ";
int2.disp(); .
cout << "\n the sum of private data values of x belonging to objects int1
and int2 is ";
int3 = int1.sum(int2);
int3.disp();
getche();
}
You should see the following output from the program.
the value of x for object int1 15
the value of x for object int2 25
the sum of private data values of x belonging to objects int1 and int2 is 40

11.5 FRIEND FUNCTIONS

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++

The best way to access a private data member by a non-member function is to


change a private data member to a public group. But this goes against the
concept of data hiding and data encapsulation. A special mechanism available
known as friend function allows non-member functions to access private data. A
friend function may be either declared or defined within the scope of a class
definition. The keyword friend informs the compiler that it is not a member
function nor the property of the class.
The general syntax of the friend function is:
friend <return_type> <function_name>(argument list);
friend is a keyword. A friend declaration is valid only within or outside the class
definition. The following code snippet shows how a friend function is defined.
class sample
{
private:
int x;
public:
void getdata( );
friend void disp(sample abc); //friend function
};
void disp(sample abc) // non-member function without scope::
operator
{
cout << "value of x ="<< abc.x;
cout << endl;
}
Note that the function is declared as friend in the class and is defined outside
the class. The keyword friend should not be in both the function declaration and
definition. The friend declaration is unaffected by its location in the class. It can
be declared either in a public or a private section, which does not affect its
access right. For example, the following declarations of a friend function are
valid:
(1) The friend function disp( ) is declared in the public group
class sample
{
private :
int x;
public:
void getdata( );
friend void disp( );
};

176
B.Com.(CA) C++

(2) The friend function disp( ) is declared in the private group


class sample
{
private:
int x;
friend void disp();
public:
void getdata( );
};

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++

void disp(example eg)


{
cout << "Display the entered number"<< eg.x<< "\n";
}
main()
{
example egl;
eg1.getdata();
disp(eg1);
getche();
}
You should see the following output.
Enter the value of x
4
Display the entered number 4

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.

A non-member function can be friendly with one or more classes. When a


function has declared to have friendship with more than one class, the friend
classes should have forward declaration as it needs to access the private
members of both classes.

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++

//data members; Classes and Objects


//member functions;
friend <return_type> <fname>(class first, class second. . ..);
};
class second
{
private:
//data members;
//member functions;
public:
//data members;
//member functions;
friend <return_type> <fname>(class first, class second. . ..); };

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

the value of y entered is 11

the sum of two private data variables x & y is 31

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++

11.6 CLASS RELATIONSHIP

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.

11.7 TYPES OF RELATIONSHIPS

a. "Kind of" relationship: Objects may be a special type of another simpler


object. For example, a human being and an elephant are both "kind of"
mammals. Mammals have attributes - eyes, limbs and memory glands.
They also have behavior, say, walking. As human beings and elephants are
"kind of" mammals, they share the attributes and behaviors of mammals.
Human beings and elephants are subsets of mammal class. The following
Figure- 11.1 depicts the relationship between the mammal and human
beings.

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

3. "Has a" relationship/part of relationship: A human being has a heart.


This represents "has a" relationship. The same relationship can be
represented as: "A heart is a part of human being". The following figure
depicts the relationship between a human being and heart.

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

Confirmed Ticket Waiting Ticket


Attribute: Flight Number, Attribute: Flight Number,
Date, Time, Destination, Date, Time, Destination,
Seat Number Status
Behavior: Cancel 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.

11.8 LET US SUM UP

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++

Check Your Progress


1. Describe the "kind of" class relationship. Give an example.
............................................................................................................................
2. Describe "Is a" class relationship. Give an example.
............................................................................................................................

11.9 KEYWORDS

Abstraction: The act of representing essential features without including the


background details or exploitations.
Class: A new data type that is created to solve a particular kind of problem.
Super class: A class from which another class inherit properties.
Subclass: A class that inherits attributes and methods from super class.

11.10 QUESTIONS FOR DISCUSSION

1. What is object-oriented programming? List down its features and functions.


2. Diagrammatically explain different kinds of class relationships.
3. Define the following terms:
a. Object Oriented programming
b. Super class
c. Sub class
4. Distinguish between Base class and Derived class
5. Fill in the blanks:
(a) ______programs attempt to emulate real world in software system.
(b) Objective provide the benefit of _______, and _______.
(c) A ______is a new data type that is created to solve a particular kind of
problem.
(d) A______is used to end the declaration.
(e) A subclass inherits _______and_______from super class.
6. State (T)rue or (f)alse:
(a) The attributes distinguish an object of the class.
(b) Behaviours of classes are represented by methods.
(c) "Is a" relationship exists in human being and mammal.
7. What is the difference between superclass and subclass?

11.11 SUGGESTED READINGS

Robert Lafore, Object Oriented Programming in Turbo C++, Galgotia Publications.


E. Balagurusamy, Object Oriented Programming through C++, Tata McGraw Hill.

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.0 AIMS AND OBJECTIVES

After completion of this unit, you should be able to:


• Define constructors and destructor
• Explain default constructor method
• Define parameterized constructors
• Explain copy constructors
• Explain characteristics of destructive method

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++

members to initial values. When a C++ program runs it invariably creates


certain objects in the memory and when
the program exits the objects must be destroyed so that the memory could be
reclaimed for further use. C++ provides mechanisms to cater to the above two
necessary activities through
constructors and destructors methods.

12.2 CONSTRUCTORS

Constructor is public method that is called automatically when the object of a


particular class is created. C++ provides a default constructor method to all the
classes. This constructor method takes no parameters. Actually the default
constructor method has been defined in system.object class. Since every class
that you create is an extension of system.object class, this method is inherited
by all the classes.

The default constructor method is called automatically at the time of creation of


an object and does nothing more than initializing the data variables of the object
to valid initial values.

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

12.3 PARAMETERIZED CONSTRUCTORS

If it is necessary to initialize the various data elements of different objects with


different values when they are created. C++ permits us to achieve this objective
by passing arguments to the constructor function when the objects are created.
The constructors that can take arguments are called 'Parameterized
constructors.' The definition and declaration are as follows:
class dist
{
int m, cm;
public:
dist(int x, int y);
};
dist::dist(int x, int y)
{
m = x; n = y ;
}
main()
{
dist d(4,2);
d. show ();
}

190
B.Com.(CA) C++

12.4 CONSTRUCTORS WITH DEFAULT ARGUMENTS

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)

12.5 COPY CONSTRUCTORS

A copy constructor method allows an object to be initialized with another object


of the same class. It implies that the values stored in data members of an
existing object can be copied into the data variables of the object being
constructed, provided the objects belong to the same class. A copy constructor
has a single parameter of reference type that refers to the class itself as shown
below:
abc::abc(abc & a)
{
x=a.x;
y=a.y;
}
Suppose we create an object myabc1 with two integer parameters as shown
below:
abc myabc1(1,2);
Having created myabc1, we can create another object of abc type, say myabc2
from myabc1, as shown below:
myabc2=abc(& myabc1);
The data values of myabc1 will be copied into the corresponding data variables
of object myabc2. Another way of activating copy constructor is through
assignment operator. Copy constructors come into play when an object is
assigned another object of the same type, as shown below:

192
B.Com.(CA) C++

abc myabc1(1,2);
abc myabc2;
myabc2=myabc1;

Actually assignment operator(=) has been overloaded in C++ so that copy


constructor is invoked whenever an object is assigned another object of the same
type.

12.6 DYNAMIC CONSTRUCTORS

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++

void join (string & a, string & b)


{
length = a.length + b.length;
delete name;
name = new char [length + 1];
strcpy (name,a.name);
strcat (name," ");
strcat (name,b.name);
};
};
main()
{
char * FirstName= "Nanjappan";
string Fname(First name);
string Mname("Rathimaran”);
string Sname("Swathi");
string Halfname, Fullname;
//Joining FirstName with Surname
Halfname.join (Fname, Sname);
//Joining Firstname with Middlename & Surname
Fullname.join (Halfname, Mname);
Fname.display ();
Mname.display ();
Sname.display ();
Halfname.display();
Fullname.displayO();
}
You should see the following output.
/*
Name :- Nanjappan
Name :- Rathimaran
Name :- Swathi
Name:- Swathi Name :- Nanjappan.Rathimaran.Swathi
*/

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();
}

Let us assume we run this program with the following input.


/*
Enter Size Of matrix :- 2 2
Please Enter A No At Position 00 :- 1
Please Enter A No At Position 01 : - 1
Please Enter A No At Position 10 : - 2
Please Enter A No At Position 11 :- 2
*1
You should see the following output.
/*
The Matrix Entered
11
22
The Squared Matrix
11
44
The Cubed Matrix
11
88
*/

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.

A destructive method has the following characteristics:

1. Name of the destructor method is the same as the name of the class
preceded by a tilde(~).

2. The destructor method does not take any argument.

3. It does not return any value.

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++

12.8 ORDER OF CONSTRUCTOR & DESTRUCTOR CALLS

When an object is created one of its appropriate constructors is called. If no


constructor is explicitly defined for the class the default constructor is called.
This constructor may call the base class constructor which in turn may call its
own base class constructor. Thus, the order in which the constructors in a class
hierarchy are called is from base(est) to most derived classes in bottom-to-top
manner as shown in Figure 12.1.
Figure 12.1: Order of calling Constructors and Destructors
This order is only logical. While creating a house (highest level object) first you
create the components of the house like rooms, bathrooms, kitchen etc.
therefore, you must first call the constructors of the house's base class(es).
Similarly, while demolishing the house you first dismantle the outer walls then
inner components like rooms etc. Therefore, destructors are called in the reverse
order of the constructor calls.

12.9 LET US SUM UP

• C++ provides mechanisms to create and initialize program through


constructors and destructors methods.

• Constructor is a public member function of a class that is used to initialize


the member data variables to valid values when an object of that class is
created.

• C++ provides a default constructor method to all the classes. This


constructor method takes no parameters. The default constructor, however,
is not accessible if the class defines its own constructor.

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

• A destructor does just the opposite when the program creating an object
exits, thereby freeing the memory.

12.10 KEYWORDS

Constructor: A public member function that creates an object, allocate memory


space to the data members and initialize the data members to appropriate
values; at the time of object creation.
Destructor: A public member function that clears up the memory allocated to
an object at the time of program termination.

199
B.Com.(CA) C++

Parameterized constructors: Constructors that can take arguments.


Dynamic construction: Allocation of memory to objects at the time of their
construction.
Copy constructor: A constructor having a single parameter of reference type
that refers to the class itself.

12.11 QUESTIONS FOR DISCUSSION

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

12.12 SUGGESTED READINGS

Herbert Schildt, The complete Reference-C++, Tata Mc Graw Hill


Robert Lafore, Object Oriented Programming in Turbo C++, Galgotia Publications.
E. Balagurusamy, Object Oriented Programming through C++, Tata McGraw Hill.

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.0 AIMS AND OBJECTIVES

After completion of this unit, you should be able to:


• Overload unary operators
• Overload binary operators
• Memorize rules for overloading operators

13.1 INTRODUCTION

Operator Overloading is to be formed many exciting features of C++ language.


C++ has the ability to provide the operators with a special meaning for data type.
The mechanism of giving such special meaning to an operator is known as
Operator Overloading. Operator overloading provides a flexible option for the
creation of new definitions for C++ operators.

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.

Overloading an operator simply means attaching additional meaning and


semantics to an operator. It enables an operator to exhibit more than one
operations polymorphically, as illustrated below:

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"

This redefining the effect of an operator is called operator overloading. The


original meaning and action of the operator however remains as it is. An
operator is overloaded

We will consider overloading a unary operator - minus (-) to enable it to be


applicable on a set of numbers instead of a single number.

Function overloading allows different functions with different argument list


having the same name. Similarly an operator can be redefined to perform
additional tasks. Operator overloading is accomplished using a special function
which can be a member function or friend function. The general syntax of
operator overloading is:
<return_type>operator<operator_being_overloaded>(<argument list>);

operator is the keyword and is preceded by the return_type of the function. To


overload the addition operator (+) to concatenate two characters, the following
declaration, which could be either member or friend function, would be needed:
char * operator + (char *s2);

13.2 OVERLOADING UNARY OPERATORS

In case of unary operator overloaded using a member function no argument is


passed to the function whereas in case of a friend function a single argument
must be passed. Following program overloads the unary operator to negate an
object. The operator function defined outside the class negates the individual
data members of the class integer.
#include <iostream.h>
#include <conio.h>
class integer
{
int x,y,z;
public:
void getdata(int a, int b, int c);

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++

You should see the following output.


S: 11 -21 -31
S:-11 21 31

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

13.3 OVERLOADING BINARY OPERATORS USING FRIENDS

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++

You should see the following output.


value = 11
value = 22
value = 33

Note that the operator overloading function is invoked by S3=S1+S2. We have


passed only one argument to the function. The left hand object S1 invokes the
function and S2 is actually the argument passed to the function.

13.4 MANIPULATION OF STRINGS USING OPERATOR OVERLOADING

ANSI C implements strings using character assays, pointers and string


functions. There are no operators for manipulating the strings. There are no
direct operator that could act upon the strings. Although, these limitations exist
in C++ as well, it permits us to create our own definitions of operators that can
be used to manipulate the strings very much similar to the decimal numbers for
e.g.
string x = string y + string z;
The following program to overload the '+' operator to append one string to
another:

# 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++

13.5 RULES FOR OVERLOADING OPERATORS

To overload any operator, we need to understand the rules applicable Let us


revise some of them which have already been explored. Following are the
operators that cannot be overloaded in table-13.1.

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

Table 13.1: Operators that Cannot be Overloaded

• Operators already predefined in the C++ compiler can be only overloaded.


Operator cannot change operator templates that is for example the
increment operator ++ is used only as unary operator. It cannot be used as
binary 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++

• Unary operators, overloaded by means of a member function, take no


explicit argument and return no explicit values. But, those overloaded by
means of a friend function take one reference argument (the object of the
relevant class).
• Binary operators overloaded through a member function take one explicit
argument and those which are overloaded through a friend function take
two explicit arguments.
Table 13.2

Operator to Arguments passed to Argument passed to


Overload the the
Member Function Friend Function
Unary Operator No 1
Binary Operator 1 2

• We cannot use friend functions to overload some operators which shows in


table-13.3. The Member functions can be used to overload them.

Operator Purpose
= Assignment operator
() Function call operator
[] Subscripting operator
-> Class member access
operator

13.6 LET US SUM UP

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

Overloading: It is an operator simply means attaching additional meaning and


semantics to an operator. It enables an operator to exhibit more than one
operations polymorphically.
Binary Operators: These are operators which require two operands to perform
the operation.

210
B.Com.(CA) C++

13.8 QUESTIONS FOR DISCUSSION

1. Write about overloading unary operators.


2. What are the rules for overloading operators?
Check Your Progress: Model Answers
(a) two operands
(b) one argument/friend function
(c) assays, points and string functions
(d) C++

13.9 SUGGESTED READINGS

Herbert Schildt, The complete Reference-C++, Tata Mc Graw Hill


Robert Lafore, Object Oriented Programming in Turbo C++, Galgotia Publications.
E. Balagurusamy, Object Oriented Programming through C++, Tata McGraw Hill

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.0 AIMS AND OBJECTIVES

After completion of this unit, you should be able to:


• Understand different types conversions

14.1 INTRODUCTION

The Constants and variables of different types are mixed in an expression. C


applies automatic type conversion to the operands as per rules governing. An
assignment operation also causes the automatic type conversion. The type of
data to the right of an assignment operator is automatically converted to the
type of the variable on the left.
int x;
float y = 54.002;
x=y;
convert x to an integer before its values is assigned to y. Thus, the fractional
part is truncated. The type conversion are automatic as long as the data type
involved are built in types.
Consider the following expression that adds two objects and then assigns the
results to a third object.
x3 = x1 + x2;

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.

14.2 TYPE CONVERSIONS

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

14.3 BASIC TO 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++

char* name2 = " COIMBATORE" ;


s1 = string(name1);
s2 = name2;
The program statement
s1 = string (name1);
first converts name 1 from char* type to string type and then assigns the string
type values to the object s1. The statement
s2 = name2;
performs the same job by invoking the constructor implicitly. Consider the
following example
class time
{
int hours;
int minutes;
public:
time (int t) II constructor
{
hours = t / 60; //t is inputted in minutes
minutes = t % 60; .
}
};

In the following conversion statements :


time T1; //object T1 created
int period = 160;
T1 = period; //int to class type
The object T1 is created. The variable period of data type integer is converted
into class type time by invoking the constructor. After this conversion, the data
member hours ofT1 will have value 2 arid minutes will have a value of 40
denoting 2 hours and 40 minutes.
Note that the constructors used for the type conversion take a single argument
whose type is to be converted. In both the examples, the left-hand operand of =
operator is always a class object. Hence, we can also accomplish this conversion
using an overloaded = operator.

214
B.Com.(CA) C++

14.4 CLASS TO BASIC TYPE

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++

14.5 ONE CLASS TO ANOTHER CLASS TYPE

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.

Conversion Conversion takes place in


Source class Destination class
Basic nclass Not applicable Constructor

Class nBasic Casting operator Not applicable

Class nclass Casting operator Constructor


Table 14.3

216
B.Com.(CA) C++

When a conversion using a constructor is performed in the destination class, we


must be able to access the data members of the object sent (by the source class)
as an argument. Since data members of the source class are private, we must
use special access functions in the source class to facilitate its data flow to the
destination class.

Consider the following example of an inventory of products in a store. One way


of keeping record of the details of the products is to record their code number,
total items in the stock and the cost of each item. Alternatively we could just
specify the item code and the value of the item in the stock. The following
program uses classes and shows how to convert data of one type to another.
#include<iostream.h>
#inc1ude<conio.h>
class stock2;
class stockl
{
int code,item;
float price;
public:
stockl(int a,int b,float c)
{
code=a;
item=b;
price=c;
}
void disp()
{
cout<< "code" <<code <<"\n";
cout<< "Items" <<item <<"\n";
cout<< "Price per item Rs." <<price <<"\n";
}
int getcode()
{return code;}
int getitem()
{return item;}
int getprice()

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

Check Your Progress


Fill in the blanks:
(a) Binary Operators are operators which require ............................... to
perform the operation.
(b) If Binary Operators are overloaded by means of member function, the
function takes ..............................., whereas it takes two arguments in
case of ...............................
(c) ANSIC implements strings using character ...............................,
............................... and ...............................
(d) ............................... allows us to define a overloaded casting operator that
convert a class type data to basic type.

219
B.Com.(CA) C++

14.6 LET US SUM UP

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

Overloading: It is an operator simply means attaching additional meaning and


semantics to an operator. It enables an operator to exhibit more than one
operations polymorphically.
Conversion function: The general form of an overloaded casting operator
function, also referred to as a conversion function

14.8 QUESTIONS FOR DISCUSSION

1. What is the conversion function?


2. Write different type of Conversions

14.9 SUGGESTED READINGS

Herbert Schildt, The complete Reference-C++, Tata Mc Graw Hill


Robert Lafore, Object Oriented Programming in Turbo C++, Galgotia Publications.
E. Balagurusamy, Object Oriented Programming through C++, Tata McGraw Hill

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.0 AIMS AND OBJECTIVES

After completion of this unit, you should be able to:


• Overload a Function
• Memorize rules for overloading features

15.1 INTRODUCTION

Function overloading: C++ enables several functions of the same name to be


defined, as long as these functions have different sets of parameters (at least as
far as their types are concerned). This capability is called function overloading.
When an overloaded function is called, the C++ compiler selects the proper
function by examining the number, types and order of the arguments in the call.
Function overloading is commonly used to create several functions of the same
name that perform similar tasks but on different data types.

15.2 OVERLOADING A FUNCTION

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.

15.3 RESTRICTIONS FOR OVERLOADING FUNCTIONS


You cannot overload the following function declarations if they appear in the
same scope. Note that this list applies only to explicitly declared functions and
those that have been introduced through using declarations:

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]);

The first array dimension is insignificant when differentiating parameters;


all other array dimensions are significant. For example, the following are
declarations of the same function:

g(char(*)[20]);
g(char[5][20]);

The following two declarations are not equivalent:

g(char(*)[20]);
g(char(*)[40]);

224
B.Com.(CA) C++

• Function declarations with parameters that differ only because one is a


function type and the other is a pointer to a function of the same type. For
example, the following are declarations of the same function:
void f(int(float));
void f(int (*)(float));
• Function declarations with parameters that differ only because of cv-
qualifiers const, volatile, and restrict. This restriction only applies if any of
these qualifiers appears at the outermost level of a parameter type
specification. For example, the following are declarations of the same
function:
int f(int);
int f(const int);
int f(volatile int);
Note that you can differentiate parameters with const, volatile and restrict
qualifiers if you apply them within a parameter type specification. For
example, the following declarations are not equivalent because const and
volatile qualify int, rather than *, and thus are not at the outermost level of
the parameter type specification.
void g(int*);
void g(const int*);
void g(volatile int*);
The following declarations are also not equivalent:
void g(float&);
void g(const float&);
void g(volatile float&);
• Function declarations with parameters that differ only because their default
arguments differ. For example, the following are declarations of the same
function:
void f(int);
void f(int i = 10);
• Multiple functions with extern "C" language-linkage and the same name,
regardless of whether their parameter lists are different.
#include <iostream.h>
// This program illustrate the use of Function overloading
int sqr(int x);
float sqr(float x);
double sqr(double x);

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);
}

15.4 LET US SUM UP

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

Overloading: It is an operator simply means attaching additional meaning and


semantics to an operator. It enables an operator to exhibit more than one
operations polymorphically.
Binary Operators: These are operators which require two operands to perform
the operation.

15.6 QUESTIONS FOR DISCUSSION

1. Write about overloading a function?.


2. What are the rules for overloading operators?

15.7 SUGGESTED READINGS

Herbert Schildt, The complete Reference-C++, Tata Mc Graw Hill


Robert Lafore, Object Oriented Programming in Turbo C++, Galgotia Publications.
E. Balagurusamy, Object Oriented Programming through C++, Tata McGraw Hill

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

16.0 AIMS AND OBJECTIVES

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

Reaccessability is yet another feature of OOP's. C++ strongly supports the


concept of reusability. The C++ classes can be used again in several ways. Once
a class has been written and tested, it can be adopted by other programmers.
This is basically created by defining the new classes, reusing the properties of
existing ones. The mechanism of deriving a new class from an old one is called
'INHERITENCE'. This is often referred to as 'IS-A' relationship because very
object of the class being defined "is" also an object of inherited class. The old
class is called 'BASE' class and the new one is called 'DERIVED' class.

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

16.2 OVERVIEW OF INHERITANCE

ƒ 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++

16.3 MOTIVATION OF INHERITANCE

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

ƒ Inheritance partitions system architecture into semi-disjoint components


that are related hierarchically.

ƒ Therefore we may be able to modify the reuse sections of the inheritance


hierarchy without disturbing existing code.

16.4 BENEFITS OF INHERITANCE

ƒ Increase reuse and software quality.


ƒ Programmers reuse the base classes instead of writing new classes.
ƒ Using well – tested base classes helps reduce bugs in application that use
them.
ƒ Reduce object code size.
ƒ Enhance extensibility and comprehensibility
ƒ Help support more flexible and extensible architectures.
ƒ Often useful for modeling and classifying hierarchically related domains.

16.5 ADVANTAGES OF INHERITANCE

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
};

16.6 LET US SUM UP

• Inheritance is the capability of one class to inherit properties from another


class. It supports reusability of code and is able to simulate the transitive
nature of real life objects.

• Inheritance has many forms: Single inheritance, multiple inheritance,


hierarchical inheritance, multilevel inheritance and hybrid inheritance.

• A subclass can derive itself publicity, privately or protected. The derived


class constructor is responsible for invoking the base class constructor; the
derived class can directly access only the public and protected members of
the base class.

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

16.8 QUESTIONS FOR DISCUSSION

1. What is single inheritance?


2. What is multilevel inheritance?
3. Write about virtual base classes.

16.9 SUGGESTED READINGS

Herbert Schildt, The complete Reference-C++, Tata McGraw Hill.


Robert Lafore, Object Oriented Programming in Turbo C++, Galgotia
Publications.
E. Balagurusamy, Object Oriented Programming through C++, Tata McGraw
Hill.

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

17.0 AIMS AND OBJECTIVES

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

Reaccessability is yet another feature of OOP's. C++ strongly supports the


concept of reusability. This is basically created by defining the new classes,
reusing the properties of existing ones. The mechanism of deriving a new class
from an old one is called 'INHERITENCE'. The old class is called '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.

235
B.Com.(CA) C++

17.2 TYPES OF INHERITANCE

The following is the different types of inheritance exist in object oriented


programming. Each inheritance plays an various role and has different uses in
various situation.
ƒ Single Inheritance
ƒ Multilevel Inheritance
ƒ Multiple Inheritances
ƒ Hierarchical Inheritance
ƒ Hybrid Inheritance

17.2.1 SINGLE INHERITANCE

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

The variable b,c,d and


method get2() is inherited
by class Y

237
B.Com.(CA) C++

Class Y own member function

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.

17.2.2 MULTILEVEL INHERITANCE

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.

The declaration of multilevel inheritance as follows


Class A
{
……….. Statements
…….. Member functions
};
Class B : public A
{
…….. Statements
……… member functions
};
Class C : public B
{

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

17.2.3 MULTIPLE INHERITANCES

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.

17.2.4 HIERARCHICAL INHERITANCE

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

Mango Apple Orange

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++

cout<<”Enter value of A and B”;


cin>>a>>b;
}
};
class A : public root Class A inherit property of class root
{
public :
int x;
public :
void dispA( )
{
x = a+ b;
cout<<”The value of X is”<<x;
}
};
class B : public root Class B inherit property of class root
{
public :
int y;
public :
void dispB( )
{
y = a+ b;
cout<<”The value of X is”<<y;
}
};
void main( )
{
A obj; // The object creation for Class A for access.
B obj1; // The object creation for Class B for access.
obj.get1( ); calling the member function in class root.
obj.dispA( );
obj1.get1( ); calling the member function in class root.

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.

17.2.5 HYBRID INHERITANCE

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.

Example : Combination of multiple and multilevel inheritance.

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++

Class C : public B, public D // class C inherit the class B and Class D


{ // Class is root for class B and Class X
public :
int c,final;
public :
void inputC( )
{
cin>>c;
}
void disp2( )
{
final = sum + c + x;
cout<”The Sum of A, B, C and X is”<<final;
}
};
void main( )
{
C obj; // Object creation for root class C

obj. inputA( ); // calling the function in class A


obj.inputB( ); // calling the function in class B
obj. dget( ); // class the function in class D
obj. inputC( ); // class the function in root class C
obj.disp2( ); // displaying the output in root class 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.3 LET US SUM UP

• Inheritance has many forms: Single inheritance, multiple inheritance,


hierarchical inheritance, multilevel inheritance and hybrid inheritance.
• A subclass can derive itself publicity, privately or protected. The derived
class constructor is responsible for invoking the base class constructor; the
derived class can directly access only the public and protected members of
the base class.
• 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.
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.

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.

17.5 QUESTIONS FOR DISCUSSION

1. What is single inheritance?


2. What is multilevel inheritance?

17.6 SUGGESTED READINGS

Herbert Schildt, The complete Reference-C++, Tata McGraw Hill.


Robert Lafore, Object Oriented Programming in Turbo C++, Galgotia Publications.
E.Balagurusamy, Object Oriented Programming through C++, Tata McGraw Hill.

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

18.0 AIMS AND OBJECTIVES

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

Reaccessability is yet another feature of OOP's. C++ strongly supports the


concept of reusability. The C++ classes can be used again in several ways. Once
a class has been written and tested. This is basically created by defining the new
classes, reusing the properties of existing ones. The old existing class is called

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.

18.2 TYPES OF BASE CLASSES

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.

18.3 DIRECT BASE CLASSES

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
…………..
…………..
};

18.4 INDIRECT BASE CLASSES

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.

18.5 TYPES OF DERIVATION

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++

The following are the existing access specifier in class concept.


Private Local to the class
Public Global to all class
Protected Access to inherited class
Example:
Class A
{
Statements
};
Class B : ___________ A
{ ( Pubic, Private, Protected)
Statements Access specifier will decide the flow
of execution or control transfer
}

18.6 PUBLIC INHERITANCE

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++

Member in Derived Access status How Obtained


class
P Not accessible From class A
Q Protected From class A
R Public From class A
G Private Added by class B
Void get( ) Public From class A

18.7 PRIVATE INHERITANCE

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.

Member in Derived Access status How Obtained


class
P Not accessible From class A
Q Private From class A
R Private From class A
T Private Added by class
B

18.8 PROTECTED INHERITANCE

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++

The general format of the public derivation is


Class base-class-name
{
Statements
};
Class derived-class-name : protected base-class-name
{
Statements
}
Example:
Class A
{
Private :
int P;
protected :
int Q;
public:
int R;
};
Class B : protected A
Protected access specifier is used for base
{ Class A
Private :
Float X;
};
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;
float X;

260
B.Com.(CA) C++

The following table displays the access specifier of the data member of the base
class in the derived class.

Member in Derived Access status How Obtained


class
P Not accessible From class A
Q Protected From class A
R Protected From class A
X Private Added by class B

18.9 LET US SUM UP

• Inheritance has many forms: Single inheritance, multiple inheritance,


hierarchical inheritance, multilevel inheritance and hybrid inheritance.

• A subclass can derive itself publicity, privately or protected. The derived


class constructor is responsible for invoking the base class constructor; the
derived class can directly access only the public and protected members of
the base 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++

18.11 QUESTIONS FOR DISCUSSION

1. What is protected inheritance?


2. What is private inheritance?
3. Write about virtual base classes.

18.12 SUGGESTED READINGS

Herbert Schildt, The complete Reference-C++, Tata McGraw Hill.


Robert Lafore, Object Oriented Programming in Turbo C++, Galgotia
Publications.
E. Balagurusamy, Object Oriented Programming through C++, Tata McGraw
Hill.

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

19.0 AIMS AND OBJECTIVES

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

The polymorphism is one of the different features in object oriented


programming in c++. The key idea behind the polymorphism is nothing but have
“one name have a multiple forms or usage”. In c++ programming the
polymorphism is implemented through overloading combination of function and
operator. The basic concept is that compiler is able to select the appropriate
member function or method for a particular call at the compile time itself we
called it as a early binding or static binding or static linking. And it also called
as compile time polymorphism.

19.2 POLYMORPHISM

The polymorphism is one of the different features in object oriented


programming in c++. The key idea behind the polymorphism is nothing but have
“one name have a multiple forms or usage”. In c++ programming the
polymorphism is implemented through overloading combination of function and
operator.

263
B.Com.(CA) C++

The concept of overloading member functions are executed by checking or


matching the number of arguments used, then the type. Based on the number of
arguments and the type the compiler will select for execution. The basic concept
is that compiler is able to select the appropriate member function or method for
a particular call at the compile time itself we called it as a early binding or static
binding or static linking. And it also called as compile time polymorphism.

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.3 LET US SUM UP

• The polymorphism is one of the different features in object oriented


programming in c++. The key idea behind the polymorphism is nothing but
have “one name have a multiple forms or usage”. In c++ programming the
polymorphism is implemented through overloading combination of function
and operator.

19.4 KEYWORDS

Polymorphism is one of the different features in object oriented programming in


c++. Polymorphism is implemented through overloading combination of function
and operator.

19.5 QUESTIONS FOR DISCUSSION

1. What is polymorphism?
2. What is operator overloading?
3. Write about function overloading.

19.6 SUGGESTED READINGS

Herbert Schildt, The complete Reference-C++, Tata McGraw Hill.


Robert Lafore, Object Oriented Programming in Turbo C++, Galgotia
Publications.
E. Balagurusamy, Object Oriented Programming through C++, Tata McGraw
Hill.

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

20.0 AIMS AND OBJECTIVES

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

Polymorphism refers to the property by which objects belonging to different


classes are able to the same substance, but in different forms. An essential
requirement of polymorphism is therefore the ability to refer to objects without
any regard to their class. Use of single pointer variable to refer to the objects of
different classes. The use of pointer to base class to refer to all the derived
classes. The compiler simply ignores the contents of the pointer and chooses the
member function that matches the type of the pointer. The polymorphism is to
achieve using known as Virtual Functions.

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++

20.2 VIRTUAL FUNCTIONS

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.

1. The virtual functions must be members of some classes.

2. They cannot be static member function be declared.

3. They members of classes can be accessed by using object pointers.

4. A virtual function can be a friend of another class in different level.

5. A virtual function in a base class must be declared, even though in such


condition it may not be utilized or not to be used.

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.

20.3 PURE VIRTUAL FUNCTION

ƒ A virtual function, equated to zero is called a pure Virtual function.


ƒ It is a function declared in a base class that has no definition relative to the
base class.
ƒ A class containing such pure function is called an abstract class.
ƒ We have not defined any object of class media and therefore the member
function in the base class has been defined “empty”.
ƒ The empty function we called it as a “ do – nothing “ functions.

270
B.Com.(CA) C++

The following is a method to define the do – nothing or empty function.


Virtual void display( ) = 0;
The above declared form is called as pure virtual functions.
ƒ A pure virtual function is a function declared in a base class that has no
definition relative to the base class.
ƒ In such conditions / circumstances, the compile requires each derived
class to either define the function or redeclared it as a pure virtual
functions.
ƒ Another important aspect is to be remember that a class containing pure
virtual functions cannot be used to declare any objects of its own.
ƒ The above all conditions be satisfied and called as abstract base class.
ƒ The key objective of an abstract base class is to provide some traits to the
derived classes and to create a base pointer required for achieving run time
polymorphism.

20.4 POINTER TO DERIVED CLASSES

ƒ 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
}

20.5 LET US SUM UP

• The polymorphism is one of the different features in object oriented


programming in c++. The key idea behind the polymorphism is nothing but
have “one name have a multiple forms or usage”. In c++ programming the
polymorphism is implemented through overloading combination of function
and operator.

272
B.Com.(CA) C++

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

20.6 KEYWORDS

Polymorphism is one of the different features in object oriented programming in


c++. Polymorphism is implemented through overloading combination of function
and operator.
Virtual function concept will plays a vital role in programming language.
Pointers concept is applied for base class
Derived class: A class inheriting properties from another class. (also called sub
class)

20.7 QUESTIONS FOR DISCUSSION

1. What is Virtual Functions?


2. What is Pointer to Derived Classes?
3. Write about pure virtual functions.

20.8 SUGGESTED READINGS

Herbert Schildt, The complete Reference-C++, Tata McGraw Hill.


Robert Lafore, Object Oriented Programming in Turbo C++, Galgotia
Publications.
E. Balagurusamy, Object Oriented Programming through C++, Tata McGraw
Hill.

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

21.0 AIMS AND OBJECTIVES

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++

21.2 C++ STREAMS

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.

Input Device Input Stream Extraction


From input stream

Program

Insertion
Into output stream
Output Device Output Stream

Figure 21.1 : Data Streams

21.3 C++ STREAM CLASSES

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

istream_withassign iostream_withassign ostream_withassign

Figure 21.2 : Stream classes for console I/O operations

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++

21.4 LET US SUM UP

• C++ treats each source of input and output uniformly.

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

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

• 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

I/O Stream: An abstraction that views every input/output device as a stream or


array or sequence of bytes.
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.

21.6 QUESTIONS FOR DISCUSSION

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

21.7 SUGGESTED READINGS

Herbert Schildt, The complete Reference-C++, Tata Mc Graw Hill


Robert Lafore, Object Oriented Programming in Turbo C++, Galgotia Publications.
E. Balagurusamy, Object Oriented Programming through C++, Tata McGraw Hill.

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

22.0 AIMS AND OBJECTIVES

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

22.2 FORMATTED I/O OPERATIONS

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++

22.2.1 IOS FORMAT FUNCTIONS

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.

Format required Flag (a1) Bit-field (a2)


Left justified output ios :: left ios :: adjustified
Right justified output ios :: right ios :: adjustified
Padding after sign or base ios :: internal ios :: adjustified
indicator
Scientific notation ios :: scientific ios :: floatfield
Fixed point notation ios :: fixed ios :: floatfield
Decimal base ios :: dec ios :: basefield
Octal base ios :: oct ios :: basefield
Hexadecimal base ios :: hex ios :: basefield
Table 22.1 : Flags and bit fields for setf() fucntion
Table 22.2 shows flags that do not have bit fields

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.

Manipulatore Meaning Equivalent


setw(int w) Set the field width to w width()
setprecision(int d) Set the floating point precision to d. precision()
setfill(int s) Set the fill character to s fill()
setiosflags(long g) Set the format flag g setf()
resetiosflags(long g) Clear the flag specified g unsetf()
endl Insert new line and flush stream “\n”
Table 22.3 : Manipulators and their meanings

22.3 UNFORMATTED I/O OPERATIONS

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++

put() and get() Functions


The classes istream and ostream define two member functions fet() and put()
respectively to handle the single character input / output operations. There are
two types of get() functions available
get(char *) //assigns the input character to its argument
get (void) //returns the input character
Since these functions are members of the input ./ output stream classes, using
an appropriate object, we must invoke them.
getline() and write() Functions
Read and display a line of text more efficiently using the line oriented input /
output functions getline() and write(). The getline () function reads a whole line of
text that ends with a new line character. This function can be invoked by using
the object cin.
cin.getline(line, size);
This function call invokes the function getline() which reads character input into
the variable line. The reading is terminated as soon as the new line character
‘\n’ is encounterd or size-1 characters are read. The new line character is read
but not saved.
The write() function displays an entire line.
cout.write(line, size);
The first argument line represents the name of the string to be displayed and the
second argument size indicates the number of characters to display. If the size is
greater than the length of line, then it displays beyond the bounds of line.
Check Your Progress
1. Write formatted console I/O operations with ios format unctions?
............................................................................................................................
............................................................................................................................
2. Write Manipulator operations?
............................................................................................................................
............................................................................................................................

22.4 LET US SUM UP

• C++ treats each source of input and output uniformly.


• The << operator is a predefined operator. This line puts the text in the file
or an output stream.

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

I/O Stream: An abstraction that views every input/output device as a stream or


array or sequence of bytes.
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.

22.6 QUESTIONS FOR DISCUSSION

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

22.7 SUGGESTED READINGS

Herbert Schildt, The complete Reference-C++, Tata Mc Graw Hill


Robert Lafore, Object Oriented Programming in Turbo C++, Galgotia Publications.
E. Balagurusamy, Object Oriented Programming through C++, Tata McGraw Hill.

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

23.0 AIMS AND OBJECTIVES

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.

23.2 DATA FILE OPERATIONS

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:

™ Opening a data file

™ Reading data stored in the data file into various variables and objects in the
program

™ Writing data from a program into a data file

• Removing the previously stored data in the file

• Without removing the previously stored data in the file

I. At the end of the data file

II. At any other location in the file


™ Saving the data file onto some secondary storage device
™ Closing the data file once the ensuing operations are over
™ Checking status of file operation

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

Data File Input Stream Program

Figure 21.1 : Input Stream Currently attached to a Data file

Keyboard Input Stream Program

Figure 21.2 : Input Stream Currently attached to Keyboard

289
B.Com.(CA) C++

Program Output Stream Monitor

Figure 21.3 : Output Stream Currently attached to Monitor

Program Output Stream Data File

Figure 21.4 : Output Stream Currently attached to a Data file

Program Output Stream Printer

Figure 21.5 : Output Stream Currently attached to a Printer

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.

A file normally remains in a closed state on a secondary storage device until


explicitly opened by a program. A file in open state file has two pointers
associated with it:
1. 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.
2. 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. These two file positions are independent, and either one can point
anywhere at all in the file. To elucidate I/O streaming in C++ let us write a
small program.
#include <fstream.h>
int main()
{
ofstream filename("d:\sdebu.dat");
filename << "This text will be saved in the file named sdebu.dat in D:\";
filename.close();
return 0;
}

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++

23.3 OPENING A FILE

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.

Opening Mode Description


ios::in Open file in input mode for reading
ios::out Open file in output mode for wri
ios::app Open file in output mode for writing the new content at the end
of the file without removing the previous contents of the file.
ios::ate Open file in output mode for writing the new content at the
current position of the pointer without removing the previous
contents of the file.
ios::trunc Open file in output mode for writing the new content at the
beginning of the file removing the previous contents of the file.
ios::nocreate The file is not created. The operation takes place on existing file.
If the file is not found an error occurs.
ios::noreplace The existing file is not overwritten. The operation takes place on
existing file. If the file is not found an error occurs.
ios::binary Opens the file in binary mode reading not a character but
reading / writing whatever binary value is stored in the file

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++

In this program the statement fstream myfile ("data.dat",ios::in | ios::out);


creates an object from class fstream. At the time of execution, the program
opens the file data.dat in read/write mode (ios::in | ios::out) which allows to
read from the file, and put data into it, at the same time. This is done by
allowing the program to move the character pointer in the file to a desired
location before reading or writing. The read and write operation takes place on
the current position of the pointer in the file . Therefore you might need to shift
this position to a desired location. The member function seekg() of the class
fstream allows you to do just that as shown below.

myfile.seekg(ios::beg) //Take the pointer to the beginning of the file

myfile.seekg(ios::end) //Take the pointer to the end of the file

myfile.seekg(10) //Take the pointer to 10 characters after the current location

myfile.seekg(-10) //Take the pointer to 10 characters before the current location

Moreover, the function seekg()is overloaded to take two parameters. Thus,


another form of the function is,

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++

23.4 CLOSING AN OPENED FILE

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

23.5 STREAM STATE MEMBER FUNCTIONS

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.

These functions are:

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

• bad(): This function returns a boolean value (TRUE or FALSE). It returns


true if the last file operation was bad else return false. It actually checks
whether badbit is set or not.

298
B.Com.(CA) C++

• eof(): This function also returns a boolean value (TRUE or FALSE). It


returns true if the last file operation reached the end of the file under
operation. It checks eofbit.

• fail(): This function also returns a boolean value (TRUE or FALSE). It


returns true if the last file operation failed due to any reason else returns
false. It checks failbit.

• good(): This function also returns a boolean value (TRUE or FALSE). It


returns true if the last file operation succeeded without any error else
returns false. It checks goodbit.

• 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++

checkState.clear(ios::goodbit); //set the current status to ios::goodbit


if(checkState.rdstate() == ios::goodbit) //check if goodbit was set correctly
cout << "OK! goodbit is et alright!\n";
checkState.clear(ios::eofbit); //set the state to ios::eofbit
if(checkState.rdstate() == ios::eofbit) // check again the state
cout << "EOF!\n";
checkState.close();
}

23.6 READING/WRITING A CHARACTER FROM/INTO A FILE

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++

Some useful file operation functions


In addition to the function discussed thus far, there are many more functions
which come handy in writing practical programs on data file processing. An
assorted list of them is given below:
tellg()
This function returns an int type value representing the current position of the
pointer inside the data file opened in input mode.
tellp()
This function does to output files what tellg() does to input files. It returns an int
type value representing the current position of the pointer inside the data file
opened in output
Mode.
seekg()
While reading data from a file this function is used to shift the pointer to a
specified location.
seekp()
This function does to output files what seekp() does to input files. It shifts the
pointer to the specified location in the output file. If you want to overwrite the
last 5 characters, you will have to go back 5 characters from the current pointer
position.
ignore()
This function is used when reading a file to ignore certain number of characters.
You can use seekg() as well for this purpose just to move the pointer up in the
file. However, ignore() function has one advantage over seekg() function. You can
specify a delimiter character in ignore() function whence it ignores all the
characters up to the first occurrence of the specified delimiter.
getline()
This function is used to read one line at a time from an input stream until some
specified criterion is met. The stopping criterion can be either specified number
of characters (Array_size) or the first occurrence of a delimiter (delimiter) else the
entire line (up to newline character '\n') is read. If you wish to stop reading until
one of the following happens:
1) You have read 10 characters
2) You met the letter 'm'
3) There is new line
Then the function will be called as follows:
getline(Carray,10,'m');

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.

23.7 STRUCTURES AND FILE OPERATIONS

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

23.8 CLASSES AND FILE OPERATIONS

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.

23.9 LET US SUM UP

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

• C++ library provides prefabricated classes for data streaming activities. In


C++, Data File Operations 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.

• A file normally remains in a closed state on a secondary storage device until


explicitly opened by a 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.

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

• 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

I/O Stream: An abstraction that views every input/output device as a stream or


array or sequence of bytes.

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++

23.11 QUESTIONS FOR DISCUSSION

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.

23.12 SUGGESTED READINGS

Herbert Schildt, The complete Reference-C++, Tata Mc Graw Hill


Robert Lafore, Object Oriented Programming in Turbo C++, Galgotia Publications.
E. Balagurusamy, Object Oriented Programming through C++, Tata McGraw Hill.

308

You might also like