0% found this document useful (0 votes)
15 views279 pages

OOPs With C++ Programming

C++ oop

Uploaded by

soufiane.maafi
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)
15 views279 pages

OOPs With C++ Programming

C++ oop

Uploaded by

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

OOPs with C++

Programming

Kiran Gurbani
B.E., MCA, [Link].,
Head of Computer Science and IT Department,
R.K. Talreja College,
Ulhasnagar - 3, Dist.
Thane, Maharashtra.

ISO 9001:2015 CERTIFIED


© Author
No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any
means, electronic, mechanical, photocopying, recording and/or otherwise without the prior written permission of the
author and the publisher.

First Edition : 2018

Published by : Mrs. Meena Pandey for Himalaya Publishing House Pvt. Ltd.,
“Ramdoot ”, Dr. Bhalerao Marg, Girgaon, Mumbai - 400 004.
Phone: 022-23860170, 23863863; Fax: 022-23877178
E-mail: himpub@[Link]; Website: [Link]

Branch Offices :

New Delhi : “Pooja Apartments”, 4-B, Murari Lal Street, Ansari Road, Darya Ganj, New Delhi - 110 002.
Phone: 011-23270392, 23278631; Fax: 011-23256286

Nagpur : Kundanlal Chandak Industrial Estate, Ghat Road, Nagpur - 440 018.
Phone: 0712-2738731, 3296733; Telefax: 0712-2721216

Bengaluru : Plot No. 91-33, 2nd Main Road, Seshadripuram, Behind Nataraja Theatre,
Bengaluru - 560 020. Phone: 080-41138821; Mobile: 09379847017, 09379847005

Hyderabad : No. 3-4-184, Lingampally, Besides Raghavendra Swamy Matham, Kachiguda,


Hyderabad - 500 027. Phone: 040-27560041, 27550139

Chennai : New No. 48/2, Old No. 28/2, Ground Floor, Sarangapani Street, T. Nagar,
Chennai - 600 017. Mobile: 09380460419

Pune : “Laksha ” Apartment, First Floor, No. 527, Mehunpura, Shaniwarpeth (Near Prabhat Theatre),
Pune - 411 030. Phone: 020-24496323, 24496333; Mobile: 09370579333

Lucknow : House No. 731, Shekhupura Colony, Near B.D. Convent School, Aliganj,
Lucknow - 226 022. Phone: 0522-4012353; Mobile: 09307501549

Ahmedabad : 114, “SHAIL”, 1st Floor, Opp. Madhu Sudan House, C.G. Road, Navrang Pura,
Ahmedabad - 380 009. Phone: 079-26560126; Mobile: 09377088847

Ernakulam : 39/176 (New No. 60/251), 1st Floor, Karikkamuri Road, Ernakulam, Kochi - 682 011.
Phone: 0484-2378012, 2378016; Mobile: 09387122121
Cuttack : New LIC Colony, Behind Kamala Mandap, Badambadi,
Cuttack - 753 012, Odisha. Mob.: 9338746007

Kolkata : 108/4, Beliaghata Main Road, Near ID Hospital, Opp. SBI Bank, Kolkata - 700 010.
Phone: 033-32449649; Mobile: 07439040301

DTP by : Sneha Gaonkar


Printed at : M/s Sri Sai Art Printer, Hyderabad. On behalf of HPH.
Dedication
I would like to dedicate this book to my mother and father Kavita
S. Bajaj and Sahijram Bajaj. I would like to thank my son Chirag
Gurbani for being my stress buster and a motivating force for putting
a better performance every time.

My sincerest big thanks for a lifetime to Mr. S.K. Srivastava of


Himalaya Publishing House Pvt. Ltd. for giving me best writing advice
and motivation and whose belief in this book has kept me motivated
and inspired and encouraged on even the darkest of days.

- Kiran Gurbani
Preface
It gives me immense pleasure to present this First Edition of “OOPs with C++ Programming”
to the teachers and students of Bachelor of Computer Science and Information Technology. This book
has been written as per the syllabus prescribed by the Indian Universities.
The first C with Classes compiler was called Cfront, which was derived from a C compiler called
CPre. It was a program designed to translate C with Classes code to ordinary. In 1983, the name of the
language was changed from C with Classes to C++. The ++ operator in the C language is an operator
for incrementing a variable, which gives some insight into how Structure regarded the language. (At
my institution, C++ is the first language introduced, immediately followed by C.)
The chapters in this book mainly focuses on new features added around this time, the most
notable of which are OOPs concepts, constructor, destructor, virtual functions, function and operator
overloading, file handling, templates, references with the & symbol, the const keyword, and single-
line comments using two forward [Link] concept and theory of each topic is followed by the
theoretical explanation and some self-assessment questions. All practical solutions of C++ are
provided.
I have tried my level best to give everything in this book in proper manner. Still few points from
book may be explained in better way than presently are there in the book.
Constructive suggestions and comments from the users will be sincerely appreciated. I would
appreciate hearing from you about any textual errors or omissions which you identify. If you would
like to suggest improvements or to contribute in any way, I would be glad to hear from you.
Please send correspondence to kiranrktcollege@[Link]
Last but not the least, I would like to give big lifetime thanks to Mr. S.K. Srivastava, Himalaya
Publishing House Pvt. Ltd. for providing an environment which stimulates new thinking and
innovations and his support, motivation, guidance, cooperation and encouragement to write this book.
I am very grateful for his support and thank him for his true blessings.

Kiran Gurbani
kiranrktcollege@[Link]
Mob.: 7769979964
Contents
1. Introduction to OOPs and C++ with Variable and Operators 1 – 28

2. Control Structures and Loops 29 – 41

3. Functions in C++ 42 – 55

4. Classes and Objects 56 – 75

5. Arrays, Pointers and References 76 – 87

6. Constructors and Destructors 88 – 105

7. Manipulators 106 – 115

8. Function and Operator Overloading 116 – 127

9. Inheritance 128 – 147

10. Virtual Functions and Polymorphism 148 – 154

11. File Handling 155 – 172

12. Templates 173 – 182

13. Exception Handling 183 – 191

14. Standard Template Library 192 – 198

Practical List 199 – 270


Introduction to OOPs
1 and C++ with Variable
and Operators
Chapter

Chapter Outline
1.1 Introduction to C Language
1.2 Compilers and Interpreters
1.3 Difference between C and C++
1.4 Software Evolution (Evolution of Programming Language)
1.5 Object Oriented Programming Paradigm
1.6 Benefits of OOPs/Features of OOPs and C++
1.7 Applications of OOPs
1.8 What is C++?
1.9 Features of C++ Language
1.10 Structure of C++ Program
1.11 Basic Data Types in C++
1.12 C++ Operators
1.13 Preprocessor Directive
1.14 Declaration of Variables
1.15 Input and Output

1.1 Introduction to C Language


C language is widely used in the development of operating systems.
An Operating System (OS) is a software(collection of programs) that controls the various
functions of a computer. Also it makes other programs on your computer work. For example, you
cannot work with a word processor program, such as Microsoft Word, if there is no operating system
installed on your computer. Windows, Unix, Linux, Solaris, and MacOS are some of the popular
operating systems. Same way to run the programs in a particular programming language we need a
language complier.
2  OOPs with C++ Programming

Origin of C:
Dennis M. Ritchie, a systems engineer at Bell Laboratories, New Jersey developed C in the early
1970’s.

1.2 Compilers and Interpreters


A program written in a high level language must be translated into machine language before it
can be executed. This is known as compilation or interpretation, depending on how it is carried out.
Compilers translate the entire program into machine language before executing any of the
instructions. Interpreters, on the other hand, proceed through a program by translating and then
executing single instructions, or small groups of instructions.
A compiler or interpreter is itself a computer program that accepts a high-level program (e.g. a C
program) as input data, and generates a corresponding machine – language program as output. The
original high-level program is called the source program, and the resulting machine-language program
is called the object program.
Every high-level language must have its own compiler or interpreter for a particular platform. It
is generally more convenient to develop a new program using an interpreter rather than a compiler.
Once an error-free program has been developed, a compiled version will normally executed much
faster than an interpreted version.
Features of C language:
C is a structured programming language, which means that it allows you to develop programs
using well-defined control structures (you will learn about control structures in the articles to come),
and provides modularity (breaking the task into multiple sub tasks that are simple enough to
understand and to reuse).
C is often called a middle-level language because it combines the best elements of low-level or
machine language with high-level languages.
1. C is a case sensitive Language
2. C is Mother of all Languages
3. C is a structured programming Language
4. C is a Middle level Language
5. C has inbuilt Library functions
6. C allows us to create user defined functions
7. C has its own Complier
8. C is used for creating powerful System Programs.
9. C is a flexible & Powerful language.
10. C has 32 Keywords or Reserved Words
11. C supports graphics.
12. C supports different functions, structures, arrays with powerful data structures like stack,
Linklist, Queue, Trees.
C’s ability to communicate directly with hardware makes it a powerful choice for system
programmers. In fact, popular operating systems such as Unix and Linux are written entirely in C.
Additionally, even compilers and interpreters for other languages such as FORTRAN, Pascal, and
Introduction to OOPs and C++ with Variable and Operators  3

BASIC are written in C. However, C’s scope is not just limited to developing system programs. It is
also used to develop any kind of application, including complex business ones. The following is a
partial list of areas where C language is used:
 Embedded Systems
 Systems Programming
 Artificial Intelligence
 Industrial Automation
 Computer Graphics
 Space Research
 Image Processing
 Game Programming
C language can be used for creating system programs, but it does not support Object concepts &
data hiding concept. Every variable and functions are public in scope, hence no data hiding concept
can be provided. C does not support object oriented concepts like Data encapsulation, Data
Polymorphism, Data Abstraction, Data Inheritance. To Provide these We will switch to C++ language
with powerful data hiding concepts.

1.3 Difference Between C and C++


C C++
In C language data hiding concept is not available. In C++ language data hiding concept is available by
using class, object with public, private and
protected scope specifier.
C is a structured programming language. C++ is a object oriented language.
In C programming scanf() and printf() functions are In C++, cin and cout are available for reading and
used for Reading variable values and printing variable printing variable value, included in iostream.h
values, they are available in stdio.h header file. header file.
The C program files are identified by .c extension. The C++ program files are identified by .cpp
extension.
In C language we can write structure which is In C++ language we can create class which is
collection of different data types. collection of different data types i.e. data members
and member functions encapsulated in one unit
called class.
C does not support data polymorphism concept. It C++ supports data polymorphism concept with the
won’t support operator and function overloading. help of operator and function overloading.
The C language does not support inheritance concept. The C++ language support inheritance with super
class and sub class.
C does not support constructor, destructor concept C++ supports constructor and destructor for
hence does not have new and delete operator. creating object and destroying object with the help
of new and delete operator.
C language does not support default arguments. C++ supports default arguments within parameters
of functions.
C language does not support friend function facility. C++ language supports friend function facility.
4  OOPs with C++ Programming

In C language templates can not be created. In C++ language templates can be created.
C language does not support exception handling. C++ language supports exception handling.
C language does not support the concept of virtual C++ supports the concept of virtual function with
functions. the help of abstraction and Inheritance.

1.4 SOFTWARE EVOLUTION (EVOLUTION OF PROGRAMMING


LANGUAGE)

1, 0

Machine Language
Assembly Language

Procedure-oriented Language
Structured Programming Language
Object Oriented Programming

Software technology has a growth of a tree. Software evolution has a layer of growth. Each layer
representing an improvement over the previous one.
Initially the programs are to be written in machine language but it is in the form of 0’s and First
hence difficult to remember.
Second layer of assembly language which has Mnemonics in the form of English language.
Language used by ALU section of the CPU.
Third layer is procedure oriented language (POP) language. In this problem is viewed as a
sequence of Instructions. All functions or tasks are combined in one procedure program.
In the fourth layer the program is divided into functions. Instructions of the program is divided
into groups known as functions.
In 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. In the fifth layer,
modularization is used with the help of functions and in large programs it is very difficult to identify
what data is used by which function. Hence data hiding concept can be provided using functions.
In object oriented following characteristics are followed:
1. Large programs are divided into smaller programs known as functions called objects.
2. Data hiding concept is provided.
Introduction to OOPs and C++ with Variable and Operators  5

1.5 OBJECT ORIENTED PROGRAMMING PARADIGM


Object oriented programming provides data hiding concept. 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 function that operate on it, and protect it from modification from
outside functions.
Object oriented programming allows decomposition of a problem into a number of entities called
objects.
Object A Object B

Data Data

Communication
functions functions

Object C

functions

Data

Organisation of data and functions in OOPs


Some of the characteristics of object oriented programming:
1. Object oriented approach provides modularizing by diving program into functions.
2. Programs are divided into objects.
3. Functions that operate on the data of an object are tied together in the data structure.
4. Data is hidden and cannot be accessed by external functions.
5. Objects may communicate with each other through functions.
6. Data and functions can be combined together in one encapsulated unit called class.
7. New data and functions can easily be added whenever necessary.
Basic concepts of object-oriented programming:
Some important concepts are needed to understand in OOPs:
1. Objects
2. Classes
3. Data Abstraction
4. Data Encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic binding
9. Message passing
6  OOPs with C++ Programming

1. Objects:
(a) Objects are the basic Run-time entities also called as Real World thing.
(b) An object in C++ is a representation of some physical, logical or conceptual entity. For
example, an object can be a vehicle, bank account, animal, place, a table of data, any item,
or it represents a person etc.
(c) Every object is identified by its own properties and methods which indicates behaviour,
states and tasks of object.
(d) The object can take place in memory and associated in a memory like a structure in C or
Record in pascal.
(e) An object is an instance of user-defined data type called class. We can also say that object
is a variable whose type is a user defined class.
(f) When a program is executed, the objects interact by sending messages to one another.
For example 1, if customer and account are two objects, customer object may send a message to
the account object requesting for the bank balance.
For example 2, if student and marks are two objects, student object may send a message to the
marks object requesting for grade of student.
Customer Object Account Object

Object : Customer Object : Account

Data: CustNo Data: AccNo


Name Name
accNo Balance

Functions: getcustdetails() Functions: display balance()


getbalance() deposit()
withdraw()

Object : student

Data: Name
Date of Birth
Marks

Functions: Total
Average
Display

2. Classes:
(a) Class is predefined blank template or blueprint which can be reused number of times.
(b) The entire set of data and code of an object are wrapped together in one capsule also
called user-defined data type called class.
(c) Class encapsulates the Attributes and behaviour of an entity.
(d) Class specifies what data and what functions will be included in objects of that class.
(e) Classes are user-defined data types and behave like the build-in types of a programming
language.
Introduction to OOPs and C++ with Variable and Operators  7

(f) Once a class has been defined, we can create any number of objects belonging to that
class. Thus class is collection of objects of similar type.
(g) Class construct supports data hiding concept by combining data and code in one unit with
powerful keywords private, protected and public.
(h) The syntax of declaring class is
Class classname
{ scope:
data members;
scope:
member functions;
}
Class student
{ private:
int rollno;
Char name [10];
public:
void getdata();
void display();
}
3. Data Abstraction:
(a) Abstraction refers data hiding, this indicates that only essential things will be known to
the user and non essential things will be abstracted or hided from the user.
(b) Abstraction refers to the way of representing essential features without including
background details and explanations. This states that only foreground details will be
shown to the user and background details will be hided.
(c) Abstraction permits the programmer to look at something without being concerned with
its internal details.
(d) Abstraction in structure program shows the task performed by the function, but it hides
from the client actually how function executes internally and how task is performed. This
is called functional abstraction.
(e) This insulation of the data from direct access by the program is called data hiding or
information hiding.
(f) Classes uses the concept of data abstraction are known as Abstract Data Types (ADT).
(g) Simple pen object may have different properties or attributes like its essential features are
colour, cost, ballpen or inkpen but non essential features are like type of ink, raw material
used for plastic of pen.
(h) Encapsulating together data/information hiding feature allows limited visibility to the
class users. Access specifiers like private, protected, public in C++ are used to implement
data hiding.
(i) Abstraction helps in managing the complexity of the software.
8  OOPs with C++ Programming

4. Data Encapsulation:
(a) The internal data of a class i.e. data members and member functions are first separated
from outside world and then they are put in a unit is called encapsulated unit.
(b) Encapsulation groups all pieces of object into one packet.
(c) Encapsulated data is not accessible outside the world. It can be accessed only by member
functions which are declared within a class.
(d) This insulation of the data from direct access by the program is called data hiding or
information hiding.
(e) All the essential properties of the objects are encapsulated in a class. The attributes are
called as data members to hold information. The functions that operate on these data are
called methods or member functions.
5. Inheritance:
(a) Inheritance is the process of creating new classes, called derived classes, from existing
classes. These existing classes are often called base classes.
(b) The derived class inherits all the properties and methods of the base class and can add
new features, properties and methods of its own, based on requirement. By adding these
refinements the base class remain unchanged.
(c) Inheritance is the process by which objects of one class acquire the properties of objects
of another class.
(d) C++ allows a programmer to create hierarchical classification i.e. it supports parent-child
relationship.
(e) The parent class is a base class also called super class and the child class is also called as
derived class or sub class.
(f) The concept of inheritance provides the idea of reusability. This means we can reuse
existing classes many times and also can add additional features to an existing class with
modifying it. Reusability concept saves lot of money and time. Reusability code helps in
case of distributing class libraries. Reusability increases program reliability.
(g) Inheritance is similar to inheriting characteristics from our parents.
Bird

Attributes
Features
Lay eggs

Flying Bird Non Flying Bird


Attributes Attributes
_________ _________
_________ _________
_________ _________

Robin Swallow Penguin Kiwi


Attributes Attributes Attributes Attributes
_________ _________ _________ _________
_________ _________ _________ _________
_________ _________ _________ _________
Introduction to OOPs and C++ with Variable and Operators  9

6. Polymorphism:
(a) Poly means many, morphism means many forms, i.e. more than one form of operation.
(b) Polymorphism indicates the ability to take more than one form.
(c) More than one form of operation may behave differently by creating different instance.
(d) The behaviour change of object depends upon the types of data used i.e. one thing
behaves differently at different places.
(e) Polymorphism allows objects having different internal structures to share the same
external interface.
(f) It supports function overloading and operator overloading concept. Function overloading
indicates that functions of a class with same name but either different number of
arguments or different types of arguments.
You can not overload a function which can have same number of arguments of same type
and in same sequence and differing only in their return types.
For example,
You behave differently when your friend asks about something and when your boss asks
something.
Example,
Same name sum function can be used for addition of two integers, addition of two floats,
addition of three integers.
sum (int a, int b);
sum (float x, float y);
sum (int a, int b, int c);
It is also called as function polymorphism.
When a single function name is used to perform different types of tasks is called function
overloading. This is same as like a particular word having several different meanings
depending on the context.
(g) In operator overloading we can overload the in-built operators as well as user-defined
data types. You can not change the semantics of an operator.
Existing operator like ‘+’ can be used for addition of two integers and also can be used
for addition of two float or ‘+’ sign can be used for concentration of two strings.
Overloading can not alter the basic template of operator.
Shape

Draw()

Circle Object Box Object Triangle Object

Draw (box) Draw (triangle)


Draw (circle) e.g. Draw
i.e. Draw
i.e. Draw (x, y, r)
(x1, y1, x2 , y2) (x1, y1, x2 , y2, x3,y3 )
10  OOPs with C++ Programming

7. Dynamic binding:
(a) Dynamic binding is a binding at Run time.
(b) Dynamic binding is also called as late binding.
(c) Binding refers to the linking of procedure call or function call to the code or definition to
be executed in response to the call.
(d) The code associated with a given procedure call or function call is not known until the
time of the call at run-time.
(e) With the help of dynamic binding, one can access method of a derived class using a
pointer of a base class depending on to which object it points to at run-time.
8. Message passing:
(a) Object oriented consists of a set of objects that communicate with each other.
(b) Message passing involves following steps:
(i) Creating classes that define objects and their behaviour.
(ii) Creating objects from class definitions.
(iii) Establishing communication among objects.
(c) Objects communicate with one another by sending and receiving information or by
passing messages.
(d) 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.
(e) Message passing involves specifying the name of the object, the name of the function i.e.
message and the information to be sent.
(f) Customer is an object.
Balance is a message
Account no. is an information
Customer. Balance (account no)
  
Object Message information
(g) The communication between objects is feasible as long as it is alive.

1.6 Benefits of OOPs/Features of OOPs and C++


OOPs offers several benefits and features. It specifies the following advantages:
1. C++ supports features of structured programming and object oriented programming.
2. C++ is a versatile language for handling large programs.
3. C++ supports data hiding concept by using data encapsulation and data abstraction with the
help of class using powerful keywords private, public and protected. This hiding concept
helps us to build secure programs.
4. Object oriented systems can be easily upgraded from small to large systems, hence software
complexity can be easily managed.
Introduction to OOPs and C++ with Variable and Operators  11

5. Object oriented programming supports inheritance concept through inheritance reusability


concept can be achieved as well as we can eliminate redundant code and extend the use of
existing classes.
6. We can build programs from the standard working module, rather than having to start
writing the code from scratch. This leads to saving of development time and higher
productivity.
7. It is possible to have multiple instances of an object.
8. Message passing techniques for communicating between objects.
9. C++ provides friend facility in which friend function defined within the class can use data
members of the class, which are declared in private area.
10. C++ supports polymorphism concept with the concept of function overloading and operator
overloading.
11. C++ has 48 keyword/reserved words.

1.7 Applications of OOPs


In real time systems often much more complex objects and number of objects with different
attributes and methods are used. By combining all these things OOPs are used.
The areas of application of OOP are:
1. Real-time systems.
2. Object oriented databases.
3. Simulation and modeling.
3. Neural networks and parallel programming.
5. Decision support and office automation system.
6. CIM/CAM/CAD systems.

1.8 What is C++?


1. C++ is an object oriented programming language developed by Biarne Stroustrup at AT & T
Bell laboratories.
2. C++ is an extension of C with major addition of the class (encapsulated unit) feature.
3. C++ is a system programming language, used to create different programs for the system.

1.9 Features of C++ Language


1. C++ is a case sensitive language.
2. C++ supports all features of structure as well as object oriented programming language.
3. C++ is a versatile language for handling for large programs. System programs can be created
with the help of C++ language.
4. C++ supports data encapsulation and data abstraction with data hiding concept with
powerful keywords like private, public and protected.
5. C++ supports data polymorphism concept with operator and function overloading.
12  OOPs with C++ Programming

6. C++ supports Inheritance concept with Reusability of a class.


7. C++ supports friend function and friend class facility.
8. C++ supports memory management concept with the help of constructors and destructors by
using new and delete.
9. C++ supports default arguments concept for member functions.
10. C++ allows us to create different templates.
11. C++ supports error handling with exception handling.
12. C++ supports virtual functions.
13. C++ supports 48 keywords or reserved words.

1.10 Structure of C++ Program


include section/Link section
class declaration
class function definition
int main ()
{
local declaration;
stmt;
stmt;
return 0;
}
1. Include section: In this section, # is a preprocessor directive which directs inclusion of
header file specified in the Include statement.
C++ is having streambuffer class which is basics of all stream classes.
It holds the character stream functions for input and output. Hence it is having istream and
ostream. Istream is the buffer defined in a streambuffer class to store set of characters from
input device. ostream is a buffer which is provided by streambuffer class used to display
stream of characters. Iostream is the buffer defined in streambuffer class which is used to
store and display stream of characters, hence with the help of iostream, cin and cout
statement can be used.
2. Class declaration: This section has class, classname with different data members and
member functions defined in public or private scope of class. Class declaration is enclosed
between { and } (curly braces) and class declaration should be terminated by;.
3. Class function definition: The member functions which are declared inside the class
declaration’ then these functions definition can be defined outside the class function
declaration.
4. Return type of main (): In C++, main returns an integer type value to the operating system
i.e. main function should end with return statement. Return type can be void which indicates
main function does not return any value.
Introduction to OOPs and C++ with Variable and Operators  13

Example:
# include <iostream.h>
int main ()
{
cout <<”Welcome to C++”;
return 0;
}

1.11 Basic Data Types in C++


Data types in C++ can be classified under various categories:
C++ Data Types

User defined type Built-in-type Derived type

structure array
union function
class pointer
enumeration reference

Integral type Void floating type

int char float double

unsigned signed unsigned signed long


int int char char double

long int short int

signed unsigned unsigned signed


long int long int short int short int
A. Built-in-type:
(a) Integral type: The data types in this type are int and char. The modifiers signed, unsigned,
long and short may be applied to character and integer basic data type.
The size of int is 2 bytes and the size of char is 1 byte.
We can use normally,
(I) int can store integers in the range – 32767 to 32767.
(II) unsigned can store integers in the int range 0 to 65535.
(III) char – stores a character.
 signed char – characters stored like type char
can store integers in the range – 127 to 127
14  OOPs with C++ Programming

 unsigned char – characters stored like type char


can store integers in the range 0 to 255
 short – can store integers smaller compared to using int. It can be used with short
int, signed short, signed short int.
 long – can store integers in the range – 2147483647 to 2147483647
can be used as long int, signed long, signed long int.
 unsigned long – can store integers in the range – 0 to 4294967295
(b) void
void is used for:
To specify the return type of a function when it is not returning any value.
To indicate an empty argument list to a function
e.g.
void functionname (void)
 
Indicate indicates
No Return empty parameters
type

(c) floating type


The data type in this can be float or double. The size of the float is 4 bytes and size of double
is 8 bytes. It is used to store the numbers with decimal. The modifier long can be applied to
double and the size of long double is 10 bytes.
(I) float data type supports single precision numbers.
(II) double data type supports double precision numbers and having size greater than float.
 long double can store double precision numbers and having size greater than
double.
B. User-defined type:
These are the data types created by the user by combining number of inbuilt data types.
(a) Structure: Structure is user defined data type. It is collection of different data types in one
unit or user defined data type i.e. structure also called as compound type. The convention
used is struct, scope of members are by default public.
(b) Union: Union is user defined data type. It is also collection of different data types in one
encapsulated unit called union. The convention used is union. It can store values of different
types in a single location, scope of members is by default public.
(c) Class: Class is a user defined data type which can be used just like any other basic data type
once declared, the class variables are known as objects. For classes all variables are by
default private. The convention used is class, also called compound type.
(d) Enumeration:
(i) An enumerated data type is another user defined type which provides a way of attaching
names to numbers to increase simplicity of the code.
(ii) Enumerations are a distinct type from ints, ints are not implicility converted to enums.
Introduction to OOPs and C++ with Variable and Operators  15

(iii) It uses enum keyword which automatically enumerates a list of words by assigning them
values 0, 1, 2 etc.
(iv) By default, enumerators are assigned integer value starting with 0.
C. Derived data types:
(a) Arrays: Array is a derived type. It is a collection of similar data elements. It can be
collection of integers, collection of characters.
datatype arrayname [size of array]
int x[10];
data objects are stored in consecutive memory locations under a common heading or variable
name.
(b) functions: functions are the derived functions are called user defined function to perform
specific task. Compare to C there is lots of modification in C++ due to object oriented in
concept.
(c) Pointer: Pointers can be used to point and reference address of another variable. In C++
concept of constant pointer and pointer to a constant pointer can be used.
e.g. char const * P1 = “Welcome”;
 pointer allows to return structured variables from function.
 It allows to pass variables, arrays, functions, strings and structures as function argument.
 It supports dynamic allocation and deallocated of memory segments.
Size of range of C++ Basic data type
Sr. No. Type Bytes Range
1. Char 1 – 128 to 127
2. Unsigned char 1 0 to 255
3. Signed char 1 – 128 to 127
4. Int 2 – 32768 to 32767
5. Unsigned int 2 0 to 65535
6. Signed int 2 – 32768 to 32767
7. Short int 2 – 32768 to 32767
8. Unsigned short int 2 0 to 65535
9. Signed short int 2 – 32768 to 32767
10. Long int 4 – 2147483648 to 2147483647
11. Signed long int 4 – 2147483648 to 2147483647
12. Unsigned long int 4 0 to 4294967295
13. float 4 3.4 E – 38 to 3.4 E +38
14. Double 8 1.7E – 308 to 1.7 E + 308
15. long double 10 3.4 E – 4932 to 1.1 E + 4932
16  OOPs with C++ Programming

1.12 C++ Operators


(1)
C++ Operators Arithmetic
Operators

(2)
Assignment
Operators
(3)
Comparison and
Relational Operators
Logical operators
Logical Operators
Equality Operators
(4)
Bitwise Logical Operators
(5)
Special Operators (a) Unary operators
(b) Ternary operator
(c) Comma operator
(d) Scope operator
(e) New and delete operator
(f) Other operators
1. Arithmetic Operators
The operators used to perform arithmetic operations such as addition (+), subtraction (–),
multiplication (*), division (/) are called arithmetic operators. These basic operators are known as
binary operators as they require two variables to be evalued.
Sr. No. Operator Meaning
1. + Addition or unary plus
2. – Subtraction or unary minus
3. * Multiplication
4. / Division
5. % Modulo division (Reminder of an Integer division)
The variables or constants on which operators are operated are known as operands. The
arithmetic in C++ can be of three types:
(a) Integer Arithmetic.
(b) Real Arithmetic.
(c) Mixed Mode Arithmetic.
(a) Integer Arithmetic: When both the operands are integers, the operation is called integer
arithmetic.
For e.g.,
55 – 5 = 50
55 + 5 = 60
14 * 2 = 28
14/2 = 7 (Decimal part truncated integer division)
14% 2 = 0 (Remainder of division)
– 14 % 3 = – 2
14 % 3 = 2
6/7=0
Introduction to OOPs and C++ with Variable and Operators  17

(b) Real Arithmetic: An arithmetic operation involving only real operands is called real
arithmetic. A real operand may assume values either in fractional or exponential form.
For e.g.,
1.5 – 0.7 = 0.8
1.5 + 0.7 = 2.2
1.5 * 2.0 = 3.0
6.0/7.0 = 0.857143
1.0/3.0 = 0.3333
– 2.0/3.0 = – 0.666667
% (modulo operator) can not be used with Real numbers
x_int/y_int = result_int
x_int/y_float = result_float
x_float/y_int = result_float
x_float/y_float = result_float
(c) Mixed Mode Arithmetic: C++ permits us to mix integer operand with real operand. When
one operand is real and the other is integer, the expression is called mixed mode arithmetic
expression i.e. if either of the operand is of the real type, then only real operation is
performed and result is always a real number.
For e.g.,
15/10.0 = 1.5
4 + 3.5 = 7.5
2. Assignment Operators
Assignment operators are used to assign the result of an expression or constant to variable.
The assignment operators can be used within any valid expression, the usual assignment operator
is ‘=’.
variable_Name = constant or expression;
The arithmetic expression is a combination of variables, constants and operators
E.g., x = a + b;
z = 0;
final = 100;
During the assignment operator the value of expression of right hand side is assigned to left side
variable.
During the assignment operator the value of the expression on right hand side is computed and is
assigned to the variable on the left hand side.
Short hand assignment operators:
In addition to the usual assignment operator ‘=’. C++ has short hand assignment operators of the
form.
variable op = expression;
18  OOPs with C++ Programming

Where op is C++ binary arithmetic operator


(a) + =
a+=1
a=a+1
if a = 5
a=5+1
a=6
x+=y+1
x = x + (y + 1)
(b) – =
a–=1
a=a–1
(c) * =
a*=5
a=a*5
(d) a/ = b
a = a/b
(e) a% = b
a=a%b
(f) & = (Bitwise and Operator)
a&=5
a=a&5
(g) / = (Bitwise or operator)
a/=6
a=a/6
(h) ~ = (Bitwise complement operator)
a~=7
a=a~7
3. Comparison and Logical Operators
(a) Relational Operators
(b) Logical Operators
(c) Equality Operators
(a) Relational Operators: With the help of relational operators we can take a decision by
comparing two or more operands values.
Relational operators compare values to see if they are equal or if one of them is greater than
the other and so on.
Operator Meaning
< is less than
<= is less than equal to
Introduction to OOPs and C++ with Variable and Operators  19

> is greater than


>= is greater than equal to
expression1 relational_operator expression2
Expression Result
3>4 false
6<=2 false
10 > – 32 True
(23 * 7) > = (–67 + 89) True
(b) Logical Operators: The logical operators are those which are used to perform logical
expression such as logical AND, logical OR and logical NOT.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
The logical AND and logical OR operators are used when we want to test for more than one
condition and make decision.
Logical AND indicates that compound expression is true when two conditions or
expressions are true.
Situation Result
true && true true
true && false false
false && true false
false && false false
Logical OR indicates the Results is true if any or all inputs are true.
expression1||expression2
Situation Result
true || true true
true || false true
false || true true
false || false false
(a < b) || (b > c)
true || false
true
Logical negation Operator (!): A logical expression can be changed from false to true or
from true to false with negation operator (!)
Situation Result
! (true) false
! (false) true
! (expression)
20  OOPs with C++ Programming

Example:
! (a < b) || (c > b)
! (4 < 5) || (6 > 5)
! (true) || (true)
false || true
true
(c) Equality Operators: These operators are used to check the equality of the given expression
or statement.
== is a comparison operator between two expressions used for equality check.
!= is a comparison operator between two expression used for not equality check.
Expression Result
a == b false if a = 4, b = 6
(a * b)! = c true if a = 4, b = 6, c= 8
‘s’ == ‘k’ false

Operator Meaning
== Equal to
!= Not equal to
4. Bitwise Logical Operators
C++ is having powerful features is the set of bit manipulation operators. These permits the
programmer to access and to manipulate individual bits within piece of data.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR (EXOR)
>> Bitwise right shift
<< Bitwise left shift
~ Bitwise complement
(a) Bitwise AND: The bitwise AND operation will be carried out between the two bit patterns
of the two operands.
Variable Value Binary pattern
x 5 0101
y 2 0010
x&y 0 0000
a 6 0110
b 3 0011
a&b 2 0010
To generate a 1 bit in the result, bitwise AND need a one in both numbers.
Introduction to OOPs and C++ with Variable and Operators  21

(b) Bitwise OR: The bitwise OR operations result 1 if any one of bit value is 1.
Bitwise OR
Variable Value Binary pattern
x 5 0101
y 2 0010
x/y 7 0111
a 6 0110
b 1 0001
a/b 7 0111
(c) Bitwise Exclusive OR: The bitwise exclusive OR will be carried out by the notation ^. To
generate a 1 bit in the result, a bitwise exclusive OR needs a one in either number but not
both.
Bitwise EX – OR
Variable Value Binary pattern
x 5 0101
y 2 0011
x^y 7 0111
a 6 0110
b 3 0011
a^b 5 0101
(d) Bitwise Right shift: The right shift >> operator is used for right shifting. For y = 41 binary
pattern is 0010 1001.
y >> 3 will result
0010 1001
00010100 *****shift
00001010 *****shift
00000101 *****shift
y >> is 0000 0101
(e) Bitwise Left shift: The << operator is used for left shifting. For y = 41 binary pattern is
0010 1001.
Variable Value Binary pattern
x 33 0010 0001
x << 3
0010 0001
shift *** 01000010
shift *** 10000100
shift *** 00001000
x << 3 is 00001000
22  OOPs with C++ Programming

(f) Bitwise complement: The complement operator ~ switches all the bits in a binary pattern
that is all the zeroes become ones and all ones become zeroes. It acts as a 1’s complement.
Variable Value Binary pattern
x 23 0001 0111
~x 132 1110 1000
y ff 1111 1111
~y 00 0000 0000
5. Special Operators
There are some special operators used in C++ language to perform particular type of operations.
(a) Unary operators.
(b) Ternary operators.
(c) Comma operators.
(d) Scope operators.
(e) New and delete operators.
(f)Other operators.
(i) parentheses for grouping expression.
(ii) Membership operators (Manipulators).
(a) Unary operators: The unary operators require only a single expression to produce a line.
Some unary operators may be followed by the operands such as incrementer and
decrementer.
The most common unary operation is unary minus, where a minus sign precedes a numerical
constant, a variable or an expression.
Operator Meaning
* Contents of the storage field to which a pointer is pointing. Hence * is used to get the
content of the address operator. Pointing to a particular memory.
& Address of variable
– Negative value (minus sign)
~ Bitwise complement
++ Incrementer
i++ post increment
++i pre increment
i++  i = i + 1  i = 5 + 1  6
–– Decrementer
i – – post decrement
– – i pre decrement
i––i=i–1i=5–14
type forced type of conversion
sizeof size of the subsequent data type or type in byte. It is used to direct the compiler to reserve
the memory size or block to the particular data type.
Introduction to OOPs and C++ with Variable and Operators  23

(b) Ternary operator (?:): C++ includes a very special operator called the ternary or
conditional operator. It is called ternary operator because it uses three expressions. It is short
hand version of if_else construct.
The format of the ternary operator is expression1?expression2:expression3
If expression1 evaluated is true then expression2 is evaluated otherwise expression3 is
evaluated.
Example,
(1) if (i % 2 = = 0)
even = true
else
even = false
even = (i % 2 = = 0)? true : false;
(2) if (i > j)
max = i
else
man = j
max = (i > j)? i : j;
(3) if (x > y)
x=x+3
else
x=x–3
x = (x > y)? x + 3 : x – 3;
(c) Comma operator: C++ uses a comma operator in two ways:
1. The first use of comma is as a separator in the variable declaration int a, b, c;
float x, y, z;
2. The second use of comma is as a separator used in for loop.
for (i = 1, j = 2; i < = 10; i++, j +=3)
{
cout <<i<< ‘‘ “ <<j<<endl;
}
(d) Scope operator (::): The double colon (::) sign is used as the scope resolution operator in
C++.
The scoping operator is used in a class member function definition.
(e) New and delete operators: C++ has two unary operators new and delete are used. The
dynamic memory allocation and deallocations are handled through library functions such as
malloc, alloc, calloc and free routines.
The new operator performs the task of allocating memory dynamically at Run-time.
The delete operator is used to deallocate memory or free memory, i.e. memory management
can be provided with new and delete operator.
24  OOPs with C++ Programming

(f) Other operators:


 Parentheses for grouping expression:
The precedence and associativity of each operator determines whether it takes effect
before or after the next operator in an expression.
According to BODMAS rules the evaluation of expression is done.
When parentheses are put around an element of an expression, that element evaluates
before anything outside parentheses.
e.g. (a + b * c) * d
Hence first b is multiplied with c and result is added to a then that result is multiplied by
d.
 Membership operator:
These are C++ manipulator available.
Manipulators are operators that are used to format the data display. The most common
manipulators used are endl and setw.
1. endl operator causes a line feed to be inserted.
int m = 5, n = 6;
cout << “m =” << m<<endl;
cout << “n =” <<n<<endl;
m=5
n = 6.
2. setw operator specifies field width
cout << setw (5) << sum <<endl;
If sum = 45 then output is
bbb 45
b indicates black spaces.
setw will set the field width 5 for printing value of sum variable.

1.13 Preprocessor Directive


1. Preprocessor is a program that modifies the C++ program according to directives supplied in
the program.
2. C++ provides basically # include and # define preprocessors directives.
3. The following actions on the source file exist before it is presented to the compiler.
(a) Replacement of defined identifiers by pieces of the text with the help of # define
statement.
(b) Inclusion of other files they may user defined files or system library files.
like # include “sum.h”
includes user header file hence enclosed with quotes.
like # include <stdio.h> it includes header file from system library, hence enclosed within
angular (<>) brackets.
Introduction to OOPs and C++ with Variable and Operators  25

The general rules for defining a preprocessor are:


1. All preprocessor directive begin with the sharp sign (#)
2. They must start in the first column and no space is required between the number sign and the
directive.
3. The preprocessor directive should not be terminated by semicolon; sign.
4. Only one preprocessor directive can occur in a line.
5. Preprocessor is also called Macro Definition.
# define max 100
Hence # is a preprocessor directive which directs to the compiler that identifier max as a
token replaced with the string 100.
Hence in the program each occurance of max is automatically replaced by 100.
Examples:
# define true 1
# define false 0
# define EoF – 1
# define product (x, y) ((x) * (y))
# define max (x, y) ((x) > (y)?(x):(y))
# define begin {
# define end}
# define writeIn printf
# define mod %
# define program main
Syntax:
#define macro_name body of macro
#define Pi 3.1415
Here we are assigning a value of symbolic Pi value as 3.1415. This macro is also called inline
function where macro name can be replaced with body of macro in one line.
The body of macro may be any constant or expression.
These preprocessor statement will be defined or declared before program compiles. Hence
preprocessor replaces every occurrence of a macro name in the program text with a copy of the body
of the macro.

1.14 Declaration of Variables


1. Declaration of Variables: In C, all variables must be declared before they are used in
executable statements. In C language all variables are to be declared first in local declaration
section i.e. at the beginning of scope. But C++ allows the declaration of variable anywhere
in the scope. This means that a variable can be declared right at the place of its first use. It
makes the program easier to understand.
26  OOPs with C++ Programming

Variable is a place holder which occupies memory space to store variable value, or a
constant value, integer, float, character, string value.
The variable name follows following rules:
(a) The variable name should always start from any alphabet a – z.
(b) The variable name is combination of alphabets, numbers and underscores.
(c) The variable name can not start with digit.
(d) No special symbol other than underscore can be used in variable name.
Syntax of declaration of variable:
data_type variable name;
e.g., int x; double ratio;
int x,y; char c;
float avg; char x[10];
2. Dynamic Initialisation of Variables: C++ allows us to initialize the variable at Run time.
Initialisation of variables at run time is referred as dynamic initialisation.
int m = 10;
float area = 3.1415 *r *r;
Here both declaration and the initialisation of variable can be done simultaneously.
float avg = sum/3;
Initialises avg at Run time i.e. dynamic Initialization of avg.
3. Reference Variables:
(a) Reference variable provides an alias for a previously defined variable.
(b) It is called alternative name of original variable.
(c) Example: If we make the variable sum a reference to the variable total, then sum and
total can be used interchangebly to represent that variable.
(d) data type reference name = variable name
int sum = 100;
int & total = sum;
Here total is the alternative name declared to represent the variable sum.
(e) A reference variable must be initialized at the time of declaration.
(f) C++ assigns additional meaning to the symbol ‘&’. Here & is not an address operation. The
notation int & means reference to int.
Example,
void fun(int&x) // uses reference
{
x = x + 10;
}
int main ()
{
int n = 10;
Introduction to OOPs and C++ with Variable and Operators  27

fun (n);
return 0;
}
When the function call fun(n) is executed then value of actual parameter n is passed to formal or
reference parameter x i.e. if x is incremented n is also incremented. n refers the x value. Hence it is
called as call by reference.

1.15 Input and Output


1. Output operator
The cout statement is used as a output operator. The cout is used to display an object on standard
output device i.e. screen.
The statement
cout << “C++ is better”;
This statement causes the string in quotation to be displayed on the screen.
The cout is predefined object that represents the standard output stream in C++. Here the
standard output stream represents the screen. It is also possible to redirect the output to other output
devices.
The operator << is called the insertion or put to operator. It inserts (or sends) the contents of the
variable on its right of the object on its left.
It is similar to printf() function in C.
Screen

Cout << C++

object Insertion Operator Variable


or or
put to operator string

There are three different ways to use cout functions:


(a) cout<< message;
e.g., cout<<”hello”<<endl;
cout<<”welcome”;
output hello
welcome
(b) int a = 5;
cout<<a;
output 5
(c) int sum = 45;
cout<<”The sum is”<<sum;
The sum is 45
28  OOPs with C++ Programming

2. Input operator
The Cin statement is used as a input operator. In this Cin object is used to read number of
characters or stream of characters from standard input device. This input statement causes the program
to wait for the user to type in a number. The Cin is predefined object in C++ that corresponds to the
standard input stream.
This stream represents the keyboard. The operator >> is a extraction or get from operator. It
extracts or takes the value from the keyboard and assigns it to the variable on its right.
It is similar to scanf() function in C.
Extraction
operator Variable
Object
C in  45.5

Keyboard

int a;
cin>>a;
int a, b;
cin>>a>>b;

Question Bank for Self-Practice


1.
Explain the features of object oriented language.
2.
Describe reusability concept in OOPs by giving suitable example.
3.
What do you mean by dynamic binding? Explain difference between static and dynamic binding.
4.
What are main advantages of using object oriented programming?
5.
What is difference between function and member function of a class?
6.
Describe the structure of C++ program with iostream header files.
7.
What are different data types available in C++? Explain the difference between built in data types and
user defined data type.
8. Explain the use of scope resolution operator in C++.
9. What are the advantages of using new operator compared to malloc function?
10. Distinguish between following terms:
(a) C and C++.
(b) Data Abstraction and Data encapsulation.
(c) Inheritance and polymorphism.
(d) Objects and Classes.
(e) Dynamic binding and message passing.
(f) Structured and object oriented programming.


Control Structures
2 and Loops
Chapter

Chapter Outline
2.1 Introduction to Control Structures
2.2 Types of Control Structures
2.3 Selection Statements
2.4 Repetition (Loops)
2.5 GOTO Statement
2.6 Break Statement
2.7 Continue Statement

2.1 Introduction to Control Structures


Controlling the flow of a program is a very important aspect of programming. There may be
many different ways to find the solution to a particular problem, but you will want to look for the best
and fastest way.
The control statements contain one logical statement, which is usually a block of statements
enclosed in curly braces {}.
Indenting control structures is essential to making readable programs. There are several styles.
The style I use is the common industrial or K&R style. The opening curly brace is on the end of the
beginning statement. The idea is to avoid creating too much visual white space separating the parts of
the statement. Indentation is usually best with 4 spaces, altho 3 and 2 are also used.
True/false values are used in the if and loop statements. These are either the Boolean values true
and false, or any non-zero value for true and zero for false (as in C).
C++ has four types of control structures: sequential, selection (decision), repetition (loops), and
subprograms (functions). These structures simply control the execution of a program.
30  OOPs with C++ Programming

2.2 Types of Control Structures


C++ has four types of control structures:
1. Sequential.
2. Selection (decision).
3. Repetition (loops).
4. Subprograms (functions).
Sequential: Sequential means the program flow moves from one statement to the next, that
statement moves to the next, and so on. It is the simplest form of structures, and it is not likely to use
sequential structuring when developing complex programs.
Selection (decision): Selection structures make decisions and perform commands according to
the decision making. Selection structures involve “if statments” which are statements like “if this, then
do that” and “if not this, then do that”. With “if statements”, we can also include “nested if statements”,
which are “if statements” inside other “if statements”. Another form of selection structures is called a
“switch statement”, which is very powerful for certain situations but not others. “Switch statements”
focus on the value of a particular variable and perform different “cases” accordingly.
Repetition (Loops): Repetition structures are used when something needs to be repeated a
certain number of times through the use of “loops”. A loop is simply a statement that completes
iterations or cycles until a certain value is reached and then execution moves to the next executable
statement. For instance, if you were to ask the user to enter ten values to find the average of the
numbers, you could write a loop that would continue letting the user enter numbers until ten numbers
had been entered.
Subprograms (functions): A function is a subprogram that performs a specific task and may
return a value to the statement that called or invoked it. Functions make programming very powerful
because once you develop a function to handle a particular situation, you can use that function for
other programs. A function can call another function, which may call another function, and so on. It is
a great way to organize your program and break your program down into logical steps.
After a very brief intro to the different types of control structures, it’s time to move on and find
out how you can use each type. We will skip over sequential structures since they are pretty much self-
explanatory and elementary and move on to selection statements. Read on for more about selection
structures and “if statements”...

2.3 Selection Statements


Selection Statements: When dealing with selection statments, there are generally three versions:
one-way, two-way, and multi-way. One-way decision statements do some particular thing or they
don't. Two-way decision statements do one thing or do another. Multi-way decision statements can do
many different things depending on the value of an expression.
One-Way Decisions: One-way decisions are handled with an "if statement" and either do some
particular thing or do nothing at all. The decision is based on a logical expression which either
evaluates to true or false. If the logical expression is evaluated to true, then the corresponding
statement is executed; if the logical expression evaluates to false, control goes to the next executable
statement. The form of a one-way decision statement is as follows:
if (logical expression) stmtT;
Control Structures and Loops  31

The stmtT can be a simple or compound statement. Simple involves 1 single statement.
Compound involves 1 or more statements enclosed with curly braces { }. A compound statement is
called a block statement.
Example 1: Simple statement
int c = 3;
.
.
if ( c > 0 )
cout << "c = " << c << endl;
Example 2: Compound statement
int c = 10;
.
.
if ( c > 5 )
{
b = 2 * b + c;
cout << c * c * b << endl;
}
Two-Way Decisions: Two-way decisions are handled with “if / else statements” and either do
one particular thing or do another. Similar to one-way decisions, the decision is based on a logical
expression. If the expression is true, stmtT will be executed; if the expression is false, stmtF will be
executed. The form of a two-way decision is as follows:
if ( logical expresion )
stmtT;
else
stmtF;
stmtT and stmtF can be simple or compound statements. Remember that compound statments are
always enclosed with curly braces { }.
Multi-Way Decisions: Multi-way decision statements involve using “if/else if” statements,
“nested ifs”, or “switch” statments. They are all used to evaluate a logical expression that could have
several possible values. “if/else if” statements are often used to choose between ranges of values.
The form of a mult-way decision using “if / else if” statements is as follows:
if ( logical expression )
stmtT1;
else if ( logical expression )
stmtT2;
else if ( logcial expression )
stmtT3;
.
32  OOPs with C++ Programming

.
.
else if ( logical expression )
stmtTN;
else
stmtF;
If the first logical expression is evaluated to true, then stmtT1 is executed. If the second logical
expression is true, then stmtT2 is executed and so on down the line. If none of the logical expressions
are true, then the statement after “else” is executed which is stmtF.
The form of a multi-way decision using "nested ifs" is as follows:
if ( conditionA )
{
if ( conditionB )
stmtBT;
else
stmtBF;
}
else
stmtAF;
If conditionA is evaluated to true, then execution moves into the nested if and evaluates
conditionB. If conditionA is evaluated to false, then stmtAF is executed.
Example 1:
int x;
if ( x > 0 )
cout << "x is positive" << endl;
else if ( x = 0 )
cout << "x is zero" << endl;
else
cout << "x is negative" << endl;
Example 2:
char ch;
if ( ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' )
cout << "ch contains a letter" << endl;
else if ( ch >= '0' && ch <= '9' )
cout << "ch represents a digit" << endl;
else if ( ch == ' ' || ch == '\t' || ch == '\n' )
cout << "ch is white space" << endl;
else
cout << "ch is a misc. character" << endl;
Control Structures and Loops  33

Switch Statements: A switch statement is yet another option for writing code that deals with
multi-way decisions. I saved it for a section by itself because some programmers feel using a switch
statment is not good programming style. With 1 semester of programming under my belt and a few
years of fooling around with different programming languages, I haven't encountered any problems
with using a switch statement. I haven't written too many programs using switch statments, but when I
have, the programs have seemed to run smoothly. Maybe I'll see why programmers don't like to use
switch statements in later programming experiences. For now, let's explore the ins and outs of a switch
statement.
The following are the feature of a switch construct:
1. Expression must be integer expression.
2. Each case is labelled by integer or character constant.
3. Cases and default may occur in any order.
4. Cases must all be different.
5. After the code for one case is done, execution falls through to the next unless you take
explicit action to escape.
6. The break statement causes an immediate exit from the switch.
7. Falling through cases is a mixed blessing.
8. Positive side is to have one code for multiple cases, redundancy avoided.
9. Negative side is to put break after each case.
Switch statments offer an alternative to an "else if" structure which has multiple possible paths
based on the value of a single expression. A revised form for a switch statement is as follows:
switch (int expression)
{
case label - 1:
stmt-list-1;
break;
case label - 2:
stmt-list-2;
break;
case label - 3:
stmt-list-3;
break;
.
.
.
case label - n:
stmt-list-n;
break;
default:
stmt-list;
}
34  OOPs with C++ Programming

During execution, the expression is evaluated. If the value of the expression matches label - 1,
then stmt-list-1 will be executed. If not, execution will move on to check label - 2 and so on. If no
labels match the expression, default will be executed. Inside each case and at the end of every
statement list (except default) there must be a break statement, which terminates the innermost
enclosing switch or loop statement.
Here are some final notes about switch statements: the expression being tested must result in an
integral value (int or single char), case labels must be integral constants (either literals or
named constants), each label within a switch should be unique, and each stmt-list may contain 0
or more stmts which do not need to enclosed with curly braces { }.
Example:
Suppose a variable named score is an int variable that contains the number of points scored on a
football play. Consider the following code:
switch ( score )
{
case 1 : cout << "Extra Point" << endl;
break;
case 2 : cout << "Safety of two point conversion" << endl;
break;
case 3 : cout << "Field Goal" << endl;
break;
case 6 : cout << "Touchdown" << endl;
break;
default : cout << "Invalid score on a football play." << endl;
}
With selection statements out of the way, it's time to talk about iteration (or looping) in a
program. This, of course, involves using loop statements. Read on to explore the world of looping...
Syntaxes of Selection Statements
Selection (if, if –else)
if Statement
//----- if statement with a true clause
if (expression) {
statements // do these if expression is true
}
//----- if statement with true and false clause
if (expression) {
statements // do these if expression is true
} else {
statements // do these if expression is false
}
Control Structures and Loops  35

//----- if statements with many parallel tests


if (expression1) {
statements // do these if expression1 is true
} else if (expression2) {
statements // do these if expression2 is true
} else if (expression3) {
statements // do these if expression3 is true
...
} else {
statements // do these no expression was true
}
Example using Switch Case Construct:
#include<iostream.h>
#include<conio.h>
void main( )
{
int a, b, c, i;
clrscr( );
printf("1 : ADD\n");
printf("2 : SUB\n");
printf("3 : DIV\n");
printf("4 : MUL\n");
cout<<"Enter your choice”<<endl;
cin>>i;
printf("Enter the Two nos. in one line :\n");
fflush(stdin);
scanf("%d %d", &a, &b);
switch(i) { /* start of switch */
case 1:
c=a + b;
printf("The Addition of two nos is %d", c);
break;
case 2:
c=a-b;
printf("The subtraction of two nos is %d", c);
break;
case 3:
c=a/b;
36  OOPs with C++ Programming

printf("The Division of two nos is %d", c);


break;
case 4:
c=a*b;
printf("The Multiplication of two nos is %d", c);
break;
} /* end of switch */
getch( );
} /* end of main */

2.4 Repetition (Loops)


While Loops: A loop is a statement of code that does something over and over again until the
logical expression of the loop evaluates to false. It is simply a way of repeating code over and over
again until some particular value is reached. It can also be an effective way of making sure the user is
inputting the correct type of input (data validation).
A loop is different from an if statement in that if the logical expression is true, the stmt will be
executed and control will go back to check the logical expression again, ..., and again, until eventually
the logical expression becomes false.
One thing to avoid is writing code that produces an infinite loop, which is a loop that never stops
until you press ctrl-break on your keyboard. In order to avoid infinite loops, you need a statement(s)
inside the body of the loop that changes some part of the logical expression. We will talk about three
types of loops: while, do while, and for.
The form of a while loop is as follows:
while (logical expression)
stmt;
Example 1:
int x = 7;
while ( x > 0 )
{
cout << x << endl;
x--;
}
Example 2: Using data validation:
Suppose the user of a program is to input an integer in the range -10 to 10 (inclusive). Using data
validation, write a section of code to input this value:
int k;
k = -99;
while ( k < -10 || k > 10 )
{
Control Structures and Loops  37

cout << "Enter an integer value (between -10 and 10): ";
cin >> k;
}
Example 3:
Write a section of code that will display all multiples of 5 that are less than 500.
int x = 5;
while ( x < 500 )
{
cout << x << endl;
x = x + 5;
}
That wraps up all I have to say about while loops so let's move on to the next loop of interest.
Read on for more about do while loops...
Do While Loops: A do while loop is another type of repetition statement. It is exactly the same
as the while loop except it does something and then evaluates the logical expression of the loop to
determine what happens next. Normally with a while loop, a part of the logical expression in the loop
must be initialized before execution of the loop. A do while loop lets something be performed and then
checks the logical expression of the loop. I like to use a do while loop when using data validation
during a program. The form of a do while loop is as follows:
do
stmt(s);
while ( logical expression );
The stmt in the loop may be single or complex. Complex statements must be enclosed with curly
braces { }. Let's look at a couple of examples of do while loops.
Example 1:
int number;
do
{
cout <<"Enter a postive number greater than 0:";
cin >> number;
}
while ( number <= 0 || int(number) != number );
Example 2:
int number;
do
{
cout << "Enter a number between 0 and 100: ";
cin >> number;
}
while ( number <= 0 || number >= 100 );
38  OOPs with C++ Programming

Having discussed while and do while loops, there is one more loop I would like to cover: for
loops. Read on for more about for loops...
For Loops:
A for loop is another way to perform something that needs to be repeated in C++ (repetition).
Most programmers like to use for loops because the code can be written in a more compact manner
compared to the same loop written with a while or do while loop.. A for loop is generally used when
you know exactly how many times a section of code needs to be repeated. The general form of a for
loop is as follows:
for ( expression1; expression2; expression3 )
stmt(s);
where stmt(s) is a single or compound statment. Expression1 is used to initialize the loop;
expression2 is used to determine whether or not the loop will continue; expression3 is evaluated at the
end of each iteration or cycle.
Note 1: Expression2 is tested before the stmt and expression3 are executed; it is possible that the body of the loop is
never executed or tested.
Note 2: Any or all of the 3 expressions in a for loop can be omitted, but the 2 semi-colons must remain. If expression1
is omitted, there is no initialization done in the loop, but you might not need any initialization for your program.
If expression2 is omitted, there is no test section so you will essentially have an infinite loop. If expression3 is
omitted, there is no update as part of the for statement, but the update could be done as part of the statement in
the body of the loop.
In general, a for loop can be written as an equivalent while loop and vice versa.
for (expression1; expression2; expression3)
stmt;
is equivalent to...
expression1;
while (expression2)
{
stmt(s);
expression3;
}
Example 1: Write a for loop that will display all odd integers between 1 and 51:
for (int k = 1; k <= 51; k += 2)
cout << k << endl;
Example 2: Write a for loop that will display a "countdown" of integers from 20 to 1:
for (int k = 20; k >= 1; k--)
cout << k << endl;
Syntaxes of all loops:
Loop Statements
while Statement: do Statement:
The while statement tests an expression. If the expression This is the least used of the loop statements,
evaluates to true, it executes the body of the while. If it is false, but sometimes you want a loop that
Control Structures and Loops  39

execution continues with the statement after the while body. executes one time before testing.
Each time after the body is executed, execution starts with the do {
test again. This continues until the expression is false or some statements
other statement (break or return) stops the loop.
} while (testExpression);
while (testExpression) {
statements
}
for Statement: Other loop controls:
Many loop have an initialization before the loop, and some break; // exit innermost loop or switch
"increment" before the next loop. The for loop is the standard continue; // start next innermost loop
way of combining these parts. iteration
for (initialStmt; testExpr; incrementStmt) {
statements
}
This is the same as: Function Return:
initialStmt; return; //return no value from void function
while (testExpr) { return expr; //return value of expr from
statements function
incrementStmt
}

2.5 GOTO Statement


goto statement performs an unconditional transfer of control to the named label. The goto
identifier; label must be in the current function.
A statement label is meaningful only to a goto statement; in any other context, a labeled
statement is executed without regard to the label.
A jump-statement must reside in the same function and can appear before only one statement in
the same function. The set of identifier names following a goto has its own name space so the names
do not interfere with other identifiers. Labels cannot be redeclared.
It is good programming style to use the break, continue, and return statement in preference to
goto whenever possible. Since the break statement only exits from one level of the loop, a goto may
be necessary for exiting a loop from within a deeply nested loop.
Example 1: In this example, a goto statement transfers control to the point labeled stop when i
equals 3.
// goto_statement.cpp
#include <stdio.h>
int main()
{
int i, j;
for (i = 0; i < 10; i++)
{
printf_s("Outer loop executing. i = %d\n", i);
40  OOPs with C++ Programming

for (j = 0; j < 2; j++)


{
printf_s(" Inner loop executing. j = %d\n", j );
if (i == 3)
goto stop;
}
}
// This message does not print:
printf_s("Loop exited. i = %d\n", i);
stop:
printf_s("Jumped to stop. i = %d\n", i);
}
Output:
Outer loop executing. i = 0
Inner loop executing. j = 0
Inner loop executing. j = 1
Outer loop executing. i = 1
Inner loop executing. j = 0
Inner loop executing. j = 1
Outer loop executing. i = 2
Inner loop executing. j = 0
Inner loop executing. j = 1
Outer loop executing. i = 3
Inner loop executing. j = 0
Jumped to stop. i = 3

2.6 Break Statement


The break Statement: We have seen one use of the break statement in a switch statement. In
addition to this, the break statement can also be used to terminate loops or to exit from a switch. It can
be used within a while a do – while, a for or a switch statement.
Example: While((c=getchar( ))!= EOF)
{
putchar(c);
i++;
if(i>20)
break;
}
Control Structures and Loops  41

2.7 Continue Statement


Continue Statement: The continue allows you to continue the execution of a for or while loop
from the beginning, making it possible to skip the rest of the statement in the loop after the continue
statement.
Example:
#include <stdio.h>
main( )
{
static int marks[5] = {90,80,76,89, -90};
int i, total = 0;
for(i=0; i<5; i++)
{
if(marks[i] <0)
{
ptrint(“negative marks not added \n”);
continue;
}
total += marks[i]
}
printf(“total marks = %d \n”, total);
}

Question Bank for Self-Practice


1. Explain what are different control structures are available in c++
2. Explain the Syntax of if, if –else statement with suitable example.
3. Explain Different Loops used in c++ with suitable example.
4. Explain difference between for loop & while loop. In which of the application for loop is advisable & in
which applications while loop is advisable. State the reason.
5. Explain use of switch statement compare switch statement with if statement & state the advantages of
switch statement.
6. Explain use of break statement, discuss in which control structures the break statement is used explain
with example.
7. Explain GOTO statement, discuss how the control can be transferred to any statement.
8. Explain Use of Break & Continue statements. State the use of these statements where they can be used.


3 Functions in C++

Chapter

Chapter Outline
3.1 Introduction to Functions
3.2 Call by Value and Call by Reference
3.3 Function Overloading
3.4 Inline Function
3.5 Functions with Default Arguments

3.1 Introduction to Functions


Functions are set of block of statement to avoid repetition task.
Dividing program into functions is the major principle of top-down structured programming. It
also reduces the size of the program when function is called many times or can be called at different
places.
When function is called following steps will be executed.
1. When function is called, control is transferred to the first statement in the function body.
2. While switching to function body it will check the prototype of function and function header
statement if it matches then control is transferred to function definition.
3. While transferring the control actual parameters values are transferred to format parameters.
4. Function definition is executed and result is returned back to function calling statement.
5. Result can be displayed in the main function where function is called.
Functions are divided into three parts
(a) Function Declaration.
(b) Function Call.
(c) Function Definition.
Functions in C++  43

(a) Function Declaration:


(a) This section is to be written in a local declaration section or in a global declaration section.
(b) It is a single statement terminated by; sign.
(c) The syntax of prototype statement is
Return type function name (No. of parameters);
Example  int one space sum(int a, int b);
(d) Function prototype statement has different formal parameters.

(b) Function Call:


(a) It is a single statement is to be written within a main function with Actual parameters.
(b) The syntax of function call statement is
Return variable = function name (parameters);
s = sum(x, y);

(c) Function Definition:


(a) Function Definition is a body of the function written outside the main function.
(b) The function Definition has function header statement with body of statements enclosed
within {and}
The Syntax of function definition is:
Return type function name (no. of parameters)
{
stmt;
stmt;
return stmt;
}
(a) Example:
int sum (int a, int b)
{
int c;
c = a + b;
return c;
}
(b) Example:
void even (int a)
{
if (a%2 = = 0)
cout << a << “is even”;
else
cout << a << “is odd”;
}
44  OOPs with C++ Programming

3.1.1 Examples of Functions


1. Write a program to print sum of two numbers using functions.
void main( )
{
int sum (int a, int b); ‘function declaration
int x, y, s;
cout << “enter value of x & Y” <<endl;
cin>>x>>y;
s=sum (x, y); ‘function call
cout<< “The sum of & Nos is” <<s;
getch( );
}
int sum (int a, int b)
{
int c; ‘function definition
c=a + b;
return c;
}
2. Write a program to print area and circumference of circle using function.
void main( )
{
void area (int r); ‘function declaration
int radius; ‘variable declaration
cout <<”enter radius” <<endl;
cin>> radius;
area (radius); ‘functionCall
getch( );
}
void area (int r) ‘function definition
{
float pi=3.1415, a, c; ‘local variables declaration
a=pi*r*r;
c=2*pi*r;
cout<<“The area is”<<a<<endl;
cout<<“The circuference is”<<c;
}
3. Write a program to print number is even or odd.
void main( )
{
void even (int n); ‘function declaration
int x;
Functions in C++  45

cout<< “enter a no” <<endl;


cin>>x;
even(x); ‘functionCall
getch( );
}
void even (int n)
{
if(n%2 = = 0) ‘function definition
cout<<n<< “is even”;
else
cout<<n<< “is odd”;
}
4. Write a program to print factorial of a number using function.
void main( )
{
long factorial (int n); ‘function Qedaration
int x;
long f;
cout<< “enter a number” <<endl;
cin>> x;
f=factorial (x); ‘functionCall
cout<< “factorial of a no is” <<f;
getch( );
}
long factorial (int n) ‘function definition
{
long fact = 1;
for (int i=1; i < = n; i++)
{
fact=fact*i;
}
return fact;
}
5. Write a program to print natural numbers from 1 to n through function.
void main( )
{
void natural (int n); ‘function declaration
int x;
cout<< “enter number” <<endl;
46  OOPs with C++ Programming

cin>>x;
natural (x); ‘function Call
getch( );
}
void natural (int n)
{ ‘function definition
for(int i=1; i<=n; i++)
{
cout<<i;
}
}
6. Write a program to print natural numbers from lower limit and upper limit through function.
void main( )
{
void natural (int l, int u); ‘function declaration
int l1, u1;
cout<< “enter lower limit & upper limit of natural numbers” <<endl;
cin>>l1>>u1;
natural (l1, u1); ‘function Call
getch( );
}
void natural (int l, int u)
{
for(int i=l; i<=u; i++) ‘function definition
{
cout<<i;
}
}
7. Write a program to print whether number is prime or not using function.
void main( )
{
void prime (int n); ‘function declaration
int x;
cout<< “enter a no”;
cin>> x;
prime (x); ‘function Call
getch( );
}
Functions in C++  47

void prime (int n)


{ ‘function definition
int p=1;
for (int i=2; i<=n–1; i++)
{
if(n%i==0)
{
p=o;
break;
}
}
if (p==1)
cout<<n<< “is prime no”;
else
cout <<n<< “is not a prime no”;
}

3.2 Call by value and Call by Reference


Call by value and call by reference function parameters can be passed by two ways:
(a) Call by value.
(b) Call by Reference.
(a) Call by value: Function call has number of different parameters, these parameters value is
passed to formal parameters hence value of actual parameters passed to formal parameters is are called
call by value. In this function call passes arguments by value. The called function creates a new set of
variables.
Function prototype statement is:
int sum (int a, int b);
OR int sum (int, int);
Function call statement is:
s = sum (x, y);
Function definition is:
int sum (int a, int b)
{
int c;
c=a + b;
return c;
}
(b) Call by reference: In this function, declaration and definition parameters are passed by
reference.
48  OOPs with C++ Programming

In this formal parameters of function definition become aliases to the actual arguments in the
calling function.
Function declaration:
int sum (int * a; int * b);
Function call:
s = sum (& x, & y);
Function definition:
int sum (int * a, int * b)
{
int t;
t = * a + * b;
return t;
}

3.3 Function Overloading


The overloading refers to have the same function for performing variety of different tasks. This is
also known as function polymorphism in OOP’s.
The function overloading is a logical method of calling several functions with different
arguments and data type that perform basically the same function.
During function overloading compiler checks following things.
1. It checks exact match of function name when it is invoked in a function call.
2. After name is matched it will check total number of arguments.
3. After total number of arguments match it will check data types of arguments.
4. It all 3 points matches then function definition will be executed.
Advantages of function overloading:
1. It eliminates the use of different function names for the same operation.
2. It helps to understand debug and grasp easily.
3. Easy maintainability of the code.

3.3.1 Examples using function overloading


1. Write a program to print sum of 2 integers and sum of three float numbers using common
sum function with function overloading.
void main( )
{
int a, b, s;
float fa, fb, fc, fs; ‘Variable declaration
int sum (int x, int y); ‘function declaration
float sum (float f1, float f2, float f3); ‘overloaded function declaration
Functions in C++  49

cout<< “enter two integer numbers”;


cin >>a>> b;
s=sum (a, b);
cout << “enter three float numbers”;
cin>>fa>>fb>>fc;
fs=sum(fa, fb, fc); ‘function Call
cout<< “The sum of two integers is” <<s<<endl;
cout<< “The sum of three float numbers is” <<fs;
getch( );
}
int sum(int x, int y)
{ ‘function definition
return (x + y);
}
float sum (float f1, float f2, float f3)
{ ‘function definition
return (f1 + f2 + f3);
}
2. Write a program to interchange the value of 2 integers, 2 floats and 2 characters using swap
common function using function overloading.
void main( )
{
int x, y;
float fx, fy; ‘variable declaration
char cx, cy;
void swap(int a, int b)
void swap(float f1, float f2) ‘function declaration
void swap(char c1, Char c2)
cout<< “enter two integers”<<endl;
cin>>x>>y;
swap(x, y); ‘function Call
cout<< “enter two float numbers”<<endl;
cin>>fx>>fy;
swap(fx, fy); ‘function Call
cout<< “enter two characters”<<endl;
cin>>cx>>cy;
swap ((x, (y);
getch();
50  OOPs with C++ Programming

}
void swap (int a, int b)
{
int temp;
temp=a; ‘function definition
a=b;
b=temp;
cout<<“a=”<<a<<endl;
cout<<“b=”<<b;
}
void swap (float f1, float f2)
{
float temp;
temp=f1; ‘function definition
f1=f2;
f2=temp;
cout<<“f1=”<<f1<<endl;
cout<<“f2=”<<f2;
}
void swap (char c1, char c2)
{
char temp; ‘function defintion
temp=c1;
c1 = c2;
c2=temp;
cout<<“c1=”<<c1<<endl;
cout<<“c2=”<<c2;
}
3. Write a program to print area of circle and area of rectangle using area function with
function overloading.
void main( )
{
int radius, length; breath, arect; ‘variable declaration
float acir;
float area(int r)
‘function declaration
void swap(int l, int b)
cout<<“enter radius”<<endl;
cin>> radius;
Functions in C++  51

acir=area (radius); ‘function Call


cout<<“enter length & breath”<< endl;
cin>>length>>breath;
arect=area(length, breath);
cout<<“The area of circle is”<<acir<<endl;
cout<<“The area of rectangle is”<<arect;
getch( );
}
float area (int r)
{ ‘function defintion
return (3.1415 * r * r);
}
int area (int l, int b)
{ ‘function definition
return (l * b);
}

3.4 Inline Function


Inline functions are also called Macros Main Object of using function is to save the memory
space, when function is called.
When function is called then function name, parameters type, Number of parameters is checked if
all thing matches then control is transferred to function and dynamic binding is provided. Then
function definition is executed and answers is returned back to calling statement. To avoid these series
of steps macros are used.
Macros are the inline function which replaces the function definition statement with function call
statement. Compiler just replaces this statement and execute the statement.
While writing the inline functions we need prefix keyword as “inline” to the function definition.
If function contains more than three lines then inline function is not advisable.
Inline function does not contain any looping statement or conditional statement because it does
not provide error-trapping, switch-case or goto statement does not exist. They can be recursive.
Advantage of using inline function:
1. The size of object code is reduced.
2. It increases the execution speed.
3. To avoid the control to be transferred back to the main function.
inline returntype functionname (list of parameters)
{
function statement;
}
52  OOPs with C++ Programming

Example:
inline int sum (int a, int b)
{
return (a+b);
}
4. Write a program to print sum of 2 numbers using inline function.
inline int sum (int x, int y), Inline function definition
{
return (x + y);
}
void main( )
{
int a, b, s; ‘variable declaration
cout<<“enter value of a&b”<<endl;
cin>>a>>b;
s=sum (a, b); ‘function Call
cout<<“The sum of 2 Nos is”<<s;
getch( );
}
5. Write a program to print area of circle using inline function.
inline float area (int r)
{
return (3.1415 * r * r); ‘Inline function definition
}
void main( )
{
int radius;
float acir; ‘variable declaration
cout<<“enter radius”<<endl;
cin>>radius;
acir=area(radius); ‘function Call
cout<< “The area of circle is”<<acir;
getch( );
}

3.5 Functions with Default Arguments


1. C++ provides facility to assign default value to the parameter.
2. The default values are specified in the function prototype statements.
Functions in C++  53

3. Whenever the function call is made without specifying the arguments the compiler checks in
the function prototype statement, how many number of arguments are there, hence after
matching the arguments it will automatically assign the values from the default function
prototype declaration.
4. A default argument is checked for type at the time of declaration and evaluated at the time of
call.
5. The default parameters is to be given from the trailing edge to leading edge i.e. from Right to
Left.
6. We cannot provide a default value to a particular argument in the middle of an argument list.
7. We cannot provide a default value from left to right.
8. More than one parameter can have default values.
9. All the parameters of the function can have default values.
10. Some examples of function declaration with default values are:
int sum(int i, int j=5, int k=12); // valid
int sum(int a=5, int b); // notvalid (invalid)
int sum (int x, int y=6, int z); //Invalid
int sum (int x=6, int y=7, int z=8); //valid
11. Default values are not be provided in the function definition.

3.5.1 Examples Using Default Arguments


1. Write a program to print sum of 3 numbers, by giving 2 parameters as default values.
void main( )
{
int sum(int a, int b=5, int c=6); ‘function declaration with default values
int x, s;
cout<<“enter a value of x”<<endl;
cin>>x;
s=sum(x); ‘function Call
cout<<“The sum is”<<s;
getch( );
}
int sum(int a, int b, int c)
{ ‘function definition
int z;
z=a+b+c;
return z;
}
54  OOPs with C++ Programming

2. Write a program to print simple interest where rate of interest should be default value.
void main( )
{
float interest(int p, int n, int r=10); ‘function declaration with default values
int pr, nyears;
float si;
cout<<“enter principle amount and number of years” <<endl;
cin>>pr>>nyears;
si=interest (pr, nyears); ‘function Call
cout<<“The simple interest is”<<si;
getch( );
}
float interest (int p, int n, int r)
{
float s; ‘function definition
s= p* n* r/100.0
return s;
}
3. Write a program to print factorial of a number where number should be default value.
void main( )
{ long factorial (int n=5); ‘function declaration with default value
int x;
long f;
f=factorial ( ); ‘function Call
cout<<“The factorial of a no is”<< f;
getch( );
}
long factorial (int n)
{ ‘function definition
long fact = 1;
for (int i=1; i<=n; i++)
{
fact=fact*i;
}
return fact;
}
Functions in C++  55

Question Bank for Self-Practice


1. Explain functions with call by value and call by reference.
2. What are the advantages of function prototype in c++?
3. What is the main advantage of passing arguments by reference? What are the different Rules are
followed for assigning default values?
4. What is inline function? How to define inline functions?
5. What do you meant by overloading of a function? When do we use this concept and what are the
advantages of using function overloading?
6. What is difference between function declaration and function definition? What is difference between
actual parameters and formal parameters? Explain with example.


4 Classes and Objects

Chapter

Chapter Outline
4.1 Structures of C Language
4.2 Structures and Classes
4.3 Specifying (Defining) a Class
4.4 Defining Member Functions
4.5 Examples of C++ Programs with Class
4.6 Making an Outside Function (Inline)
4.7 Nesting of Member Functions
4.8 Private Member Functions
4.9 Array within a Class
4.10 Static Data Members
4.11 Static Member Functions

4.1 Structures of c Language


One of the key feature of C language is structures. They are collection of different data types.
They provide a method of encapsulating different types of data in one unit. A structure is a very
convenient tool for handling a group of logically related data items. Structure is a user defined data
types with a template that serves to define its data properties. Once structure type is defined then we
can create variables of that type using declarations that are similar to the built-in-type declarations.
Example:
Struct employee
{
int empno;
char ename [10];
Classes and Objects  57

float salary;
};
struct employee e;
E is instance variable of type student three member variable are defined by the template. Member
variables can be accessed using the dot or period operator.
Example:
[Link]=10
[Link]=”Kiran”
[Link]=16000
Limitations of Structures:
1. By default members of structures are public hence they do not permit data hiding.
2. Structure does not support inheritance.
3. Member functions can not be encapsulated in a structure.
4. In structures, the instance of the structures can not be added or subtracted.
5. To overcome limitations of the structure class is invented in C++.
6. Structure data type is not treated as built-in data type.

4.2 Structures and Classes


Difference between structures and class in C++.
Structure in C Class in C++
1. Structure is a encapsulated unit of different 1. Class is a encapsulated unit of different data
data type variables. type variables (data members) and member
functions.
2. Structures by default are value types. 2. Classes by default are of reference types.
3. Structure does not support inheritance. 3. Classes supports inheritance.
4. In structure we can not declare default or 4. In class we can declare default constructor and
parameterised constructor. parameterised constructor.
5. Structures are created by using Struct 5. Class can be created by Class Keyword.
Keyword.
6. In the structures we can not use the classes. 6. In classes we can declare a structure.
7. In structures we can not specify members as 7. In class we can provide data hiding by
private, public and protected. Hence they do specifying the scope as private, public and
not permit data hiding. protected.
8. Example of structure declaration: 8. Example of class Declaration:
Struct Student {Private:
{ int rollno;
int rollno; char name[10];
char name [10]; Public:
}s; void getdata();
9. Struct Complex 9. In this we can create object of class like
{ C1,C2,C3.
58  OOPs with C++ Programming

float x; We can add the object or subtract the objects by


float y; using operator overloading concept.
};
Struct Complex C1,C2,C3;
Values can be assigned to C1,C2,C3 but we can
not add two complex number or subtract one
form other.
i.e. C3 = C1 + C2 (not valid)
10. By default members of structure are public. 10. By default members of class are private.

4.3 Specifying (Defining) a Class


1. A class is a predefined blank template which can be reused number of times.
2. A class is a way to bind the data and its associated functions encapsulated in one unit.
3. It allows the data hiding of data and its functions.
4. When defining a class, we are creating a new abstract data type, that can be treated like any
other built-in-data type.
5. A class can be reused many number of times by crating object of it.
6. Objects contains data encode to manipulate the data and the class contain different data
members and member functions.
7. Wrapping of data and functions in one unit is called class.
8. Class specification has two parts:
(a) Class declaration.
(b) Class function definition.
(a) Class declaration
Syntax:
Class class-name
{
Private:
variable declarations;
function declarations;
Public:
variable declarations;
function declarations;
};
Class declaration is similar to the structure declaration. The keyword class specifies that what
follows is an abstract data of type class-name.
The body of a class is enclosed within braces and terminated by a semicolon. The class body
contains the declaration of variables and functions.
These variables and functions are collectively called class members.
These variables and functions are grouped under two sections:
Classes and Objects  59

(i) Private (ii) Public if needed then protected.


The private and public are known as Scope Specifier or Visibility labels OR Access Specifiers.
These two visibility modes are followed by colon sign (:).
The class members which are declared as private can be accessed only from within the class.
Public members can be accessed from outside the class also.
The no visibility mode is defined within a class, then all class members are by default private.
Such a class is completely hidden form outside world.
The variables declared inside the class are known as data members. They are used to serve the
data being a member of a class. Functions declared inside the class are called member functions. They
are used to perform specific function or task being a member of a class.

Private area
Data
entry is no t
allow ed M em bers

Public area
Data
entry is
allow ed M em bers

Example:
Class Item
{
Private:
int productid;
float price;
void stock();
Public:
float amount;
void getitem();
void calculate();
void display();
};
In this data member’s productid and price can be accessed by stock, getitem, calculate and
display member functions.
60  OOPs with C++ Programming

i.e., private data members can be accessed by private member functions and public member
functions of a class and data member amount in public can be used outside the class.
i.e., public data members can be used by member functions of a class as well as functions outside
the class.
Creating Objects
Object is a instance variable or class variable. Once the class has been declared, we can create
object of the class i.e. we can create variables of that type by using the class name.
Example:
item x;
item is a class, x is the object or instance of type item x is a variable of class type we can declare
more than one object of a class.
item x, y, z;
This statement create three objects x, y, z. The necessary memory space is allocated to an object.
Accessing Class Members
1. Private data of the class can not be accessed outside the class. It can be accessed only by the
member functions of that class.
2. The public variable and public member functions can be accessed outside the class by
referring [Link](list of arguments);
[Link]();
obj is the object & getdata() is the member function accessed with the help of object. If
member function is parameterised then while calling parameters are to be passed.
Example:
[Link](2,3,5);
obj is the object, calculate is a member function. 2,3,5 are the value of the arguments of the
function.
3. If x is private data member & to access in main function if you have written.
obj.x=10; // It is not allowed
It gives error because private data members cannot be accessed outside the class.
If it is public data member then it can be accessed outside the class.
It x is public variable then we can write.
obj.x=100;
Hence x is assigned as 100.

4.4 Defining Member Functions


Member functions of a class can be defined outside the class as well as they can be defined inside
the class.
Hence definition of a class is of two types.
1. Outside the class definition
2. Inside the class definition
Classes and Objects  61

Outside the Class Definition


Member functions that are declared inside the class, they have to be defined outside the class.
The definition outside the class is same as normal member. Only it is prefixed by classname followed
by :: (scope resolution operator).
classname which is used before the member functions, specifies to the compiler that this member
function belongs to specific class.
Syntax is
return-type class-name :: functionname
(arguments list)
{
function body
}
return type is any data type of the member function like int, float, char which indicates that the
function return the result of specified data type.
classname is the name of the class of which member function is to be defined.
:: Scope Resolution Operator.
It is to be written in the function header statement.
The classname :: tells the compiler that function-name belongs to the classname specified.
class item
{
private:
int productid;
float price;
void stock();
public:
float amount;
void getitem(int pid, float p);
void calculate();
void display()
{
cout<<”The amount is”<<amount;
}
};
void item :: getitem(in pid, float p)
{
productid=pid;
price=p;
}
62  OOPs with C++ Programming

void item :: calculate()


{
amount=price*4;
}
The member function have following special characteristics.
1. Several different classes can use the same function name. The classname with :: (scope
resolution operator) will resolve their scope.
2. Member function can access the private data of the class. A non member function cannot
access the private data members of the class as well as it can not be accessed outside the
class.
3. A member function can call another member function directly without using dot operator. i.e.
one function can be used with another member function hence called Nesting of Member
functions.
Inside the class definition:
The member function can be defined within a class. Hence declaration is replaced by the function
definition.
class item
{
int pid;
float price;
public:
void getdata(int a, float b)
{
pid=a;
price=b;
}
void putdata()
{
cout<<”The productid is”<<pid;
cout<<”The price is”<<price;
}
};

4.5 A C++ Programs with Class


Example 1: Write a program to create a class student having private data members Rollno, name
and marks of due student.
Declare getdata member function to accept student details from the user.
Provide putdata member function to display all details of the student.
# include <iostream.h>
# include <conio.h>
Classes and Objects  63

class student
{
private:
int rollno, marks;
char name [10];
public:
void getdata()
{
cout<<”enter rollno, name & marks of the student” << endl;
(in>> rollno>>name>>marks;
}
void putdata()
{
cout<< “The Rollno is” << rollno <<endl;
cout<< “The name is” << name <<endl;
cout<< “The marks is” <<marks;
}
};
void main()
{
student s;
[Link]();
[Link]();
getch();
}
Example 2: Write a program in C++ to create a class Bank having private data members Accno
for Accountno, balance amt, initial deposit amount.
Provide getdata member function to accept account and initial deposit amount from the user and
make this initial deposit amount as balance.
Provide deposit member function to deposit the amount and according update the balance.
Provide withdraw member function to allow the user to withdraw amount, while withdrawing we
have to check the withdraw amount should be less than balance amount. If it is so allow the user to
withdraw amount and update the Balance else provide message to the user accordingly.
Provide display member function to display account no and balance amount.
# include <iostream.h>
# include <conio.h>
class bank
{
private:
64  OOPs with C++ Programming

int accno, depositamt, balance;


public:
void getdata()
{
cout<<”enter account no & initial deposit amount” <<endl;
cin>>accno>>depositamt;
balance = depositamt;
}
void deposit()
{
int amount;
cout<< “enter the amount to be deposited” << endl;
cin>> amount;
balance = balance + amount;
}
void withdraw()
{
int amount;
cout<< “enter amount to be withdrawn” <<endl;
cin>> amount;
if (amount > balance)
{
cout <<”sorry! balance amount is not available” <<endl;
}
else
{
balance = balance – withdraw;
}
}
void display()
{
cout<<”Accno is” <<accno<<endl;
cout<<”Balance amount is” <<balance;
}
};
void main()
{
bank obj;
[Link]();
Classes and Objects  65

[Link]();
[Link]();
[Link]();
getch();
}
Example 3: Write a program in C++ print greatest of three numbers by accept 3 numbers
through getdata and print greatest number through calculate member function.
# include <iostream.h>
# include <conio.h>
Class greatest
{
private:
int a, b, c;
public;
void getdata()
{
cout<<”enter three number “<<endl; cin>>a>>b>>c;
}
void calculate()
{
if (a > b && a > c)
{
cout<<a<< “is greater”;
}
if (b > a && b > c)
{
cout<< b << “is greater”;
}
if (c > a && c > b)
{
cout <<c << “is greater”;
}
}
}
void main()
{
greatest g;
[Link]();
[Link]();
getch();
}
66  OOPs with C++ Programming

Example 4: Write a program in C++ to print factorial of a number, Accept number through
getdata member function, calculate factorial through calculate member function and display factorial
through display member function.
Class factorial
{
private:
int n, fact;
public:
void getdata()
{
count<< “enter a number “<< end; Cin>> n;
}
void calculate()
{
fact = 1;
for (int i = 1; i< = n; i++)
{
fact=fact *i;
}
}
void display()
{
cout<< “the factorial of “<<n <<” is” << fact;
};
void main()
{
factorial f;
[Link]();
[Link]();
[Link]();
getch();
}
Example 5: Program to accept product id, Quantity and price of product through parameterised
getdata member function, calculate total amount through calculate member function and display all
detail through display member function.
# include<iostream.h>
# include<conio.h>
class product
{
private:
int pid, quantity;
Classes and Objects  67

float price, amount;


public:
void getdata(intp, int q, float pr)
{
pid=p;
Quantity = q;
price = pr;
}
void calculate()
{
amount=price*Quantity;
}
void display(); /* definition of display member function outside the class*/
};
void product :: display ()
{
cout<< “The product id”<<pid<<endl;
cout<<”The price is”<<price<<endl;
cout<<”The Quantity is”<<Quantity<<endl;
cout<<”The amount is”<<amount;
}
void main()
{
product obj; /creating object of a class*//*
calling parametrized member function */
[Link](100,55,5000);
[Link]();
[Link]();
getch();
}
Example 6: Write a program to print mean value of two numbers through parameterised member
function.
class mean
{
int x,y;
float m;
Public:
void getdata(int a, int b) /*defining parameterised getdata member function */
{
68  OOPs with C++ Programming

x=a;
y=b;
}
void calculate()
{
m=(a+b)/2.0;
}
void display()
{
cout<<”The mean value is”<<m;
}
};
void main()
{
mean m;
[Link](2,5);
[Link]();
[Link]();
getch();
}
Example 7: Write a program to calculate factorial of a number, through parameterised member
function.
class factorial
{
Private:
int n, fact;
Public:
void getdata(int x)
{
n=x;
}
void calculate();
void display()
{
cout<<”The factorial of”
<<n<<”is”<<fact;
}
};
void factorial :: calculate()
Classes and Objects  69

{
fact=1;
for(int i=1; K=n; i++)
{
fact=fact * i;
}
}
void main()
{
factorial f;
[Link](5);
[Link]();
[Link]();
getch();
}

4.6 Making an Outside Function (Inline)


1. Member functions of the class should be inline functions i.e., they should not contain for
loop, while loop, switch case.
2. The functions which are not inline contains any looping statement is not to be defined within
a class. It is declared within a class & definition is kept outside the class.
3. Inline functions can also be defined outside the class by using keyword inline.
class item
{
private:
int pid;
float price;
public:
void getdata(int p, float pr);
};
inline void item :: getdata(int p, float pr)
{
pid=p;
price=pr;
}
70  OOPs with C++ Programming

4.7 Nesting of Member Functions


1. When member function can be called by another member function inside it, is called Nesting
of member function.
2. One member function is used within another member function of the same class.
3. Nested member function should have Return type.
4. The function which is nested is not to be called in main function.
Example 8:
class largest
{
Private:
int a,b;
Public:
void getdata(int x, int y)
{
a=x;
b=y;
}
int great()
{
if(a>b)
return a;
else
return b;
}
void display()
{
cout<<”The greatest no is”<<great();
}
};
void main()
{ largetst l;
[Link](5,8);
[Link]();
getch();
}
Classes and Objects  71

4.8 Private Member Functions


Normally we are placing data items in private section and all the functions in public but in some
situations if we need to hide the functions, then functions also can be placed in private like deleting an
employee number or making increment in a salary. To provide restriction on these functions, we can
make them in private.
A private member function cannot be called outside the class. It can be called by another function
within a class.
Example 9:
class student
{
Private:
int rollno;
char name[20];
void getdata()
{
cout<<”enter rollno, name”<<endl;
cin>>rollno>>name;
}
Public:
void display()
{ getdata();
cout<<”The rollno is”<<rollno<<endl;
cout<<”The name is”<<name;
}
};
void main()
{
student s;
[Link](); // we cannot call this function
because It is in private
[Link]();
getch();
}
We cannot call getdata() function with the help of object also but we can call display() function
because it is in public. Within display() function we can call getdata() function.
72  OOPs with C++ Programming

4.9 Array within a Class


Data members used within a class can be array variable. This array data member can be integer or
it can be character array.
The size of array can be declared through constant variable or it can be declared directly while
declaring array.
Example 10:
const int size=10; //provides value for array size
class student
{
int a[size]; //a is integer type array
char name[10]; //name is character type array
Public:
void getdata();
void display();
};
void student :: getdata()
{
for (int i=0; i<size; i++)
{
cout<<”enter value of a”;
cin>>a[i];
cout<<”enter name”;
cin>>name[i];
}
}
void student :: display()
{
for(int i=0; i<size; i++)
{
cout<<”The a value is” <<a[i];
cout<<”The name is”<<name[i];
}
}
void main()
{
student s;
[Link]();
[Link]();
getch();
}
Classes and Objects  73

Memory Allocation for Objects:


The Member functions are created and placed in memory space only once when they are defined
as a part of class specification. Since all the objects belonging to that class use the same member
function, non separate space is allocated for member functions when the objects are created. Only
space for member variables is allocated separately for each object. Separate memory locations for the
objects are essential, because member variables will hold different data values for different objects.

4.10 Static Data Members


1. A data member of a class can be qualified as static.
A static member variable has certain special characteristics are:
(a) It is initialised to zero when the first object of its class is created. No other initialisation is
permitted.
(b) It is visible inside the class. Scope is within the class but static existence is lifetime in the
entire program.
(c) Only one copy of that member is created for the entire class. One copy can be shared by
multiple objects.
2. Static variable is common for entire class. It is used to count how many objects are created.
3. Static variable count is initialised to zero when objects are created.
#include<iostream.h>
class item
{
static in count;
int number;
public:
void getdata(int a)
{
number=a;
count++;
}
void getcount()
{
count<<”count:”<<count<<endl;
}
};
void main()
{
item a,b,c;
[Link]();
[Link]();
[Link]();
74  OOPs with C++ Programming

[Link](100);
[Link](200);
[Link](300);
cout<<”After reading data”;
[Link]();
[Link]();
[Link]();
getch();
}

4.11 Static Member Functions


1. A static function can have access to only one static member of that class.
2. Static member functions are prefixed by the keyword static.
3. Static member function can not be called with object reference. They are to be called with
class name followed by :: (scope resolution operator)
Example 11:
#include<iostream.h>
class test
{
int code;
static int count;
public:
void getdata()
{
code=++count;
}
void display()
{
cout<<”object no”<<code;
}
static void showcount()
{
cout<<”count=”<<count;
}
}
int test :: count;
void main()
{
Classes and Objects  75

test t1, t2, t3;


[Link]();
[Link]();
[Link]();
test::showcount();
[Link]();
[Link]();
[Link]();
getch();
}

Question Bank for Self-Practice


1. Explain difference between structure of C and C++.
2. Explain difference between structure and classes.
3. Explain how to define a class. What are two different methods of declaring member functions of a class?
4. Explain how the Nesting of functions can be implemented.
5. Explain use of static data members and member functions.
6. What are objects? How they are created?


Arrays, Pointers
5 and References
Chapter

Chapter Outline
5.1 Arrays of Objects
5.2 Objects as Function Arguments
5.3 Friend Function or Friendly Function
5.4 Common Friend Function Between Two Classes or (A Function Friendly to Two Classes)
5.5 Granting Friendship to Other Class

5.1 Arrays of Objects


1. An array is collection of similar data type. It can be collection of struct data type.
2. We can declare array of variables that are of type class. Such variables are called arrays of
objects.
3. Like if we create structure student having Rollno, name and marks. To accept 10-15 students
details we will create 10 or 15 instances of structure using Array hence it is called Array of
instances.
4. For example, if we create a class employee having empno, name, salary. To store 10
employees details we have to create 10 objects of a class hence array of 10 objects is created.
Each array element is of employee class type which is called object Array. OR Array of
objects.
5. Array of objects is stored inside the memory in the same way as Multidimensional array. It
will allocate space in memory for only data items, not member functions.
Example 1: Create a class employee to accept empno, name and salary of 10 employees
through getdata() member function and display the details of each employee through display
member function.
#include<iostream.h>
Arrays, Pointers and References  77

class employee
{
int empno, sal;
char name[10];
public:
void getdata()
{
count <<”enter empno,name & salary”;
cin>>empno>>name>>sal;
}
void display()
{
cout<<”The empno is”<<empno<<endl;
cout<<””The name is”<<name<<endl;
cout<<”The salary is”<<slary<<endl;
}
};
void main()
{
employee e[10];
for (int i=0; i<10; i++)
{
e[i].getdata();
}
cout<<”\n”;
for(int j=0; j,10; j++)
{
cout<<”employee”<<j+1
<<”Details are”<<endl;
cout<<e[i].display();
}
getch();
}
Output:
enter empno name & slary
10 tenna 15000
enter empno name & salary
11 Meena 19000
78  OOPs with C++ Programming

employee 1 details are


The empno is 10
The name is teena
The salary is 15000
employee 2 details are
The empno is 11
The name is Meena
The salary is 19000

5.2 Objects as Function Arguments


Parameters or arguments can be passed to functions. Like data types, the object also can be
passed to function arguments.
For using object as a function argument there are two ways:
1. A copy of the entire object is passed to the function.
2. Only the address of the object is transferred to the function.
(a) Copy of the entire object method is called pass-by-value. Since copy of the object is
passed to function, any change made to the object inside the function do not affect the
object used to call the function.
Address of object method is called pass-by-reference. When an address of the object is
passed, called function works directly on the actual object used in the call. This means
that any changes made to the object inside the function will reflect in the actual object.
(b) Pass-by-reference method is more efficient hence it requires to pass only the address of the
object and not the entire object.
Example 2:
#include <iostream.h>
#include <conio.h>
class time
{
int hours, minutes;
public:
void gettime(int h, int m)
{
hours=h;
minutes=m;
}
void puttime()
{
count<<hours<<”hours and”;
count<<minutes<<””minutes”<<endl;
Arrays, Pointers and References  79

}
void sum(time t1, time t2)
{
minutes=[Link]+[Link];
hours=minutes/60;
minutes=minutes%60;
hours=hours+[Link]+[Link];
}
};
void main()
{
time obj1, obj2, obj3;
[Link](2,45);
[Link](3,30);
[Link](obj1,obj2);
cout<<”obj1=”;
[Link]();
cout<<”obj2=”;
[Link]();
cout<<”obj3=”;
[Link]();
getch();
}
Output:
obj1 = 2 hours and 45 minutes
obj2 = 3 hours and 30 minutes
obj3 = 6 hours and 15 minutes
ob [Link] urs ob [Link] urs ho urs
2 3 6
ob j1.m inu tes ob j2.m inu tes m inu tes
45 50 15

(ob j3) =
ob j1 + obj2

ob [Link] m (obj1, obj2)

5.3 Friend Function or Friendly Function


1. The main objective of OOPS is data hiding where private data members of a class cannot be
accessed from outside the class as well as non-member function cannot access to the private
data of a class.
80  OOPs with C++ Programming

2. If direct access is required then private variables has to be written in public section but it
removes the concept of data hiding. To solve this problem the friend function can be
declared to have an access of private data members of the class.
3. Such a friend function need not be a member of any of these classes.
4. Friend is a special mechanism for non-member function to access private data of a class.
5. Friend function is declared or defined within the scope of class definition.
6. The function should have prefix keyword as friend. This keyword friend informs to the
compiler that it is not a member function of the class but because of friendly this function
can access all data members and member functions of a class.
7. The friend function can be declared with friend keyword as prefix followed by the return
type of the function with function name and arguments of the function.
8. If friend function is declared within a class and defined outside the class then friend keyword
should not be repeated while defining outside the class along with that number :: (scope
resolution operator) is to be used.
9. The Syntax of friend function is
class xyz
{
private:
int a;
public:
__________
__________
friend void display(xyz & x)
{
cout<<”The value of x is”<<x.a;
}
}
10. A friend function, although not a member function, has full access right to the private
member of the class.
Special Characteristics of friend function:
1. It is not in the scope of the class to which it has been declared as friend.
2. A friend function which is not the member function of the class but has full access rights to
the private members of the class.
3. While defining friend function no scope resolution is required.
4. friend function can be declared either in the public or the private part of a class without
affecting its meaning.
5. Normally the member function of a class can access private data members without creating
object but the friend function cannot access the private data member directly but it can be
accessed with object of the class.
Arrays, Pointers and References  81

6. While defining or declaring friend function, the friend function should have argument which
should be object of the class.
7. While calling friend function in the main function. It should have argument which is object
of the class. This function cannot be called with reference to object.
8. friend functions are used in operator overloading.
Example 3: Write a program in C++ to accept two numbers through getdata() member
function and print mean value of two numbers through friend function.
class sample
{
int a,b;
public:
void getdata()
{
cout<<”enter value of a&b”;
cin>>a>>b;
}
friend float mean(sample s);
};
float mean (sample s)
{
return(float (s.a + s.b)/2.0);
}
void main()
{
sample s1;
[Link]();
cout<<”Mean Value is”<<mean(s1);
getch();
}

5.4 Common Friend Function between Two Classes (A Function Friendly


to Two Classes)
1. Two classes can have one common friend function which is capable of accessing members
of both classes.
2. Common friend function should have arguments of both classes.
3. Common friend function should be declared within both classes.
Example 4:
class second; //forward declaration
class first
82  OOPs with C++ Programming

{
private:
int x;
public:
inline void getdata()
{
cout<<”enter value of x”;
cin>>x;
}
friend int sum(first, second);
};
int sum(first one, second two)
{
int temp;
temp=one.x+two.y;
return temp;
}
class second
{
private:
int y;
public:
inline void getdata()
{
count<<”enter value of y”;
cin>>y;
}
friend int sum(first,second);
};
void main()
{
first a;
second b;
[Link]();
[Link]();
int t = sum (a,b);
cout<<”The sum of 2 Nos is”<<t;
getch();
}
Arrays, Pointers and References  83

Example 5: Write a program to create a common friend of two classes as max which is used to
calculate the maximum number entered by two classes.
private: class abc; //forward declaration
class xyz
{
int x;
public:
void getdata(int i)
{
x=i;
}
void display()
{
cout<<”The value of x is”<<x;
}
friend void max(abc, xyz);
};
class abc
{
private:
int y;
public:
void getdata(int p)
{
y=p;
}
void display()
{
cout<<”The value of y is”<<y;
}
friend void max (abc, xyz);
};
void max(abc e, xyz f)
{
if(e.x>f.y)
{
cout<<e.x<<”is greater than”<<f.y;
}
else
84  OOPs with C++ Programming

{
cout<<f.y<<”is greater than”<<e.x;
}
}
void main()
{
abc a;
xyz b;
[Link](10);
[Link](20);
[Link]();
[Link]();
max(a,b);
getch();
}
Example 6: Write a program to print area of circle through one friend function and area of
rectangle through another friend function.
class area
{
private:
int l,b,r;
public:
void getdata()
{
cout<<”enter length & breadth”<<endl;
cin>>l>>b;
cout<<”enter radius”<<endl;
cin>>r;
}
friend float areac(area a)
{
return(3.1415*a.r*a.r);
}
friend int arear(area b1)
{
return(b1.l*b1.b);
}
};
void main()
Arrays, Pointers and References  85

{
area obj;
[Link]();
cout<<”The area of circle is”<<areac(obj);
cout<<”The area of rectangle is”
<<arear(obj);
getch();
}

5.5 Granting Friendship to Other Class


1. Like friend function, the class can be assigned as a friend.
2. While declaring a class as a friend, class should be defined within a class.
3. friend class must be forward declared within a class.
4. friend class member function can use the private data member of another class with object of
that class in which this class is declared as a friend.
Example 7:
class first
{
friend class second; //forward declaration
private:
int x;
public:
void getdata()
{
cout<<”enter no”<<endl;
cin>>x;
}
};
class second
{
public:
void disp(class first temp);
};
void second :: disp(class first temp)
{
cout<<”entered no is”<<temp.x;
}
void main()
86  OOPs with C++ Programming

{
first objx;
second objy;
[Link]();
[Link](objx);
getch();
}
Example 8: Write a program to create a friendship between two classes. Accept semester1 total
marks through class first and Accept semester2 total marks through class second and print sum of both
semesters.
class first
{
friend class second;
private:
int seml;
public:
void getdata()
{
cout<<”enter total marks of sem1”;
cin>>sem1;
}
};
class second
{
private:
int sem2;
public:
void getdata()
{
cout<<”enter semster2 marks”;
cin>>sem2;
}
void disp(first temp)
{
int sum;
sum=tem.sem1+sem2;
cout<<”The sum is”<<sum;
}
};
Arrays, Pointers and References  87

void main()
{
first objx;
second objy;
[Link]();
[Link]();
[Link](objx);
getch();
}

Question Bank for Self-Practice


1. Explain what is Array and define Array of objects with example.
2. Define how the objects can be passed in the arguments of the functions.
3. What is use of friend function and how it can be declared?
4. Define friend function and explain how friend function can access properties and Method of a class.
5. How one common friend can share the properties and Methods of two classes? Explain with example.
6. How the friendships can be achieved between two classes?


Constructors
6 and Destructors
Chapter

Chapter Outline
6.1 Introduction to Constructor and Destructor
6.2 Constructors
6.3 Parameterised Constructors
6.4 Multiple Constructors (Constructor Overloading)
6.5 Constructor with Default Arguments
6.6 Copy Constructor
6.7 Dynamic Constructors
6.8 Destructors

6.1 Introduction
We have used member functions such as getdata( ) or input( ) to initialize the variables. When
this function is invoked with the help of object, it assigns the initial values to the data items of object.
These functions invoked when already objects are created. These functions cannot be used to initialize
member variables at the time of creation of their objects hence to perform initialization of members
while creating object is performed by special member function in c++ called constructor.
It is required to be destroy the variable automatically by the compiler, when a variable of built-in
type goes out of scope hence in C++ directly it is not possible.
Hence special member function called the constructor which enables an object to initialize itself
when it is created. This is known as automatic initialization of objects. It also provides another
member function called the destructor that destroys the objects when they are no longer required.

6.2 Constructors
Definition: A constructor is a special member function which enables object to initialize itself
when it is created. It is invoked automatically having same name as the name of the class.
Constructors and Destructors  89

Constructor function has following special characteristics.


1. Constructor is special member function used to initialization of object.
2. Constructor member function is having the same name as name of the class.
3. Constructor member function is automatically invoked when the object of its associated
class is created.
4. They should be declared in public section.
5. They do not have return types, they cannot return any value. Hence they cannot have even
void return type.
6. Like other member function the constructor member function also can have parameters the
constructor function with parameters are called parameterised constructor.
7. The Default constructor which is called to initialize the object is the non-parameterised
default constructor.
8. Like other C++ function, they can have default arguments because the constructors can be
parameterised constructors.
9. Constructors supports polymorphism. Constructor can be overloaded like function
overloading. Hence one class can have more than one constructor with the different number
of arguments.
10. The constructor makes implicit calls to the two operations.
(a) new
(b) delete
when memory allocation is required for the first time.
The new operator is called when object is created and it is having memory allocation for the
first time.
Delete operator is called when object is not used and it is deallocated from memory.
11. The constructor cannot be inherited further, though derived class can not call the base class
constructor.
12. Constructors cannot be virtual.
13. When object is created the default (non-parameterised) constructor is invoked. If the object
is without arguments then empty constructor is called.
If object is created with parameters, then parameterised constructor is called.
14. It is called constructor because it construct the object and assign data members of the class
by initializing some value.
Example of Constructor:
class hello
{
private:
int x; //private declaration
public:
hello ( ) //constructor definition
{
cout<< “constructor is called” <<endl;
90  OOPs with C++ Programming

x=o;
}
void display ()
{
cout<< “The x value initialize to” <<x;
}
}; // class declaration ends
void main( )
{
hello hi; //object h1 is
[Link]( ); created and constructor
getch( ); is called
}
Output:
Constructor is called
The x value initialize to 0.
Examples:
1. Write a program to print how many number of objects are created by the user.
int count = o;
class hello
{
private:
int x; //private data members declaration
public:
hello() // constructor
{
count=count + 1;
cout<< “object created no is” << count;
}
};
void main( )
{
hello. h1, h2, h3;
getch( );
}
Output:
Object Created no is 1
Object Created no is 2
Object Created no is 3
Constructors and Destructors  91

2. Write a program to accept the value of x and y from the user through constructor and print
sum of two numbers.
class addition
{
private:
int x, y, sum; //private declaration
public:
addition( ) //constructor
{
cout<< “enter value of x&y”;
cin>>x>>y;
}
void calculate( )
{
sum=x + y;
class addition
{
private:
int x, y, sum; //private declaration
public:
addition( ) //constructor
{
cout<< “enter value of x&y”;
cin>>x>>y;
}
void calculate( )
{
sum=x + y;
}
void display( )
{
cout<< “The sum of 2 Nos is” <<sum;
}
};
void main( )
{
addition a; //object creation
[Link] ( );
[Link]( );
getch( );
}
92  OOPs with C++ Programming

3. Write a program to print sum of even numbers from 1 to n by initializing sum variable to
zero.
class series
{
private:
int n, sum;
public:
series( ) //constructor
{
sum=0;
cout<< “enter value of n”;
cin>>n;
}
void calculate( ); //member function declaration
void display( ) //member function definition
{
cout<< “The sum of even series is” <<sum;
}
};
void series:: calculate( ) //member function definition outside the
class with SCOPE Resolution operator (::)
{
for (int i=2; i<=n; i+ = 2)
{
cout<<i;
}
}
void main( )
{
series s; //creating object
[Link]( );
[Link]( );
getch( );
}
Constructors and Destructors  93

6.3 Parameterised Constructors


1. Sometimes we need to initialize the various data elements of different objects with different
values when they are created. This can be achieved by passing arguments to the constructor
function when object is to be created.
2. The object is to be initialized through the constructor by passing arguments to the
constructor function when object is created.
3. The constructor that takes arguments is called parameterised constructor.
4. Parameterised constructor can be called in two ways:
(a) Implicit call.
(b) Explicit call
(a) Implicit call:
addition a (10, 20);
addition is a class
a is object with two parameters 10 & 20.
(b) Explicit call:
addition a = addition (10, 20);
addition is a class name having a is object, to create a object constructor is called by
passing parameters.
Example of Parameterised Constructor
1. Write a program to accept the value of m & n variable through parameterised constructor.
Calculate mean value of it and display through display member function.
class mean
{
private:
int m, n;
float avg;
public:
mean (int m1, int n1)
{
m=m1;
n=n1;
}
void calculate( )
{
avg=(m+n)/2.0;
}
void display( )
{
94  OOPs with C++ Programming

cout<< “The mean value is” << avg;


}
};
void main( )
{
mean m(2, 3);
[Link]( );
[Link]( );
getch( );
}
2. Write a program to create a class student to accept rollno, name, marks of the student
through parameterised constructor and display the details of the student.
#include <string.h>
class student
{
private:
int rollno, marks; //private declaration
char name [10];
public:
student (int r, char n[10], int m) // parameterized constructor
{
rollno=r;
strcpy(name, n); //strcpy string function copies n string to name
marks=m;
}
void display( )
{
cout<< “The rollno is” <<rollno<<endl;
cout<< “The name is” <<name<<endl;
cout<< “The marks is” <<marks;
}
};
void main( )
{
student s(12, “Kiran”, 893); // Creating object with parameterised constructor
[Link]( );
getch( );
}
Constructors and Destructors  95

3. Write a program to create a class book to accept bookno, bookname, title, price of the book.
Also accept Quantity to purchased through parameterised constructor. Calculate member
function will calculate total amount to be paid. Display function will display total amount.
class book
{
int bookno, quantity;
char *name; //private declaration
char *title;
double price, amount;
public:
book(int b, char * n, char *t, double p, int Q)
{ //parameterised constructor
bookno=b;
slrcpy (name, n);
slrcpy (title, t);
price=p;
Quantity = Q;
}
void calculate ( )
{
amount = Price * Quantity;
}
void display( )
{
cout<< “The total amount is” <<amount;
}
};
void main( )
{
book b(101, “C programming”, “Complete Reference C”, 400, 2);
[Link]( ); //creating object of parameterised constructor
[Link]( );
getch( );
}

6.4 Multiple Constructors in a Class or Constructor Overloading


There are three different types of constructors.
1. Default constructor: The constructor itself supplies data values and no values or parameters
are passed by the calling program. It is also called as non-parameterised constructor.
96  OOPs with C++ Programming

2. Parameterised Constructor: In this, the function call the appropriate values. Number of
parameterised passed within constructor.
3. Copy Constructor: Copy constructor is used to declare and initialize an object from another
object.
Example of constructor overloading
We have two kinds of constructors:
1. try( ) // No arguments
2. try(int, int) // Two arguments parameterised constructor.
In the first, the constructor itself supplies the data values and no values are passed by calling
program.
In the second case, the function call passes the values from main function.
C++ allows us to use both types of constructors in the same class.
class try
{
private:
int x, y, z; //private data member declaration
public:
try( ) //default constructor to initialise data members
{
x=0;
y=0;
z=0;
}
try (int a, int b) //parameterised constructor
{
x=a;
y=b;
}
try (int a, int b, int c)
{
x=a; //parameterised constructor
y=b;
z=c;
}
try(try & i) //copy constructor
{
x=i.x;
y=i.y;
z=i.z;
}
Constructors and Destructors  97

To call a constructor the following statements are written.


try t1; //It will invoke automatically first default constructor.
try t2 (2, 3); //It will call second constructor will initialize value of x & y.
try t3 (4, 5, 6); //It will call third constructor will initialize value of x & y & z.
try t4 (t2); //It will invoke third constructor which copies the value of t2 into t4
void display( )
{
cout<< “x=” <<x<<endl; //defining display member function
cout<< “y=” <<y<<endl;
cout<< “z=” <<z<<endl;
}
};
void main( )
{
try t;
try t1(2, 3);
try t2(4, 5, 6);
[Link]( );
[Link]( );
[Link]( );
try t3=t1;
[Link]( );
getch( );
}
Output of the program:
x=0
y=0
z=0
x=2
y=3
x=4
y=5
z=6
x=2
y=3
Example 1: Write a program to accept bookno, bookname, title and price of the book. Accept all
these through parameterised constructor and assign default values through default constructor using
constructor overloading.
# include <string.h>
class book
{
98  OOPs with C++ Programming

int bookno;
char *name;
char *title;
float price;
public:
book( )
{
bookno=0;
name=’\0’;
title=1\0; title = ‘\0’;
price=0.0;
}
book (int b, char * n, char *t, float p) //parameterised constructor
{
bookno=b;
strcpy (name, n);
strcpy (title, t);
price=p;
}
void display( ) //display member function definition
{
cout<< “The bookno is” <<bookno<<endl;
cout<< “The bookname is” <<name<<endl;
cout<< “The booktitle is” <<title<<endl;
cout<< “The book price is” <<price<<endl;
}
};
void main( )
{
book b; // creating object of default constructor
book b1(100, “cplus”, “Vipul Cplus”, 150.50); //creating object of
parameterised constructor
[Link]( );
getch( );
}
Output:
The bookno is 100
The bookname is Cplus
The booktitle is Vipul cplus
The bookprice is 150.50
Constructors and Destructors  99

6.5 Constructor with Default Arguments


1. It is possible to define constructor with default arguments.
Like a member function the constructor member also has parameters; and these parameters
can have default values.
2. The default arguments should be specified from trailing edge to leading edge.
Example:
try (int a, int b=5)
hence default value of argument b is 5.
3. The actual parameter, when specified overrides the default value. The missing arguments
must be trailing ones.
4. All the arguments can have default value.
5. If all arguments are default arguments then constructor called without arguments and if the
some default arguments are passed then the constructor with argument is passed.
Example 2: Write a program to create a class named as interest with parameters principal
amount, number of years and rate of interest number of years and rate of interest should be default
values.
Accept the principle amount from the user through parameters and print simple interest.
class interest
{
private:
float principle, si, year, rate;
public:
interest (float p, float y=10, float r=12)
//parameterised constructor with default arguments
{
principle=p;
year=y;
rate=r;
}
void calculate( )
{
si=principle * year *(rate/100);
}
void display( )
{
cout<< “The simple interest is” <<si;
}
};
void main( )
{
100  OOPs with C++ Programming

interest s(5000); // creating object without assigning value of


default arguments
[Link] ( );
[Link]( );
getch( );
}
Example 3: Write a program to print fibonacci series. Initialize the starting values in the
constructor. Increment these values through increment member function and display the fibonacci
series with the display function.
class fib1
{
private:
int fo, f1, fib; //private declaration of data members
public:
fib1( ) //default constructor
{
fo=0;
f1=1;
fib=0 f0 + f1;
cout<<fo<<f1<<“It”;
}
void increment ( ) //increment member function definition
{
fo=f1;
f1=f1b;
fib=fo + f1;
}
void display( ) //display member function definition
{
cout<<fib<<“It”;
}
};
void main( )
{
fib1 n; //creating object
for (int i=0; i < =15; i++)
{
[Link]( );
[Link]( );
}
getch( );
}
Constructors and Destructors  101

6.6 Copy Constructor


Copy constructor is used to declare and initialize an object from another object.
integer I2 (I1);
Would define the object I2 and at the same time initialize it to the values of I1.
We can write.
integer I2 = I1;
The process of initializing through a copy constructor is known as:
Copy initialization.
I2 = I1;
A copy constructor takes a reference to an object of the same class as itself as an argument.
class test
{
int id; // private declaration
public:
test( ) { } // default constructor
test(int a) // parameterised constructor
{
id = a;
}
test (test & x) // copy constructor
{
id = [Link];
}
void display( )
{
cout<<id;
}
};
void main( )
{
test t; // creating object of default constructor
test t1(10); ‘creating parametrised constructor
test b(t1); ‘creating copy constructor
test c=t1; ‘copying object
cout<< “id of t1 is” << [Link]( );
cout<< “id of b is” << [Link]( );
102  OOPs with C++ Programming

cout<< “id of c is” << [Link]( );


getch( );
}
Output:
id of t1 is 10
id of b is 10
id of c is 10

6.7 Dynamic Constructors


1. The Constructors can also be used to allocate memory at Run time means while creating
objects.
2. This dynamic allocation will allocate right amount of memory for each objects when the
objects are not of the same size, thus resulting in the saving of memory.
3. Allocation of memory to objects at the time of their construction is known as dynamic
construction of objects. The memory is allocated with the help of new operator.
4. The following program shows the use of new in constructors that are used to construct
strings in objects.
#include <iostream.h>
#include <string.h>
class string
{
char name;
int length;
public:
string ( )
{
length = 0;
name = new char [length + 1];
}
string (char * s)
{
length = strlen (s);
name = new char [length + 1];
strcpy (name, s);
}
void display( )
{
cout<<name<< “\n”;
}
Constructors and Destructors  103

void join (string &a, string &b)


{
length = [Link]+[Link];
delete name;
name=new char[length+1];
strcpy(name, [Link]];
strcpy(name, [Link]);
}
};
void main( )
{
char *first=”fy”;
string name1(first), name2(“IT”),
name3(“ty”), s1,s2;
[Link](name1, name2);
[Link](s1, name3);
[Link]( );
[Link]( );
[Link]( );
[Link]( );
[Link]( );
getch( );
}
Output of the program is:
Fy
IT
Ty
FyIT
FyITTy
5. The above program uses two constructors. The first is default empty constructor that allows
us to declare any array of string. The second constructor initialized the length of the string
allocates necessary space for the string to be stored and creates the string itself and the string
is terminated by null character.
6. The member function join concatenates two strings. It estimates the combined length of the
strings to be joined, allocates memory for the combined string and then creates the same
using the string functions.
strcpy( ), strcat( )
In the function join, length and name are members of the object that calls the function, where
[Link] and [Link] are members of the argument object a.
The main( ) function program concatenates three strings into one string.
104  OOPs with C++ Programming

6.8 Destructors
1. A destructor is a special member function used to destroy the objects that have been created
by a constructor.
2. After the use of an object, the memory should be deallocated which is holding the object for
this reason the object should be destroyed.
3. Destructor is automatically invoked when the object is not used.
4. Destructor member function is having the same name as a name of destructor and it is
prefixed by ∼ (tilde) sign.
e.g. ∼ test( )
{
}
5. Destructor member function is implicilitly called by the compiler upon exit from the
program by calling delete operator to clean up storage that is no longer accessible.
6. A destructor never takes any arguments.
7. A destructor does not return any value.
8. Since no parameters can be passed, hence destructor can not be parameterized and it cannot
have default arguments.
9. Destructors cannot be overloaded.
10. Destructors cannot be inherited further.
Example 4:
# include <iostream.h>
int count = 0; //declaring global count variable by initializing to zero
class hello
{
public:
hello( )
{ // constructor
count++;
cout<<”object Number created is” << count;
}
∼ hello ( )
{ // destructor
cout<< “No. of object destroyed is” <<count;
count – –;
}
};
void main( )
Constructors and Destructors  105

{
hello h1, h2, h3;
getch( );
}
Output of the program is:
No. of object created is 1
No. of object created is 2
No. of object created is 3
No. of object destroyed is 1
No. of object destroyed is 2
No. of object destroyed is 3

Question Bank for Self-Practice


1. What is a constructor? What is use of the constructor?
2. How the objects can be allocated and deallocated with memory management?
3. How can we use more than one constructor in one class? Illustrate with example.
4. List some of special characteristics of constructor.
5. Explain how the constructor can be overloaded with example.
6. Can we use more than one constructor in one class? If yes justify answer with example.
7. How the dynamic initialization of objects can be achieved?
8. What are different types of constructors?
9. Explain difference between constructor and destructor.
10. How the objects can be copied from one to another object? Illustrate with example.
11. Discuss the advantages of destructors.
12. Discuss how default values can be assigned in the parameterised constructor. Explain with example.
13. Write a program to accept rollno, name and marks from the user through parameterised constructor of
student class. Display details through display member function. Display destructor message to destroy
the object.
14. Write a program to print factorial of a number through parameterised member function.
15. Write a program to print number is prime number or not and print prime numbers from 1 to n through
constructor overloading.
16. Create a class factorial containing a variable n of integer data type. Define a constructor to initialize the
value of n = 5. Define a member function fact to calculate the factorial of n.
17. Create a class A contains two variables x & y. Which is of float type & they will be the instance variable.
Define a constructor to initialize the value of x & y. Define member functions.
(a) Swap to interchange the value of x and y.
(b) Max to print maximum of x & y.
(c) Min to print minimum of x & y.

7 Manipulators

Chapter

Chapter Outline
7.1 C++ Streams
7.2 C++ Stream Classes
7.3 Unformatted I/O Operations
7.4 Formatted Console I/O Operations
7.5 Managing O/P with Manipulators

7.1 C++ Streams


Special stream functions are used as manipulator functions. For input and output processing cin
and cont functions along with get from operator and put to operator e.g. << and >> are used.
The I/O system in C++ is designed to work with variety of devices including terminals, disks and
tape drives. The I/O system supplies an interface to the programmer called stream.
A stream is a sequence of bytes. It acts either as a source from which the input data can be
obtained or as a destination to which the output data can be sent.
The source stream that provides data to the program is called input stream and the destination
stream that receives output from the program is called the output stream.
A program extracts the bytes from an input stream and inserts bytes into an output stream.
In put stream

In put device
extraction from
in put stream

Pro gram
ou tpu t stream in sertion in to
ou tpu t device ou tpu t stream
Manipulators  107

The data in the input stream can come from the keyboard or any other storage device and the
output stream can go to the screen or any other storage device. A stream acts as a interface between
the program and the input/output device. cin represents the input stream connected to the standard
input device.
cout represents the output stream connected to the standard output device.
The default input device for cin is keyboard.
The default output device for cout is screen.
We can Redirect streams to other devices or files also.

7.2 C++ Stream Classes


The C++ I/O system contains hierarchy of classes that are used to define various streams to deal
with both the console and disk files. Stream classes are used for input and output operations. These
classes are declared in the header file iostream.
io s

po inter

istream stream b uf ostream

in put

io stream

istream _w ithassign io stream _w ithassig n ostream _w ithassign

ios is the base class for istream(input stream) and ostream(output stream), in turn base classes for
iostream(input-output stream).
ios is declared as virtual base class so that only one copy of its members are inherited by the
iostream.

7.3 Unformatted I/O Operations


istream provides facilities for formatted and unformatted I/O operations.
While ostream provides facilities for output stream and output functions.
>>and<< are input and output operators.
>>operator is overloaded in the istream class.
>> is overloaded operator in ostream class.
Example:
cin>>variable>>variable2
int a;
cin>>;
108  OOPs with C++ Programming

int a,b;
cin>>a>>b;
cout
Example:
cout<<”hello”<<endl;
cout<<”welcome”<<”\n”;
cout<<”Intro to c++ streams”;
Example:
int a,b,sum=45;
cout<<”the sum of 2 Nos is”<<sum;
istream is the input stream.
 It inherits the properties of ios
 Declares input functions such as get(), getline() and read()
 Contain overloaded extraction operator >>
ostream is the output stream.
 Inherits the properties of ios
 Declares output functions put() and write()
 Contains overloaded insertion operator<<
iostream is input/output stream.
 Inherits the properties of ios stream and ostream through multiple inheritance and thus
contains all the input and output functions.
streambuf is stream buffer class.
 Provides an interface to physical devices through buffers.
 Acts as a base for filebuf class used ios files.
put() and get() functions
The istream and ostream classes defines two member functions get() and put() respectively to
handle the single character input/output operations. We can use get (char*) and get(void) prototypes to
fetch a character including blank spaces, tabs and newline characters.
char c;
[Link](c); //ger character from keyboard
while(c !=’\n’)
{
cout<<c; //display a character
[Link](c); //get another character
}
Example :
char c;
c=[Link]();
Manipulators  109

Hence value returned by the function get() is assigned to the variable c.


The put() function is a member of ostream class, can be used to output a line of text character by
character.
[Link](‘x’);
[Link](ch);
Example:
char c;
[Link](c);
while(c !=’\n’)
{
[Link](c); //displays character on screen
[Link](c);
}
get() and put() are character handling functions.
getline() and write() functions:
We can read and display 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 newline character. The function
can be invoked by using cin function.
[Link](line,size);
The function call invokes the function getline() which reads character input into the variable line.
The reading is terminated by new line character ‘\n’ the new line character is replaced by NULL
character.
char name[22];
[Link](name,22);
Assume user has inputed.
ANGELA IS A CUTE GIRL
This sentence consist of 21 characters hence it will print whole line.
If we write
char name[16];
[Link](name,16);
Assume user has inputed
ANGELA IS A CUTE GIRL
Output is
ANGELA IS A CUTE
Write() function display an entire line can be invoked with cout method.
[Link](line,size)
line indicates the name of the string, size indicates number of characters to display.
110  OOPs with C++ Programming

Example 1:
#include<iostream>
#include<string.h>
void main()
{
char*string1=”Kiran”;
char*string2=”Chirag”;
int m=strlen(string1);
int n=strlen(string2);
for(int i=1; i<n; i++)
{
[Link](string2, i);
cout<<endl;
}
for(i=n; i>0; i--)
{
[Link](string2, i);
cout<<”\n”;
}
// concatenating strings
[Link](string1,m).write string2,n);
//crossing the boundary
[Link](string1,3);
getch();
}
Output of program:
C
Ch
Chi
Chir
Chira
Chirag
Chira
Chir
Chi
Ch
C
KiranChirag
Kir
Manipulators  111

7.4 Formatted Console I/O Operations


Manipulator functions are special stream functions that change certain characteristics of the input
and output.
They change the format flags and values for a stream.
These manipulator functions facilitate the formatting of Input and Output streams.
<iomain.p> is the input output manipulator header file.
Predefined Manipulators:
1. endl  It is the output manipulator to generate a carriage return or line feed character.
2. setbase manipulator is used to convert the base of one numeric value into another base.
dec – decimal base(10)
hex – hexadecimal base(16)
oct – octal base
3. setw()  The stew() stands for set width. It is used to specify the minimum number of
character position on output field a variable will consume.
setw(int w)
cout<<setw(5)<<a;
4. setfill()  It is used to specify a different character to fill unused field width of the value.
setfill(char f)
setfill(‘*’)
5. setprecision()  It is used to control number of digits of an output stream, display of a
floating point value.
setprecision(int p)
It sets the precision for floating point insertion to P. The default precision is 6.
6. ends  The ends manipulator used to attach a null terminating character (‘\0’) at the end of
the string. It takes no argument whenever it is invoked.
7. ws  white space  It is used to ignore the leading white space that precedes the first field.
8. setf()  It is used to set iosflags.
9. unsetf()  It is used to reset iosflags.
Formatted Console I/O Operations:
C++ supports number of features used for formatting the output.
1. ios class functions and flags.
2. manipulators
3. user defined output functions.
ios class contains large number of member functions which is used to format the output.
ios format functions:
1. width  It is used to specify field size required for displaying an output value.
2. precision  to specify the number of digits to be displayed after the decimal point of a float
value.
112  OOPs with C++ Programming

3. fill()  To specify a character that is used to fill the unused portion of a field.
4. setf()  Used to specify format flags that can control the form of output display.
5. unself()  To clear the flags specified.
Defining field width:
width() function is used to define the width of a field necessary for the output of an item.
To invoke cout function is used.
[Link](w);
where w is the field width (number of columns).
The output will be printed in a field of w characters wide at the right end of the field.
[Link](5);
cout<<543<<12<<”\n”;
output
54312
setting precision:
Floating numbers are printed with six digits after the decimal point. We can specify the number
of digits to be displayed after the decimal point while printing the floating point numbers.
[Link](d);
[Link](3);
Example:
float a=3.14159
cout precision(3);
cout<<a;
output=3.142
filling and padding: fill()
fill() function is used to fill the unused positions by any desired character.
This functions used to invoke cout method.
[Link](ch);
where ch represents the character which is used for filling the unused positions.
[Link](‘*’);
[Link](10);
cout<<5250<<”\n”;
Output:
******5250
Example 2:
#include<iostream.h>
void main()
{
Manipulators  113

[Link](‘<’);
[Link](3);
for(int n=1; n<=6; n++)
{
[Link] (5);
cout<<n;
[Link](10);
cout<<1.0/float(n)<<”\n”;
if(n==3)
[Link](‘>’;
}
cout<<”\n padding changed \n”;
cout fill(‘#’);
[Link](15);
cout<<12.345678<<”\n”;
getch();
}
The Output:
<<<<1<<<<<<<<<1
<<<<2<<<<<<0.5
<<<<3<<<<<0.333
>>>>4>>>>>>0.25
>>>>5>>>>>>>0.2
>>>>6>>>>>0.167
Pading changed:
#########12.346

7.5 Managing Output with Manipulators


All manipulators are stored into different functions. These set of functions are stored in iomanip.h
header file. It has same features as that of ios member functions and flags.
Example:
out<<mainp1<<mainp2<<mainp3<<item;
hence setw(int w) function is used to set the field width to w, it is equivalent to width() function.
setprecision(int d) function set the floating point precision to d, it is equivalent to precision ()
function.
setfill(int c) function set the fill character to c. It is equivalent to fill() method.
setiosflags(long f) function set the format flag f. It is equivalent to setf() function.
resetflags(long f) function clear the flag specified by f. It is equivalent to unself().
114  OOPs with C++ Programming

endl function is used to insert new line and flush stream. It is equivalent to “\n”.
Example:
1. cout<<setw(10)<<12345;
b b b b b 12345
b indicates black space.
2. cout<<setw(10)<<setiosflags(ios::left)<<12345;
Example 3: Program illustrates the formatting of the output values using both manipulators and
ios functions.
#include<iostream.h>
#include<iomainip>
void main()
{
[Link](ios::showpoint);
cout<<setw(5)<<”no”<<
setw(15)<<”Inverse_of_n”<<
setw(15)<<”sum_of_terms\n”;
double term, sum=0;
for(int n=1; n<=10; n++)
{
term=1.0/float(n);
sum=sum+term;
cout<<setw(5)<<n
<<setw(14)<<setprecision(4)<<setiosflags
(ios::scientific)<<term
<<setw(13)<<resetiosflags(ios::scientific)<<
sum<<endl;
}
getch();
}
Output:
No. Inverse_of_n Sum_of_terms
1. 1.0000e + 000 1.0000
2. 5.0000e – 001 1.5000
3. 3.3333e - 001 1.8333
4. 2.5000e - 001 2.0833
5. 2.000e - 001 2.2833
6. 1.6667e - 001 2.4500
7. 1.4286e - 001 2.5929
Manipulators  115

8. 1.2500e - 001 2.7179


9. 1.1111e - 001 2.8290
10. 1.0000e - 001 2.9290

Question Bank for Self-Practice


1. Explain in brief what is stream.
2. Discuss get() function supported by the input stream.
3. What role does the iomanip file play?
4. Describe briefly the features of I/O system supported by C++.
5. Explain what are different manipulators with example.
6. Explain how and with what functions the output can be manipulated.
7. Explain formatted console I/O operations.
8. Explain use of getline() and write() function.
9. Explain get() and put () functions.
10. Explain different C++ stream classes.


Function and Operator
8 Overloading
Chapter

Chapter Outline
8.1 Function Overloading
8.2 Operator Overloading

8.1 Function Overloading


1. Overloading refers to the use of same function with different type of parameters for different
purposes.
2. The function would perform different operations depending on the argument list in the
function call. Function overloading can be performed with class also.
Function overloading is already explained in chapter – 2 without using class.
Function Overloading with Class:
Example 1:
void display( )
{
int x=25;
cout << “n=” << x;
}
Class first
{
private:
int x;
public:
void getdata( )
Function and Operator Overloading  117

{
cout << “enter value of x” << endl;
cin>>x;
}
void display( )
{
cout<< “x within first class is” <<x;
}
}
class second
{
private:
int x;
void getdata( )
{
cout<< “enter value of x” <<endl;
cin>> x;
}
void display( )
{
cout<< “The value of x in second class is” <<x;
}
};
void main( )
{
first obj1; ‘creates object of class first
second obj2; ‘creates object of class second
[Link]( ); ‘Invoking getdata member function through obj1
[Link]( ); ‘Invoking display member function
[Link]( ); ‘Invoking getdata with reference to obj2
[Link]( ); ‘Invoking display with reference to obj2
display( ); ‘Invoking main global display member function
getch( );
}
Example 2:
Write a program in C++ to create a class areademo has area member function to calculate area of
rectangle and overloaded with another area member function to calculate area of circle.
Class areademo
{
int r, l, b, a; ‘declaring private data members
118  OOPs with C++ Programming

float ac;
public:
int area (int l1, int b1) ‘Defining area parameterised member function
{
l = l1;
b = b1;
retum l *b;
}
float area (int*r1) ‘refining area member function by overloading previous are
member function
{
r=r1;
return (3.1415*r*r);
}
};
void main( )
{
areademo obj; ‘Creating object of a class
cout<< “The area of rectangle is” << [Link] (2, 3);
cout<< “The area of circle is” << obj. area (5); getch( );
}
Example 3:
Write a program in C++ using addition class has common sum member function to add 2 integer
and 3 float numbers using function overloading.
Class addition
{
int x, y, s; ‘declaring private data member
float fx, fy, fz, fs;
void sum (int x1, int g1) ‘definign sum member function with two integer
paremeters
{
x=x1;
y=y1;
S= x + y;
}
void sum (float f1, float f2, float f3) ‘defining sum member function
with 3 float parameters
{
fx=f1;
Function and Operator Overloading  119

fy=f2;
fz=f3;
fs=fx + fy + fz;
}
void dispint( )
{
cout<< “The sum of integer is” <<s;
}
void dispfloat( )
{
cout<< “The sum of float is” <<fs;
}
};
void main( )
{
addition obj;
[Link] (2, 3);
[Link]( );
[Link] (2.5, 5.6, 9.6);
getch(); obj. disfloat( );

8.2 Operator Overloading


1. Overloading means assigning different meanings to the operation depending on the context.
2. Like function overloading we can perform operator overloading i.e. the existing operators
can be overloaded.
3. Existing operator like ‘+’ can be used for addition of two integer numbers. Same ‘+’
operator can be used for addition of two float numbers. Same ‘+’ operator can be used for
concentration of two strings.
4. Overloading cannot alter the basic template of operator i.e. basic meaning of operator cannot
be changed.
5. The operators that are predefined in C++ can be overloaded but the new operators cannot be
assigned or created.
6. Special operator function is used to overload any operator.
Syntax:
Return type operator OP (argument list)
{
function body
}
(a) Return type is the data type of the value returned by the function.
120  OOPs with C++ Programming

(b) Operator is the special member function name.


(c) OP is the operator being overloaded.
(d) Argument list is the list of parameters passed within operator function.
Function body is the statements within operator function to perform any task.
7. The operators like : :, sizeof , ?, :, ., * cannot be overloaded they are having special meaning
in C++.
8. Operator function must be either member function or friend function. The operators which
are to be overloaded are the Unary and Binary operators.
In friend function with Unary operator will have one argument in operator function and
while for binary it has two arguments.
In member function with unary operator it has no argument in operator function and while
for binary it has one argument.
9. Overloaded operator functions can be invoked by
OP x OR x OP
++x OR x ++
OR
–x
Rules of Operator Overloading:
1. Only existing operators can be overloaded.
2. Basic meaning of operator never changes.
3. ++, – –, – are unary operators.
4. +, – can act as a binary operators.
5. There are some operators which cannot be overloaded they have special meaning in C++
like : :, . , :, ?, * operators.
6. The operators can be overloaded only with operator function which is either member
function or friend function.

8.2.1 Unary Operator Overloading


1. Unary operator overloading requires one operator and one operand.
2. When unary operator overloading can be performed with operator function as a member
function, no argument is to be passed.
3. While overloading unary operators with friend function, one argument is to be passed in the
operator function.
4. Let us consider if unary minus operator is used then only one operand is used to overload
that operand.
5. Normally ‘–‘ Sign is used to change the sign of a variable or a number. Here we are
overloading ‘–‘ operator to negate the object in turn all data members of object will be
negated. Hence ‘–‘ operator is overloaded.
6. In member function no argument is passed hence object itself is used to invoke member
function and it acts as a argument, it won’t return value.
Function and Operator Overloading  121

7. Example of overloading – operator as unary operator using operator function as a member


function.
class abc
{
int x, y; ‘declaring private data members
public:
abc (int a, int b) ‘Defining abc constructor with two integer parameters
{
x = a;
y = b;
}
void operator – (void) ‘Defining operator member function to overload ‘–‘ operator
{
x = – x;
y = – y;
}
void display ( ) ‘display member function to display value of x & y
{
cout << “x=” << x <<endl;
cout << “y=” <<y;
}
};
void main( )
{
abc s(2, – 3); ‘creating object of parameterised constructor
[Link]( ); invoking member function invoking display
– s; ‘Calling ‘–‘ operator member function
[Link]( );
getch( );
}
Output:
x=2
y = –3 Original values

x = –2
y=3 Overloaded values

8. In Unary operator using friend function it should have only one argument which should be
the object of the class. Hence object is to be passed as a argument.
9. Unary operator overloading using friend function.
122  OOPs with C++ Programming

Overloading – operator
class abc
{
int x, y; ‘declaring private data members
public:
abc (int a, int b) ‘Defining parameterised constructor
{
x = a;
y = b;
}
friend void operator – (abc & S)
{ ‘defining operator function as a friend function
s.x = – s.x;
s.y = – s.y;
}
void display( ) ‘ defining display member function
{
cout<< “x =” <<x<<endl;
cout<< “y =” <<y;
}
};
void main( )
{
abc s(2, – 3); ‘creating parameterised object
[Link]( ); ‘invoking display function
– s; ‘overloading ‘–‘ operator
[Link]( ); * invoking display function
getch( );
}

8.2.2 Binary Operator Overloading


1. Binary operators can be overloaded using members functions for that following Rules are
followed:
(a) While overloading binary operator the operator member function should have only one
argument.
(b) This passed argument should be object of the class.
(c) Two operands are used while calling operator.
(d) Example while calling we have to write.
C3 = C1 + C2
Function and Operator Overloading  123

C1 is the object on LHS of operator which takes responsibility of invoking operator


member function.
C2 is the object on RHS of operator acts as a argument which is passed to operator
function.
C3 is object where result is stored after overloading.
(e) Example: Overloading of + operator as a Binary operator using operator function as a
member function.
class abc
{
int x, y; ‘declaring private data members
public:
abc ( ) ‘defining default constructor
{
}
abc (int a, int b) ‘overloading constructor with parameterised constructor
{
x = a;
y = b;
}
abc operator + (abc & s) ‘defining operator function
{
abc S3;
s3.x = x + s.x;
s3.y = y + s.y;
return s3;
}
void display( ) ‘defining display member function
{
cout << “The x is” <<x<<endl;
cout << “The y is” <<y;
}
};
void main( )
{
abc s1 (2,3); ‘creating object S1
abc s2 (4,5); ‘creating object S2
abc s4: ‘creating object S4
s4 = s1 + s2; ‘invoking ‘+’ binary operator function
124  OOPs with C++ Programming

[Link]( ); ‘invoking display member function


} getch( );
2. Binary operators can be overloaded using friend functions for that following rules are
followed:
(a) While overloading binary operator the operator friend function should have two
arguments.
(b) These both arguments should be object of the class.
(c) Two operands are used while calling operator.
(d) While Calling.
C3 = C1 + C2 is used where C1 and C2 are objects of class should be passed to the
arguments of operator function and C3 is Return object to store the Result.
(e) Binary operator overloading by friend function using + operator overloading.
class abc
{
int x, y; ‘declaring private data member
public:
abc (int a, int b) ‘declaring parameterised constructor
{
x = a;
y = b;
}
abc ( )
{
}
friend abc operator + (abc & s1, abc & s2) defining operator member function as a
friend function
{
abc s3;
s3.x = s1.x + s2.x;
s3.y = s1.y + s2.y;
return s3;
}
void display( ) ‘defining display member function
{
cout<< “x is” <<x<<endl;
cout<< “y is” <<y;
}
};
void main( )
{
Function and Operator Overloading  125

abc s4 (2, 3); ‘creating objects


abc s5 (4, 5);
abc s6;
s6 = s4 + s5; ‘invoking ‘+’ operator function
s6. display( ); ‘invoking display function
getch( );
}
Example 1:
Overloading of ++ unary operator by using operator function as member function.
class abc
{
int x, y; ‘declaring private data members
public:
abc (int a, int b) ‘defining parameterised constructor
{
x = a;
y = b;
}
void operator ++ (void) ‘defining operator function
{
x = ++ x;
y = ++ y;
}
void display( ) ‘defining display function
{
cout <<”x =” <<x<<endl;
cout <<”y =” <<y;
}
};
void main( )
{
abc s(2, – 3); ‘creating object
[Link]( ); ‘invoking display
++s; ‘overloading operator
[Link]( ); ‘invoking display
getch( );
}
126  OOPs with C++ Programming

Example 2:
Overloading + operator as a binary operator to add 2 complex numbers by operator as a member
function.
#include <iostream.h>
class complex
{
float x, y;
public:
complex (float real, float, img) ‘constructor
{
x = real;
y = img;
}
complex operator + (complex c) ‘operator function
{
complex temp;
temp.x = x + c.x;
temp.y = y + c.y;
return temp;
}
void display( )
{
cout <<x << “+ j” <<y <<endl;
}
};
void main( )
{
complex c1, c2, c3; ‘creating objects
C1 = complex (2.3, 4.5);
C2 = complex (1.3, 1.6);
C3 = c1 + c2; ‘overloading operator
cout << “C1 =”;
cout << [Link]( );
cout << “C2=”;
cout << [Link]( );
cout << “C3 =”;
cout << [Link]( );
getch( );
}
Function and Operator Overloading  127

Example 3:
Overloading + operator as a binary operator to combine two strings by using operator function as
a member function.
#include <iostream.h>
#include <string.h>
class stringdemo
{
char s[10];
public:
stringdemo (char s1[10]) ‘constructor
{
strcpy (s, s1):
}
stringdemo operator + (string demo d) ‘operator function
{
strcat (s, d.s);
return s;
}
void display( ) ‘display function
{
cout<< “combined string is” <<s;
}
};
void main( )
{
stringdemo s1 (“Kiran”); ‘object
stringdemo s2 (“Gurbani”); creation
stringdemo s3;
s3 = s1 + s2; ‘invoking operator function
[Link]( );
getch( );
}

Question Bank for Self-Practice


1. What is operator overloading? State its Rules.
2. What is an operator function? Describe the syntax of an operator function. Where it is used?
3. What are unary and binary operators and how these operators can be overloaded?
4. What rules are to be followed while overloading unary and binary operators?
5. Explain function overloading with a one common swap function to swap two integers and swap two
floats using function overloading within class.


9 Inheritance

Chapter

Chapter Outline
9.1 Introduction to Inheritance
9.2 Types of Inheritance
9.3 Declaring Derived and Base Class
9.4 Single Inheritance
9.5 Multilevel Inheritance
9.6 Multiple Inheritance
9.7 Hybrid Inheritance
9.8 Hierarchical Inheritance

9.1 Introduction to Inheritance


Inheritance is a concept of reusability. It is also called derivation. Reusability is the important
feature of OOP’s. Reusability is a technique where we can reuse the class which is already tested and
debugged many times.
This technique is used for creating new class from old class and reusing the properties of existing
one.
The mechanism of deriving new class from old class is known as inheritance. The old class is
referred as base class and the new class is referred as derived class. The base class is also called as
super class and the derived class is also called as sub-class. It is also known as parent-child
relationship. The derived class can access properties and member functions of base class during any
type of inheritance as well as derived class has its own properties and methods.
Inheritance  129

9.2 Types of Inheritance


1. Single Inheritance: A derived class with only one base class is called single inheritance.
With this one derived class can be possible with one base class.

A Base class

B Derived class

2. Multilevel Inheritance: The mechanism of deriving a class from another derived class is
known as Multilevel Inheritance.

A Base class

B Intermediate Base Class

C Derived class
In multilevel first class is derived from base class and again from derived class another class
will be derived.
3. Multiple Inheritance: A derived class with several base classes, is called multiple
inheritance.

A B

C
This type of inheritance can have one or more base classes from that we can drive only
derived class is called as Multiple Inheritance.
4. Hierarchical Inheritance: The properties of one class may be inherited by more than one
class is called hierarchical Inheritance. In this type of inheritance one base class, number of
classes can be derived is known as hierarchical Inheritance.

B C D
130  OOPs with C++ Programming

5. Hybrid Inheritance: It is a combination of Multilevel and Multiple Inheritance as well as it


can be combination of hierarchical and Multiple inheritance hence it is combination of
different types of inheritance.

B C

9.3 Declaring the Derived Class and Base Class


Base class can be defined as normal C++ class which may consist of some data and functions.
Derived class is a class which acquires properties from base class is called derived class.
Derived class can have its own properties and methods.
The syntax for creating derived class is
Class ABC : private PQR
{
members of ABC;
}
ABC is derived class and
PQR is base class
ABC is derived from PQR privately.
Private is a visibility mode: Sign indicates the class name is derived from base class.

9.4 Single Inheritance


9.4.1 Public Inheritance
1. When the visibility mode is public the base class is publicly inherited.
2. In public Inheritance, the private members of base class can not be inherited and the public
members of the base class become public members of the derived class and protected
members of base class become protected members of the derived class.
3. Syntax is:
class abc: public PQR
{
members of ABC;
}
4. Simple example of Single Inheritance using Public Inheritance.
Inheritance  131

# include <iostream.h>
class base
{
int x;
public:
int y;
void getdata( )
{
cout<< “enter value of x&y”;
cin>>x>>y;
}
int getx( )
{
return x;
}
void show x( )
{
cout << “x; is” <<x;
}
};
class d: public base
{
int total;
public:
void sum( )
{
total = y + getx( );
}
void display( )
{
cout<< “x =” << getx( )<<endl;
cout<< “y =” << y <<endl;
cout<< “sum =” <<total;
}
};
void main( )
{
d obj;
[Link]( );
132  OOPs with C++ Programming

[Link]( );
[Link]( );
obj.y=100;
[Link]( );
[Link]( );
getch( );
}

9.4.2 Private Inheritance


1. When the visibility mode is private, the base class is privately inherited.
2. When a base class is privately inherited by a derived class public members of the base class
becomes private members of the derived class, as well as protected members of base class
will become private members of derived class. The private data members of base class can
not be inherited further.
Hence public members and protected members of base class can only be accessed by the
member functions of the derived class. They are inaccessible to the objects of the derived
class.
3. Syntax is:
class abc: private PQR
{
members of abc;
}
4. Example of single inheritance using private.
class base
{
int x;
public:
int y;
void getxy( )
{
cout << “enter value of x&y”;
cin>>x>>y;
}
int getx( )
{
return x;
}
void show x( )
{
cout << “The x value is” <<x;
Inheritance  133

}
};
class d: private base
{
int z;
public:
void setxy( )
{
getxy( );
}
void MUL( )
{
z = y * getx( );
}
void display( )
{
showx( );
cout << “y =” << y;
cout << “z =” << z;
}
};
void main( )
{
d obj;
[Link] ( );
[Link]( );
[Link]( );
getch( );
}
Output:
enter the value of x & y : 5 10
The x value is 5
y = 10
z = 50

9.4.3 Protected Members


1. If we want to inherit some part of private members by a derived class hence directly it is not
possible and if we keep these some private variable as public then they can be accessed by
134  OOPs with C++ Programming

derived class but it will also accessed by other classes, hence it removes data hiding concept
so keep those private variables in a protected scope.
2. This third visibility mode protected used for limited access of private data inheritance.
3. A member declared in protected scope of base class can be accessed by only member
functions of derived class. It cannot be accessed by the functions outside these two classes.
4. When a derived class inherited as protected from base class then protected members of base
class will become protected members of derived class and public members of base class will
become protected members of derived class and private members of base class can not be
further inherited.
Class B

not inherited Private not inherited

Protected

Public
Class D1: Public B Class D2: Public B

Private Private

Protected Protected

Public Public
Class x: Public D1: Protected D2

Private

Protected

Public

9.5 Multilevel Inheritance


1. The mechanism of deriving a new class from another derived class is known as multilevel
inheritance.
2. From base class derived class is created further from that derived class new derived class is
created hence to increase the levels of inheritance.
3. If class A acts as a base class B is immediate derived class of A. C is derived class of B
derived class which acts as a base class for C. Hence class B is called as intermediate base
class and the chain ABC is known as Multilevel inheritance path.
class A {-------------} // base class
class B: public A {--------}// B derived from A
class C: public B {--------}// c is derived from B
Inheritance  135

A Base class

B Intermediate Base Class

C Derived class
4. Class B can inherit the properties of A class C can inherit the properties of A&B both.
Example 1:
Create a base class student to accept Rollno and display Rollno through member functions.
Create sem1 derived class to accept total marks of sem1 and print marks of sem1 through member
functions. Create sem2 derived class from sem1 to accept and print the marks of sem2 through
member functions. Create a result derived class to print rollno, sem1, sem2 marks and total marks of
sem1 & sem2.
#include <iostream.h>
class student
{
protected:
int rollno;
public:
void getroll( )
{
cout<< “enter rollno”;
cin>>rollno;
}
void putroll( )
{
cout<< “The Rollno is” << rollno;
}
};
class sem1: public student
{
protected:
int s1;
public:
void getsem1( )
{
cout<< “enter total marks of sem1”;
cin>> s1;
136  OOPs with C++ Programming

}
void putsem1( )
{
cout<< “sem1 marks is” << sem1;
}
};
class sem2: public sem1
{
protected:
int s2;
public:
void getsem2( )
{
cout<< “enter total marks of sem2”;
cin >> s2:
}
void putsem2( )
{
cout<< “sem2 marks is” <<sem2;
}
};
class result: public sem2
{
private:
int total;
public:
void display( )
{
total=s1 + s2;
putroll( );
putsem1( );
putsem2( );
cout << “Total marks is” << total;
}
void main( )
{
result r1;
[Link]( );
r1.getsem1( );
Inheritance  137

r1.getsem2( );
[Link]( );
getch( );
}
Example 2:
Create a class student to accept rollno and print rollno through member functions. Create a
derived class marks to accept marks of three subjects and print three subjects marks. Create a derived
class Result to display total of all 3 subjects and Avg of 3 subjects.
class student
{
protected:
int rollno;
public:
void getroll ( )
{
cout << “enter rollno”;
Cin>> rollno;
}
void putroll ( )
{
cout<< “The Rollno is” <<rollno;
}
};
class marks : public student
{
protected:
int sub1, sub2, sub3;
public:
void getmark( )
{
cout<< “enter 3 subjects marks”;
(Cin>>sub1>>sub2>>sub3;
}
void putmark( )
{
cout<< “Three subjects marks are” << “sub1=”<<sub1<<”sub2=”<<
sub2<<”sub3=”<<sub3;
}
};
class result : public marks
138  OOPs with C++ Programming

{
int total;
float avg;
public:
void display( )
{
total = sub1+sub2+sub3;avg=total/3.0;
putroll( );
putmark( );
cout<< “total marks is” <<total<<endl;
cout<< “The Average marks is” <<avg;
}
};
void main( )
{
result r1;
[Link]( );
[Link]( );
[Link]( );
getch( );
}

9.6 Multiple Inheritance


1. One derived class from more than one base class is called Multiple inheritance.
2. If A is one base class
B is another base class
C is derived from A & B
A B Base classes

C Derived class

3. Multiple Inheritance allows to combine the features of A & B in C hence class C can inherit
the properties of A & B.
4. The syntax is
class D: visibilitymode baseclass 1,
visibilitymode baseclass 2
{
Body of class D;
}
Inheritance  139

D is derived class, derived from two base classes baseclass1 and baseclass2 with visibility
mode can be private, public, protected.
5. Example 1:
Create a base class M to accept and print value of M variable. Create another base class N to
accept and Print value of N variable. Create derived class P from M & N to multiply the
value of M variable and N variable through member functions also display M & N individual
values along with product.
class M
{
protected:
int m;
public:
void getm(int x)
{
m=x;
}
void putm( )
{
cout<< “M value is” <<m;
}
};
class N
{
protected:
int n;
public:
void getn(int y)
{
n=y;
}
void putn( )
{
cout<< “n value is” <<n;
}
};
class P: public M, public N
{
int mul;
public:
140  OOPs with C++ Programming

void display( )
{
mul=m*n;
putm( );
putn( );
cout<< “product is” <<mul;
}
};
void main( )
{
p obj;
[Link](25);
[Link](10);
[Link]( );
getch( );
}
Example 2:
Write a program in C++ to create a base class basic to accept basic salary from the user and
print basic salary. Create another base class year to accept and print number of years worked
in the organisation. Create a derived class from both base classes to print basic sal, no. of
years and check if number of years > =3 then print bonus is 300 and add that bonus to basic
sal. print updated basic and if it is < 3 then bonus = 100 add to basic and print updated basic
through member function.
#include<10stream.h>
class basic
{
protected:
int basic;
public:
void getbasic(int x)
{
basic=x;
}
void printbasic( )
{
cout<< “The basic is” << basic;
}
};
class year
{
Inheritance  141

protected:
int year;
public:
void getyear (int y)
{
year = y;
}
void putyear( )
{
cout<< “The year is” <<year;
}
};
class d: public basic, public year
{
public:
void display( )
{
cout<< “original basic is” <<basic;
cout<< “No. of years is” << year;
if (year >= 3)
{
int bonus=300;
basic = basic + 300;
}
else
{
int bonus=100;
basic = basic + 100;
}
cout<< “Updated basic is” <<basic;
}
};
void main( )
{
d obj;
[Link](5000);
[Link](10);
[Link]( );
getch( );
}
142  OOPs with C++ Programming

9.7 Hybrid Inheritance


1. The mechanism of Combining Multilevel and Multiple Inheritance is called hybrid
Inheritance.
2. Class A is base class, B, is derived class of A, C is another base class, D is derived class
from B derived class (as base class) and C class is called hybrid inheritance.
3. D derived class can access the properties of A class, B class as well as C class.
4. Example: Create a class student as base class to accept Rollno and print rollno. Create
derived class test of student class to accept subject1 and subject2 marks and print both
subjects marks through member functions. Create a base class sports to accept the sports
marks and print sports marks. Create a derived class result from test and sports class to print
sum of sub1, sub2, and sports marks. Also print individual marks through display member
functions.

Student

Test Sports

Result
#include <iostream.h>
class student
{
protected:
int rollno;
public:
void getroll(int a)
{
rollno=a;
}
void putroll( )
{
cout<< “The rollno is” <<rollno;
}
};
class test: public student
{
protected:
int sub1, sub2;
public:
void getmarks(int x, int y)
Inheritance  143

{ sub1=x;
sub2=y;
}
void putmarks( )
{
cout<< “sub1= “<<sub1 <<endl;
cout<< “sub2= “<<sub2 <<endl;
}
};
class sports
{
protected:
int spmark;
public:
void getsport(int P)
{
spmark = p;
}
void putscore( )
{
cout<< “sports marks is” <<spmark;
}
};
class result: public test, public sports
{
int total;
public:
void display( )
{
total = sub1+sub2+spmark;
putroll ( );
putmarks( );
putscore( );
cout << “The total is” << total;
}
};
void main( )
{
result s;
[Link] (10);
[Link](25, 95);
144  OOPs with C++ Programming

[Link](49);
[Link]( );
getch( );
}

9.8 Hierarchical Inheritance


1. The mechanism of creating two or more derived classes from one base class is called
hierarchical inheritance.
2. Class A is base class. Class B, C, D are derived classes derived from A base class.
3. All derived classes can access properties of Base class A.

B C D
4. Example:
Create a Base Class student to accept rollno and print rollno through member function.
Create three derived classes art, medical and Engg. In derived class art, accept the marks of
arts and print the art marks. In derived Class Medical marks. Accept medical marks and print
medical marks. In derived class Engg. define member function for mechanical, electrical,
civil to accept the marks and print the marks through dispengg member function. In the main
function give choice to the user to select either of one type from mech, elec, civil. Accept
marks of each and display.
#include <iostream.h>
class student
{
protected:
int rollno;
public:
void getroll( )
{
cout<< “enter rollno” <<endl;
cin>> rollno;
}
void disproll( )
{
cout<< “rollno is” <<rollno;
}
};
class art: public student
Inheritance  145

{
protected:
int marks;
public:
void getart( )
{
getroll( );
cout<< “enter arts marks”;
cin>>marks;
}
void dispart( )
{
disproll( );
cout<< “Arts marks is” <<marks;
}
};
class med: public student
{
protected:
int marks;
public:
void getmedi( )
{
getroll( );
cout<< “enter medical marks” <<endl;
cin>> marks;
}
void dispmedi( )
{
putroll( );
cout<< “Medical marks is” <<marks;
}
};
class engg: public student
{
protected:
int marks;
public:
void mech( )
{
getroll( );
146  OOPs with C++ Programming

cout<< “enter mechanical marks”;


cin>>marks;
}
void elect( )
{
getroll( );
cout<< “enter electrical marks”;
cin<< marks;
}
void civil( )
{
getroll( );
cout<< “enter engg marks”;
cin>> marks;
}
void dispengg( )
{
cout<< “marks is” <<marks;
}
};
void main( )
{
engg el;
art al;
med ml;
int ch;
[Link]( );
[Link]( );
[Link]( );
[Link]( );
cout<< “[Link]” <<endl;
cout<< “[Link]” <<endl;
cout<< “[Link]” <<endl;
cout<< “enter your choice” <<endl;
cin>> ch;
switch(ch)
{
case l:
[Link]( );
break;
Inheritance  147

case 2:
[Link]( );
break;
case 3:
[Link]( );
break;
}
[Link] ( );
getch( );
}

Question Bank for Self-Practice


1. Explain concept of reusability in inheritance.
2. Explain what is inheritance state its types? Explain single inheritance with example.
3. Explain how the inheritance can be possible with different visibility mode? How it can be achieved?
Explain Rules of each visibility mode in inheritance.
4. Explain syntax of single inheritance and multiple inheritance and state difference between them.
5. Private data members can not be inherited further. If some private members can be inherited, how it can
be done? Explain with example.
6. Explain Multilevel inheritance with example.
7. Explain hybrid inheritance with example.
8. Explain hierarchical inheritance with example.
9. Create a base class emp which should have empno, name as private data members. It should have 2
public member functions get and display for accepting and printing details. It has one public data
member as sal. Create a derived class D. It should have private data member as bonus and 2 member
functions calculate( ) and display( ). In calculate accept the value of bonus from the user. Add this bonus
to the salary and update the salary. Print all details of employee along with bonus and updated sal. Use
public inheritance.
10. Write a program in C++ to create a base class employee used to accept empcode and basic sal through
member function and print with other member function. Create a drived class allowance accept total
allowances and print through separate member functions. Create a deduction derived class from
Allowances to accept and print deduction amount through separate member functions. Create a derived
class net of deduction.
Calculate Net Salary = basic + allowance – deduction through calculate( ) member function and print Net
Sal along with the details of the employee.
11. Write a program to create a base class student to accept and print Rollno through separate member
functions.
Create a derived class BA of student to accept marks of BA and print the marks of BA.
Create a derived class BSc of student to accept marks of either of one category i.e. BSCIT or BSCCS
through menu choice from the User. Create a derived class commerce of student to accept marks of
commerce and print the marks. Implement using Hierarchical Inheritance.


Virtual Functions
10 and Polymorphism
Chapter

Chapter Outline
10.1 Polymorphism
10.2 Virtual Function
10.3 Rules of Virtual Functions
10.4 Pure Virtual Function
10.5 Abstract Classes
10.6 EARLY Binding
10.7 LATE Binding

10.1 Polymorphism
Compile Time and Run Time Polymorphism:
1. Polymorphism is basic feature of OOPS. It states that one thing behaves differently at
different place.
2. It also states that one name multiple forms i.e., one function name behaves differently for
different tasks.
Same as one operator behaves differently at different place.
3. Polymorphism can be function overloading Or operator overloading.
4. Polymorphism is divided into two parts.
(a) Compile time polymorphism.
(b) Run time polymorphism.
5. Compile time polymorphism: In function overloading and operator overloading the compile
time polymorphism is achieved. In function overloading the function name is same with
different number of parameters or type of parameters it is overloaded. Overloaded member
functions are selected for invoking by matching arguments both type and the number.
Virtual Functions and Polymorphism  149

This information is known to the compiler at compile time and hence compiler is able to
select the appropriate function for a particular call at compile time itself.
This is called compile time polymorphism. This is also called as early binding or static
binding.
Early binding indicates that an object is bound to its function call at compile time.
At the compile time if prototype does not match then compile time error occurs.
The binding of function and allocation of variables during compilation time is called compile
time polymorphism.
6. Runtime polymorphism:
(a) When object is created at Run time and when at Runtime object is bounded to allocate
memory then it is called Runtime polymorphism.
(b) When the base class and derived class have same function with same prototype then
function is not overloaded it is based at Runtime which function is selected for base or
derived. This is called Run time polymorphism.
class base
{
int x;
public:
void show( )
{ _________
_________
_________
}
};
class d: public base
{
int y;
public:
void show( )
{ ________
________
________
}
};
In this example, both base class and derived class has common show( ) member function with
same prototype.
This show function is still not overloaded. Because it is based how it is called at Run time with
the help of object pointer by specifying member function of base class or derived class.
150  OOPs with C++ Programming

This is called Run time polymorphism. The binding performed at Runtime is called late binding
also called dynamic binding because the selection of a particular function is done dynamically at
Runtime.
7. Polymorphism can be graphically represented as follows:
Polymorphism

Compile time Runtime


polymorphism Polymorphism

Function Operator Virtual


overloading overloading functions

10.2 Virtual Function


1. Virtual function is used to avoid the duplication of member function in base class and
derived class.
2. A virtual function is one that does not really exist but it appears real to some parts of the
program.
3. When we use same function name in both the base and derived class and at Runtime if we
call same common function with the object of derived class then also by default base class
function is called. To avoid this duplication of function in the base class, function is declared
as virtual using the keyword virtual.
4. A virtual function is a member function that is declared within the base class and it is
redefined by the derived class.
To create a virtual function precede the function declaration in the base class as Keyword
‘virtual’.
5. When base class contains virtual function then this virtual function is inherited in derived
class and it is redefined in derived class to fit its own needs.
The virtual function is also called as ‘One Interface Multiple Methods.’
6. Each Redefinition of virtual function by derived class implements a specific method. It is
called Run-time polymorphism because during run-time the member function will be
accessed through pointer.
7. In the derived function when definition of virtual function is redefined then virtual keyword
is not used.
8. When a function is made virtual, C++ determines which function is to be used at runtime
based on the type of object pointed by the base pointer, rather than the type of the pointer.
Thus by making the base pointer to point to different objects, we can execute different
versions of the virtual function.
Virtual Functions and Polymorphism  151

10.3 Rules of Virtual Functions


1. The virtual function must be the member of class.
2. They can be accessed by using object pointer.
3. In base class the virtual function should be defined even though it is not used.
4. The prototype of base class version of virtual function and derived class version of virtual
function should be identical.
5. They cannot be static members.
6. A virtual function can be friend of another class.
7. While a base pointer can point to any type of the derived object the reverse is not possible
i.e., we can not use a pointer to a derived class to access an object of the base type.
Example of Virtual Function:
class base
{
public:
virtual void vfunc( )
{
cout<< “This is base class vfunction”;
}
};
class d: public base
{
public:
void vfunc( )
{
cout<< “This is derived 1 class vfunction”;
}
};
class d1: public base
{
public:
void vfunc( )
{
cout<< “This is derived2 class vfunction”;
}
};
void main( )
{
base *p, b;
152  OOPs with C++ Programming

d obj1;
d1 obj2;
p=&b;
p vfunc( );
p = &obj1;
p vfunc( );
p = &obj2;
p vfunc( );
getch( );
}
Output:
This is base class vfunction
This is derived 1 class vfunction
This is derived 2 class vfunction

10.4 Pure Virtual Functions


1. A pure virtual function is a function declared in a base class that has no definition relative to
the base class.
2. In this compiler requires each derived class to either define the function or redeclare it as a
pure virtual function.
3. A class containing pure virtual functions cannot be used to declare any objects of its own.
4. A pure virtual function is also called as do-nothing function may be defined as.
5. Virtual void display( ) = o;
6. Example:
# include <iostream.h>
class base
{
public:
virtual void show( )= o;
};
class dl: public base
{
public:
void show( )
{
out<< “In derivedl”;
}
Virtual Functions and Polymorphism  153

};
class d2: public base
{
public:
void show( )
{
cout<< “In Derived2”;
}
};
void main( )
{
Base *a[2];
d1 obj1;
d2 obj2;
a[0] = &obj1;
a[1] = &obj2;
a[0] show( );
a[1] show( );
}
Output:
In Derived 1
In Derived 2

10.5 Abstract Classes


1. A class that contains at least one pure virtual function is called Abstract class.
2. A abstract class contains one or more functions for which there is no definition, one cannot
create the object of abstract class.
3. We can create pointers and references to an abstract class. Hence abstract class supports
Run-time polymorphism.
4. The abstract class can not be used to declare any objects of its own.
5. The main objective of abstract class is to create a base pointer required for achieving Run-
time polymorphism.
6. The abstract class is often defined as one that will not be used to create any objects, but
exists only to act as a base class of other classes.
7. It is design concept in program development and provides a base upon which other classes
may be built.
154  OOPs with C++ Programming

10.6 Early Binding


1. When an object is bound to its function call at compile time, it is called early binding.
2. It refers to events that occur at compile time.
3. When all information needed to call a function is known as ‘at compile time’.
e.g., Normal function call, overloaded function call and overloaded operators.
When function overloading is done, the overloaded functions are selected for invoking by
matching the arguments and data type of argument.
This information is known to the compiler at compile time and hence compiler is able to select
the appropriate function for a particular call at the compile time. This is called early binding. OR static
binding or static linking also known as compile time polymorphism.

10.7 Late Binding


1. When the function is invoked at Runtime then it is called Late binding OR binding at
Runtime.
2. When there is function whose name and prototype are same in both base class and derived
class and same function in base class is defined as virtual then which version of that function
should be called by compiler. It can be possible at Runtime when it is known what class is
pointed to by base class object pointer, the appropriate version of the function will be called.
This is called late binding.
3. It refers to function call that are not resolved until run-time.
4. The virtual function are used to achieve late binding. When access is through a base pointer
or reference the virtual function actually called is determined by the type of object pointed
by the pointer.
5. The advantage of late binding is flexibility.
6. Late binding require some overhead but provider increased power and flexibility.

Question Bank for Self-Practice


1. Explain difference between early binding and late binding.
2. Explain difference between virtual function and pure virtual function.
3. Explain Need for Virtual function. Explain Rules of Virtual function.
4. Explain Abstract class.
5. What is polymorphism? How it is achieved at compile time and Runtime?
6. What is virtual function?
7. When do we make a virtual function “pure”?


11 File Handling

Chapter

Chapter Outline
11.1 Introduction to File Handling
11.2 Classes for File Stream Operations
11.3 Opening and Closing a File
11.4 Detecting End of File
11.5 More about Open (): File Modes
11.6 File Pointer and their Manipulations
11.7 Sequential Input and Output Operations
11.8 Reading and Writing a Class Object
11.9 Updating a File
11.10 Error Handling During File Operations
11.11 Command-Line Arguments

11.1 Introduction to File Handling


A file is a collection of related data stored in a particular area on the disc. The program can be
designed to perform Read and Write operations on these files through file handling program. We can
transfer the data between console and file and between the files and monitor.
The iostream of C++ handles file operations similar to console I/O operations. It uses file streams
to interface between program and file. The stream that supplies data to the program is called as input
stream. The stream which receives data is known as output stream. The I/O stream file consists of
istream methods and ostream method.
Similarly fstream consist of ifstream and ofstream and it also supports one file buffer class to
store data. All these file stream classes are derived from fstream base class.
156  OOPs with C++ Programming

In put stream
read data
data inp ut

Disk file pro gram

data ou tput
w rite data
File input and output streams
The I/O system uses file streams as an interface between the programs and the files. The stream
that supplies data to the program is known as input stream and the one that receives data from the
program is known as output stream.
The input stream extracts OR reads data from the file and output stream is used to insert or write
data to the file.
The input operation is used to create input stream and this input data link to the program and
output operation involves establishing an output stream. It takes data output from the program to
output stream and writes the data to disk files.

11.2 Classes for File Stream Operations


The I/O system of C++ contains a set of classes that define the file handling methods.
These include ifstream, ofstream and fstream.
These classes are derived from fstreambase and from the corresponding iostream class.
These classes, designed to manage the disk files, are declared in fstream and therefore we must
include this file in any program that uses files.
io s

io stream istream stream buf ostream


file

io stream

fileb uf
ifstream fstream ofstream
fstream
file

fstream base

Stream classes for file operations


File Handling  157

ios is a class consist of istream and ostream class. istream is the input stream class and ostream is
the output stream. fstream base class consist of ifstream and ofstream classes used for creating input
stream and output stream.
iostream class has input stream (Istream) and ostream (output stream).
Streambuf class has filebuf class.
fstream class has ifstream and ofstream. ifstream functions meaning open for reading only.
Ofstream functions meaning open for writing only.

11.3 Opening and Closing a File


If we want to use any file then following things are considered.
1. Give suitable name to the file.
2. Give proper datatypes. Structure of the file depends on the contents of a file.
3. Specify the purpose of the file by specifying the mode of the file either in Read or Write
purpose.
4. Opening Method whether in Sequential or Random.
For opening fstream class is used.
1. filebuf class  Its purpose is to set the file buffers to read and write.
2. fstreambase class  It serves as a base for fstream, ifstream and ofstream class. Contains
open() and close() functions.
3. ifstream class  provides input operations contains open() with default input mode.
It inherits the functions get(), getline(), read(), seekg() and tellg() functions from istream.
4. ofstream class  provides output operation. Contains open() with default output mode. It
inherits put(), seekp(), tellp() and write() functions from ostream.
5. fstream class  It contains open() method with default input mode. It inherits all the
functions from istream and ostream classes through iostream.
For opening a file, we must first create a file stream and then link it to the filename. A file stream
can be defined using the classes ifstream, ofstream and fstream that are contained in fstream.h header
file.
A file can be opened in two ways:
1. Using the constructor function of the class.
2. Using the member function open() of the class.
1. Using the constructor functions of the class:
This method is used when we use only one file in the stream as we know constructor is used to
initialise the object when object is to be created. Here filename is used to initialize the file stream
object.
This involves the following steps:
(a) Create a file stream object with appropriate stream class.
ofstream is used to create output stream ifstream is used to create input stream.
(b) Initialise the file object with the desired filename.
158  OOPs with C++ Programming

For example:
ofstream outfile (“[Link]”);
ofstream is a class, outfile is a object ofstream class within object parameters. We are specifying
the filename that means we are calling parameterised constructor of ofstream. Hence if we want to
write anything into file, it can be written with the help of outfile object.
Example:
outfile << “Total”;
outfile << sum;
Output:
total 45
if value of sum variable is 45.
Ifstream class is used to create input file stream.
ifstream infile (“[Link]”);
ifstream is a class and infile is a object. Object has a parameter which is filename. If we want to
read anything from the file, we can read through infile object.
Example:
infile >> sum;
Reading value of sum variable from the file [Link].
2. Using the member function Open:
This method is used when we want to manage multiple files using one stream. open() function is
used to open multiple files that use the same stream object. We may need to process a set of files
sequentially.
Example:
ofstream outfile; // creates object for
output stream
[Link](“[Link]”); // opens [Link] file
[Link] // closing a file
[Link](“[Link]”); // opening [Link]
with same object
[Link] // closing a file
Hence with the same object we can open multiple files.
Closing a file  The file can be closed with the help of close method. For close method we have
to specify object [Link].
Example:
[Link]
Outfile is an object name, hence with the help of close method, it will close object outfile, in turn
will close the file which is opened through outfile object.
Note: When the file is opened for writing only it means with the help of ofstream class object, a new file is created. If
there is no file existing of the same name. If the same name file is already existing then current contents will be
overwrite the previous contents.
File Handling  159

11.4 Detecting End of File


eof() member function is used to indicate End of file. After last line of the file the eof character is
available in the file.
If we want to read the contents of the file.
eof() is a member function of ios class. It returns a non-zero value if the end-of-file (Eof)
condition is encountered, and a zero, otherwise.
ifstream fin(“[Link]”);
while(fin)
ifstream is a class and fin is object to open [Link] file for Reading. This while Loop will
terminate when it returns O, it indicates that an error has occurred in the file. When it returns 1, it
indicates Eof() is reached & while Loop terminates.
Hence while statement terminates the program on reaching the end of the file.

11.5 More About OPEN (): File Modes


ifstream and ofstream constructors and the function open() are used to create new files as well as
to open the existing files.
Hence for specifying Mode, open() method has two arguments.
1st argument is to specify filename.
2nd argument is to specify the mode of the file.
This mode will identify the purpose for which the file is opened.
ifstream inf;
[Link](“[Link]”,mode);
Example:
[Link](“[Link]”, ios::in);
It indicates [Link] is opened in read mode hence ifstream function is opened for reading only.
Example:
ofstream out;
[Link](“[Link]”, ios::out);
It indicates [Link] is opened for write mode hence ofstream function is opened for writing only.
Here ofstream function is used for writing only.
File Mode Parameters:
Parameters Meaning
1. ios::app Append to end-of-file.
2. ios::ate Go to end of file on opening.
3. ios::binary Binary file.
4. ios::in Open file for reading only.
5. ios::nocreate Open fails if the file does not exist.
160  OOPs with C++ Programming

6. ios::noreplace Open fails if the file already exists.


7. ios::out Opens file for writing only.
8. ios::trunc Delete the contents of the file if it exists.
Programs:
1. Write a program in C++ to accept the name from user & store it into the file [Link].
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
char name[10];
clrscr();
cout<<”enter the name”;
cin>>name;
ofstream out(“[Link]”);
out<<name;
[Link]();
getch();
}
2. Write a program to display the contents of [Link] file.
#include <iostream.h>
#include <conio.h>
#include <fstream.h>
void main()
{
char name[10]
clrscr();
ifstream inf(“[Link]”);
inf>>name;
cout<<name;
[Link]();
getch();
}
3. Write a program to open a file [Link] for writing an string after writing read the contents of
that file.
#include <iostream.h>
#include <conio.h>
#include <fstream.h>
void main()
{
char name[20];
File Handling  161

clrscr();
ofstream out;
[Link](“[Link]”);
out<<“hello”;
[Link]();
ifstream inf;
[Link](“[Link]”);
inf>>name;
cout<<name;
[Link]();
getch();
}
4. Write a program to accept item name and cost of item from the user and write it into the
[Link] file and then display the contents of [Link] file.
void main()
{
char name[20];
float cost;
clrscr();
ofstream out;
[Link](“[Link]”);
cout<<“enter the item name”;
cin>>name;
out<<name<<end1;
cout<<“enter the cost”;
cin>>cost;
out<<cost;
ifstream inf;
[Link](“[Link]”);
inf>>name;
inf>>cost;
cout<<“The item name is”<<name;
cout<<“The item cost is”<<cost;
[Link]();
getch();
}
5. Write a program to accept empno, name and salary of emp. from the user and save it into
[Link] and then display on the screen.
void main()
{
char name[20];
162  OOPs with C++ Programming

int eno, esal;


clrscr();
ofstream out;
[Link] (“[Link]”);
cout<<“enter the name”;
cin>>name;
out<<name<<endl;
cout<<“enter the eno”;
cin>>eno;
out<<eno;
cout<<“enter the salary”;
cin>>esal;
out<<esal;
[Link]();
ifstream inf;
[Link](“[Link]”);
inf>>name;
inf>>eno;
inf>>esal;
cout<<“The empname, sal & no is”
<<name<<eno<<esal;
[Link]();
getch();
}
Getline function  This function is used to read the full line from a particular file and you have
to specify the size of characters i.e. how many characters are there in a line.
Program:
Example: Write a program in C++ to create a file [Link], write 3 different lines then open
that particular file & display the contents linewise.
void main()
{
char x[80];
clrscr();
ofstream out;
[Link](“[Link]”);
out<<“united state of america”;
out<<“India is a country”;
[Link]();
ifstream inf;
File Handling  163

[Link](“[Link]”);
while(inf)
{
[Link](x,80);
cout<<x;
}
[Link]();
getch();
}

11.6 File Pointer and Their Manipulators


Every file is associated with file pointer. Every file has two pointers: (1) input pointer (get
pointer) and (2) output pointer (put pointer). We can use these pointers to move through the file while
reading or writing.
The input pointer is used for reading the contents and output pointer is used to write the contents
at given location. When input and output pointer is used, automatically pointer is advanced.
When we open a file in read only mode, the input pointer is defaulty set at the beginning hence
we can read file from start.
When we open a file in write-only mode, the existing contents are deleted and output pointer is
set at the beginning. Hence, we can start writing from beginning.
When we want to open an existing file to add more data, the file is opened in append mode. This
moves output pointer to the end of the file.
Functions for Manipulation of File Pointers:
1. seekg( )  It moves get pointer (input) to a specified location.
2. seekp( )  It moves put pointer (output).
3. tellg( )  It gives the current position of the get pointer.
4. tellp( )  It gives the current position of the put pointer.
[Link](10);
It moves the file pointer to the byte number 10.
ofstream fileout;
[Link](“hello”,ios::app);
intp=[Link]();
On execution of these statements, the output pointer is moved to the end of the file “hello” and
the value of P will represent the number of bytes in the file.
ios::beg  indicates start of the file.
ios::cur  current position of the pointer.
ios::end  End of the file.
164  OOPs with C++ Programming

11.7 Sequential Input and Output Operations


The files can be accessed sequentially as well as randomly. To access the file, we have input and
output operations on the file.
In the sequential files, get() and put() functions are used to read a single character and to print a
single character. If we want to handle the random file or binary file then function like read and write
functions are used.
Get() and put() functions:
put() function writes a single character to the associated string and get() function is used to read a
single character from the associated string. If program needs to read the string then get method is used
to read characters by characters.
Example: This program reads the string from the user and on receiving the string, the program
writes it character by character, to the file using the put() function.
The program then displays the contents of the file on the screen. It uses the function get () to
fetch a character from the file and continues to do so until the end-of-file condition is reached.
# include <iostream.h>
# include <fstream.h>
# include <string.h>
void main()
{
char string [80];
cout<<“enter a string”;
cin>>string;
int len = strlen(string);
fstream file;
[Link](“Text”, ios::in|iso::out);
for (int i=0; i<len; i++)
[Link](string[i]);
[Link](0);
char ch;
while (file)
{
[Link](ch);
cout<<ch;
}
return 0;
}
Output of the program:
Enter a string
malcolm_ovichegan input
malcolm_ovichegan output
File Handling  165

11.8 Reading and Writing a Class Object


Get() and put() functions are used to read and print character.
getline() function is used to read a line but all these functions are having fixed number of
characters to read and if we want to read the whole data without specifying the format then we can use
the function read and write. These function handle the data in a binary form.
To use the read function, first we will create the object of ifstream.
Example 
ifstream infile;
Hence infile is the object of ifstream class.
[Link]((char*) & v, sizeof(v));
ofstream outfile;
[Link] ((char*) & v, sizeof (v));
These functions take two arguments. The first is the address of the variable v and the second is
the length of that variable in bytes is indicated by ‘size of’ keyword.
The address of the variable must be cast to type char* (i.e., pointer to character type)
Example: (example of I/O operations on binary files)
Program to declare array of float values and save it into array and then recover them for display
on the screen.
# include <iostream.h>
# include <fstream.h>
# include <iomanip.h>
const char * filename = “BINARY”;
void main()
{
float height [4] = {175.5, 153.0, 167.25, 160.70};
ofstream outfile;
[Link](filename);
[Link]((char*) & height, sizeof(height));
[Link]();
for(int i=0; i<4; i++)
{
height[i]=0;
}
ifstream infile;
[Link](filename);
[Link]((char*)&height, sizeof(height));
for(i=0; i<4; i++)
166  OOPs with C++ Programming

{
cout<<8etw(10)<<setprecision(2)<<height[i];
}
[Link]();
getch();
}
The output of program is
175.50 153.00 167.25
Example of Reading and writing class objects:
#include <iostream.h>
#include <fstream.h>
#include <iomanip.h>
class employee
{
int empno;
char name[10];
float salary;
public:
void readdata(void)
{
cout<<“enter empno, name & salary”;
cin>>empno>>name>>salary;
}
void writedata(void)
{
cout<<setiosflags(ios::left)<<setw(10)<<
empno<<name<<salary;
}
};
void main()
{
employee e[2];
fstream file;
[Link](“[Link]”, ios::in|ios::out));
cout<<“enter details of two employees”;
for(int i=0; i<2; i++)
{
e[i].readdata();
File Handling  167

[Link] ((char*)&e[i],sizeof(e[i]));
}
[Link](0);
cout<<“\nOUTPUT\n\n”;
for(i=0; i<2; i++)
{
[Link]((char*)&e[i], sizeof(e[i]));
e[i].writedata();
}
[Link]();
getch();
}
The output of program:
Enter details of two employees.
enter empno, name & salary
1 malcolm 40000
enter empno, name & salary
2 Angela 20000
Output:
1 malcolm 40000
2 Angela 20000

11.9 Updating a File (Random Access)


Updating is modifying the data in the file.
The updating would include one or more of the following tasks.
1. Displaying the contents of a file.
2. Modifying an existing item.
3. Adding a new item.
4. Deleting an existing item.
To obtain length of the object sizeof of each object can be obtained.
int object_length = sizeof (object);
seekg() and seekp() functions are used to search moves get pointer to the specified location as
well as set pointer is used to the specified location to write or put the contents to the specified location.
tellg() and tellp() functions are used to display the current pointer position of get pointer and put
pointer.
168  OOPs with C++ Programming

11.10 Error Handling During File Operations


While opening a file for reading and writing, possibly error may occur while reading or writing.
There can be number of Errors.
1. A file which we are attempting to open for reading does not exist.
2. A filename used for a new file may already exist.
3. We may attempt on invalid operations such as reading past the end-of-file.
4. There may not be any space available in the disc to store more data.
5. We may use invalid filename.
6. We may attempt to perform an operation when the file is not opened for that purpose.
Different Error handling functions supported are:
1. eof()  It is end of file function returns true or non-zero value if end of the file is
encountered while reading otherwise returns false(zero).
2. fail()  This function returns zero when an input or output operation has failed.
3. bad()  This function returns true if an invalid operation is attempted or any
unrecoverable error has occurred. It return false, when it is possible to recover data.
4. good()  This function Return true if no error has occurred. When it returns false, no
further operations can be carried out.
Example:
ifstream infile;
[Link](“[Link]”);
while(![Link]())
{ ________
________
________
________ (process the file)
}
if ([Link]())
{ ________
________
________
________ (terminate program normally)
}
else
if([Link])
{ ________
________
________
________ (report fatal error)
}
File Handling  169

else
{
[Link](); // clear error state
________
________
________
________
}

11.11 Command-Line Arguments


The C++ supports feature that it allows us to supply the arguments to the main function. These
arguments are supplied at the time of invoking the program. They are used to typically pass the names
of data files.
Example: At the command prompt if we type exam data result.
exam is the C++ program file and data & results are the filenames passed to the program as
command line arguments. The command line arguments data & result should be separated or delimited
by space.
The first argument always should be the file name.
The main() function of the program has two arguments.
main(int argc, char*argv[])
The first argument argc is called as argument counter. It counts how many number of arguments
user has passed at the command line. The second argument is argv which is called as argument vector.
That means it is array of argument and return type is character. Each and every command line
argument is stored into argv array. The size of array is equal to argc.
If we write following line at command line argument.
Exam Data Results.
then argc will be 3 and argv is an array created.
argv[a] = exam
argv[1] = data
argv[2] = results
If we want to open the data file then we write
[Link] (argv[1]);
If we want to open the Result file then we write
[Link] (argv[2]);
Example: Write a program to accept two filenames from the user through command line
arguments through C++ and declare one numbered array having 10 different numbers, it may be
combination of even and odd numbers.
170  OOPs with C++ Programming

Check each and every numbered array element. If it is even then write the contents into 2nd file.
Advisable to take the 2nd file name as [Link] and if the number is odd then write that number into
the 1st file advisable to take [Link].
# include<iostream.h>
# include<fstream.h>
# include<stdlib.h>
int main (int argc, char*argv[])
{
int number [10] = {1,2,3,4,5,6,7,8,9,10};
if(argc!=2)
{
cout<<”error in arguments p/s.
enter two arguments”;
exit(1);
}
ofstream fout1, fout2;
[Link](argv[1]);
[Link](argv[2]);
for (int i=0; i<=9; i++)
{
if (number [i] 2 ==0)
{
fout2<<number[i],<<“ ”;
}
else
{
fout1<<number[i]<<“ ”;
}
}
[Link]();
[Link]();
ifstream fin;
char ch;
for (i=1; i<argc; i++)
{
[Link](argv[i]);
cout<<“The contents are”;
while(fin)
{
[Link](ch);
File Handling  171

cout<<ch;
}
[Link]();
}
} return 0;
Output:
contents of odd
1 3 5 7 9
contents of even
2 4 6 8 10
Example:
1. Write a program to display the length of a file
# include<iostream.h>
# include<conio.h>
void main()
{
int count=0;
char ch;
ifstream inf;
[Link](“[Link]”);
while (inf)
{
[Link](ch);
int count = count + 1;
}
count<<”The Length of the file is”<<count;
[Link]();
getch();
}
2. Write a program to read the contents of 1 file & append those contents into another file.
# include<iostream.h>
# include<conio.h>
void main()
{
char ch;
ifstream inf;
ofstream out;
[Link](“[Link]”);
[Link](“[Link]”);
172  OOPs with C++ Programming

while(inf)
{
[Link](ch);
[Link](ch);
}
[Link]();
[Link]();
getch();
}

Question Bank for Self-Practice


1. What are input and output streams?
2. What is the difference between opening a file? With a constructor function and opening a file with open ()
function?
3. What is a file mode? Describe the various file mode options available.
4. Explain open method with different file modes.
5. Explain command line arguments.
6. Explain get() and put() function in detail.
7. Explain Updating of files in Random Access.
8. Explain error handling in files.


12 Templates

Chapter

Chapter Outline
12.1 Introduction
12.2 Class Templates
12.3 Class Templates with Multiple Parameters
12.4 Function Templates
12.5 Function Templates with Multiple Parameters
12.6 Overloading of Template Functions
12.7 Member Function Templates
12.8 Non-Type Template Arguments

12.1 Introduction
Template is a method for writing a single function or class for a family of similar functions or
classes in a generic manner. When a single function is written for a family of similar functions, it is
called as ‘function template’.
A template can be used to create a family of classes or functions.
The templates can be for array class, creating arrays of various data types such as integer array,
float array, character array or double array.

12.2 Class Templates


A template can be called as a macro, it is type of macro, which runs faster than normal functions.
Since a template is defined with a parameter that would be replaced by a specified data type at
the time of actual use of the class or function, the templates are sometimes called parameterised
classes or functions.
174  OOPs with C++ Programming

Syntax of creating A Template


template<class T>
class classname
{ ________
________
________
________ // class member specification with type T
wherever required;
};
A generic function is created using the keyword template. It is used to create a template that
describes what a function will do, leaving it to the compiler to fill in the details as needed.
Type is a placeholder name for a data type used by the function. This name may be used within
the function definition. It is only a placeholder that the compiler will automatically replace with an
actual data type when it creates a specific version of the function and use of keyword class to specify a
generic type in a template declaration is traditional. You may also use the keyword typename.
Example:
# include<iostream.h>
const size=3;
template<class T>
class vector
{
T* V;
public:
vector()
{
v=new T[size];
for(int i=0; i<size; i++)
v[i]=0;
}
vector (T* a)
{
for(int i=0; i<size; i++)
{
v[i]=a[i];
}
}
T operator * (vector & y)
{
T sum=0;
for(int i=0; i<size; i++)
Templates  175

{
sum+=thisv[i]*y.v[i];
}
return sum;
}
};
void main()
{
int x[3]={1,2,3};
int y[3]={4,5,6};
vector <int> v1;
vector <int> v2;
v1=x;
v2=y;
int R=v1*v2;
cout<<“R=”<<R<<endl;
getch();
}
The class template definition is similar to ordinary class definition. Only difference is that the
class definition is prefixed by temp <class t>. This prefix tells the compiler that we are going to
declare a template t is a type name in the declaration. Thus the vector becomes parameterised class
with the type t as the parameter. We can create vector for holding different datatypes like the vector
can be int vector or float vector.
A class which is created from a class template is called a template class. If we want to create the
object of template, the syntax is
classname <type> objectname(args list);
OR
classname <type>objectname;

12.3 Class Templates with Multiple Parameters


We can use more than one generic data type in a class template. They are declared as a comma-
separated list within the template, specification is as shown below.
template <class T1, class T2>
class classname
{ ________
________
________
________ {Body of the class}
};
176  OOPs with C++ Programming

Example:
# include<iostream.h>
template<class T1, class T2>
class test
{
T1 a;
T2 b;
public:
Test(T1 x, T2 y)
{
a=x;
b=y;
}
void show()
{
cout<<a<<“and”<<b<<endl;
};
void main()
{
Test <float,int> test1(1.23,123);
Test <int,char> test2(100,’W’);
[Link]();
[Link]();
getch();
}
Output of program:
1.23 and 123
100 and W

12.4 Function Templates


Template is a method for writing a single function or class for a family of similar functions or
classes in a generic manner. When a single function is written for a family of similar functions. It is
called as a ‘function template’.
Like a class templates, we can also define function templates that is used to create a family of
functions with different arguments types.
Syntax of function template
template<class T>
returntype functionname(arguments of type T)
{ ________
________
Templates  177

________
________ // body of function with type T wherever
appropriate
}
The function template syntax is similar to that of the class template except that we are defining
functions instead of classes. We must use the template parameter T as and when necessary in the
function body and in its argument list.
Example:
# include<iostream.h>
# include<conio.h>
template<class T>
void swap(T &x, T &y)
{
T temp=x;
x=y;
y=temp;
}
void fun(int m, int n, float a, float b)
{
cout<<“m and n before swap:”<<m<<“ ”<<n<<endl;
swap (m,n);
cout<<“m and n after swap:”<<m<<“ ”<<n<<endl
cout<<“a and b before swap:”<<a<<“ ”<<b<<endl;
swap(a,b);
cout<<“a and b after swap:”<<a<<“ ”<<b<<endl;
}
void main()
{
fun(100,200,11.22,33.44);
getch();
}
Output of the program is
m and n before swap 100 200
m and n after swap 200 100
a and b before swap 11.22 33.43
a and b after swap 33.43 11.22
Program consist of swap() function template that will swap two values of a given type of data.
This template function declares a set of overloaded functions, one for each type of data. We can
invoke or call swap() function like any ordinary function.
178  OOPs with C++ Programming

For example, fun() is ordinary function having four parameters. Within this ordinary function we
can call swap() functions.

12.5 Function Templates with Multiple Parameters


Like template classes, we can use more than one generic data type in the template statement,
using comma-separated.
syntax is
template<class T1, class T2, …>
returntype functionname(arguments of types T1, T2, …)
{ ________
________
________
________ (Body of function)
}
Example:
# include<iostream.h>
# include<string.h>
template<class T1, class T2>
void display(T1 x, T2 y)
{
cout<<x<<“ ”<<y<<endl;
}
void main()
{
display (1999, “ABC”);
display (12.34, 1234);
getch();
}
Output
1999 ABC
12.34 1234

12.6 Overloading of Template Functions


Like function overloading, a template function can be overloaded either by template functions or
ordinary functions of its name.
Following rules are followed for overloading of template functions:
1. Call an ordinary function that has an exact match.
2. Call a template function that could be created with an exact match.
3. Try normal overloading resolution to ordinary functions and call the one that matches.
Templates  179

Example shows template function is overloaded with an explicit function.


# include<iostream.h>
# include<string.h>
template<class T>
void display(T x)
{
cout<< “Template display:”<<x<<endl;
}
void display(int x)
{
cout<<“Explicit display”<<x<<endl;
}
void main()
{
display(100);
display(12.34);
display(‘c’);
getch();
}
Output:
Explicit display : 100
Template display : 12.34
Template display : c

12.7 Member Functions Templates


When we created a class template for vector, all the member functions were defined as inline
which was not necessary. We can define them outside the class as well, member functions of template
classes themselves are parameterised by the type argument and therefore these functions must be
defined by the function templates:
Syntax:
Template<class T>
returntype classname<T>::functionname(arg list)
{ ________
________
________
________ // function body
}
180  OOPs with C++ Programming

Example:
template <class T>
class vector
{
T* V;
int size;
public:
vector (int m);
vector (T* a);
T operator * (vector & y);
};
// member function templates …
template<class T>
vector<T>::vector(int m)
{
v=new T[size=m];
for(int i=0; i<size; i++)
{
v[i]=0;
}
}
template<class T>
vector<T>::vector(T* a)
{
for(int i=0; i<size; i++)
{
v[i] = a[i];
}
}
template<class T>
T vector<T>::Operator * (vector &y)
{
T sum=0;
for(int i=0; i<size, i++)
{
sum+=thisv[i] * y.v[i];
}
return sum;
}
In above program the class vector has member functions which are declared within a class they
are redefined outside class vector. Member functions are parameterised member function.
Templates  181

12.8 Non-Type Template Arguments


Template can have multiple arguments but it is possible that we can specify non-type arguments.
In addition to the argument T, we can also use other arguments that can be strings, function name,
constant expressions and built-in-types.
Syntax:
template<class T, int size>
class array
{
T a[size]; //automatic array initialisation
________
________
________
________
};
This template supplies the size of the array as an argument. The size of the array is known to the
compiler at the compile time itself.
Example:
array<int, 10>a1; // Array of 10 integers
array<float, 5>a2; // Array of 5 floats
array<char, 20>a3; // String of size 20
Example:
# include<iostream.h>
# include<stdlib.h>
template<class AType, int size>
class atype
{
AType a[size];
public:
atype()
{
register inti;
for(i=0; i<size, i++)
{
a[i]=i;
}
}
Atype & operator[] (int i);
};
// Providing Range Checking for atype
182  OOPs with C++ Programming

template<class
AType, int size>
AType & atype<AType,size>::operator[](int i)
{
if(i<0 || i>size–1)
{
cout<<“Index value of”<<i<<“is out of bound”
<<endl;
exit(1);
}
return a[i];
}
void main()
{
atype<int, 10>intob; //integer array of size 10
int i;
cout<<“Integer array”;
for(i=0; i<10; i++)
{
intob[i]=i;
}
for(i=0; i<10; i++)
{
cout<<intob[i]<<“ ”;
}
getch();
}

Question Bank for Self-Practice


1. Explain concept of template with its advantages.
2. Explain class template and function template with example.
3. What is difference between template and Macro?
4. Distinguish between overloaded functions and function templates.
5. Explain Class Template with parameters.
6. Explain Function Templates with multiple parameters.
7. Explain how the member functions of template can be defined with example.
8. Explain Non-type template Arguments.


13 Exception Handling

Chapter

Chapter Outline
13.1 Introduction and Basics of Exception Handling
13.2 Exception Handling Mechanism with Try, Catch & Throw Statement
13.3 Multiple Catch Statements
13.4 Rethrowing and Exception
13.5 Specifying Exception
13.6 Advantages of Exception Handling

13.1 Introduction and Basics of Exception Handling


Normally the program consist of errors and bugs. The most common type of bugs are:
1. Logical error
2. Syntactic error
Logical error is due to wrong solution or wrong logic and syntactic error occurs due to poor
understanding of language, that means syntax mistake. We can detect these errors and then can debug
them and accordingly can provide error description for those errors and these are called as exceptions.
Exceptions are run-time condition or error that a program may encounter while executing. Errors
like division by 0 or access to an array outside of its bounds or running out of memory or running out
of disk space.
There are two types of exception handling:
1. Synchronous
2. Asynchronous
A synchronous exceptions out of range index and overflow error can occur. In Asynchronous the
events which are beyond the control like keyboard interrupts or bad sectors in the disc or hardware
failure are called as asynchronous exceptions.
184  OOPs with C++ Programming

The following task can be performed for exception.


1. Find the problem (hit the exception)
2. Inform that an error has occurred (throw the exception)
3. Receive the error information (catch the exception)
4. Take corrective action (handle the exception)

13.2 Exception Handling Mechanism With Try, Catch & Throw Statement
An exception is an error or an unexpected event. The exception handler is a set of codes that
executes when an exception occurs.
Exception handling uses basically 3 blocks:
(i) Try (ii) Throw, (iii) Catch.
The try & catch blocks are written between open & closing curly braces ‘{ }’. The try block is
identified by try keyword having block of statements between {and}. When the exception is detected
by the try block, it is thrown using throw statement in try block.
A catch block is defined by the keyword catch followed by { } with block of statement. This
catch block catches the exception thrown by throw statement in try block and handles it appropriately.
When the try block throws an exception the program control leaves the try block and enter into the
catch block and if the type of object thrown by the try block matches then only the catch block is
executed for handling exception. If they do not match, the program is aborted using abort function.
Example:
void main()
{
int a,b;
cout<<“enter value of a & b”;
cin>>a>>b;
int x=a–b;
try
{
if(x!=0)
{
cout<<“Result of division is”<<(a/x);
}
else
{
throw(x);
}
}
catch(int i)
{
cout<<“exception at x=”<<x;
Templates  185

cout<<“The denominator is 0 hence it is not


possible & it is called division by 0
exception”;
}
getch();
}
Throw p oint

Function that
c aus es a n
e xc eption In vo ke
function

Try block

In vo kes a fu nc tion
tha t c ontain s an
e xception .
Th row
exc eption

Ca tch block
C atch es an d
handles th e
e xc eption

Figure
Syntax (general format of try catch block)
type function (argument list)
{ ________
________
________
________
throw(object) //throw exception
________
________
________
________
}
________
________
________
________
try
{ ________
________
________
186  OOPs with C++ Programming

________ Invoke function here


}
catch (type org) // catches exception
{ ________
________
________
________ Handles exception here
}

13.3 Multiple Catch Statements


The program segment can have more than one condition to throw an exception. In such cases we
can have more than one catch blocks, that means one try block can have multiple catch blocks. When
an exception is thrown the exception handlers are searched in order for an appropriate match, if the
handler searches proper exception match then that catch block is executed. After executing the catch
block, the control is transferred to the next statement of the try block and when match is not found the
program is terminated. The catch block can have a single argument to catch thrown information.
General Format of Multiple Catch Statements/Blocks:
try
{
// try block
}
catch(type1 arg)
{
// catch block1
}
catch(type2 arg)
{
// catch block2
}
________
________
________
________
catch(type N arg)
{
// catch blockN
}
Example:
# include<iostream.h>
# include<conio.h>
void test(int x)
Templates  187

{
try
{
if(x==1)
{
throw x;
}
else
{
if(x==0)
{
throw x;
}
else
{
if (x==–1)
{
throw 1.0
}
cout<<“end of try block”;
}
catch(char c)
{
cout<<“caught a character”;
}
catch(int m)
{
cout<<“caught an integer”;
}
catch(double d)
{
cout<<“caught a double”;
}
cout<<“end of try catch block”;
}
void main()
{
cout<<“for x=1” <<endl;
test(1);
cout<<“for x=0”<<endl;
test(0);
188  OOPs with C++ Programming

cout<<“for x=–1”<<endl;
test(–1);
cout<<“for x=2”<<endl;
test(2);
getch();
}

13.4 Rethrowing and Exception


A catch handler will decide to rethrow the exception caught without processing. In such situation
we have to simply write throw keyword followed by semicolon (;) without arguments.
throw;
This statement calls the current exception to be thrown to the next enclosing try catch block. But
the prototype or format of the next catch block should match.
If we wish to rethrow an exception from within an exception handler, we may do so by calling
throw, by itself, with no exception. This causes current exception to be passed to an outer try/catch
sequence. It allows multiple handlers access to the exception.
An exception can only be rethrown from within a catch block. When you rethrow an exception, it
will not be recaught by the same catch statement. It will propogate outward to the next catch statement.
Example:
# include<iostream.h>
# include<conio.h>
void divide (double x, double y)
{
cout<<“Inside function”;
try
{
if (y==0.0)
throw y;
else
cout<<“division=”<<x/y;
}// end of try block
catch(double)
{
cout<<“caught double inside the function”;
throw;
}// end of catch block
cout<<“end of function”;
} //end of function divide
void main()
Templates  189

{
cout<<“Inside main function”;
try
{
divide(10.5,2.0);
divide(20.0,0.0);
}
catch(double)
{
cout<<“caught double inside the main
function”;
}
cout<<“end of main”;
getch();
}

13.5 Specifying Exception


You can restrict the type of exceptions that a function can throw outside of itself. We can also
prevent a function from throwing any exceptions whatsoever. It is possible to restrict a function to
throw only certain specified exceptions. This can be achieved by adding throw clause to a function
definition.
The general form of using specific exception is as given below:
ret-type function-name(arg-list) throw (type-list)
{ ________
________
________
________ function body
}
The type-list specifies the type of exceptions that may be thrown. In the type-list we have to
specify the data type list separated by comma that may be thrown by the function. Throwing any other
type of expression will cause abnormal program termination. If we wish to prevent a function from
throwing any exception, we may do so by making the type-list empty. Hence this empty type-list
function will not throw any exception.
Attempting to throw an exception that is not supported by a function will cause.
The standard library function unexpected () to be called.
The unexpected() function is called when a function attempts to throw an exception that is not
allowed by its throw list. By default, unexpected() calls terminate(). The terminate() function is called
whenever the exception handling subsystem fails to find a matching catch statement for an exception.
terminate() is the handler of last resort when no other handlers for an exception are available. By
default terminate() calls abort() hence abnormal termination of program occurs.
190  OOPs with C++ Programming

Example:
void test(int x) throw(int, double)
{
if(x==0) throw ‘x’; // char
else
if(x==1) throw x; // int
else
if(x==–1) throw 1.0; // double
cout<<“end of function block/n”;
}
void main()
{
try
{
cout<<“Testing Throw Restriction”<<endl;
cout<<“x==0”<<endl;
test(0);
cout<<“x==1”<<endl;
test(1);
cout<<“x==–1”<<endl;
test(–1);
cout<<“x==2”<<end1;
test(2);
}
catch(char c)
{
cout<<“caught a character”<<endl;
}
catch(int m)
{
cout<<“caught an integer”<<endl;
}
catch(double d)
{
cout<<“caught a double”<<endl;
}
cout<<“End of try-catch system”;
getch();
}
Templates  191

Output:
Testing Throw Restrictions
x==0
caught a character
End of try-catch system
In above example, test function is called by passing value of x=0, in the test function if the value
of x is zero then it with character ‘x’, catch block catches it and displays a message caught a character
and terminate the loop because in test function with the throw clause type-list specifies only int and
double exception should be thrown but the character is not listed in type-list hence program will be
terminated.

13.6 Advantages of Exception Handling


1. With the help of exception we can detect logical as well as syntactic errors.
2. With the help of exception at the Run time we can catch the error and throw the error
message to the user.
3. The exception handling provides type safe integrated approach.
4. The synchronous exceptions can be created by the user, hence user can control the program.
5. The main advantage of exception handling mechanism is to detect an exception and report
on exception circumstances so that the user can take appropriate action.
6. One program segment can have multiple conditions, all these multiple conditions can be
handled by multiple catch blocks that means one try block can have multiple catch blocks.
7. The exceptions are divided into 3 Modulus. Try block, throw statement, catch block. Hence
it supports Modularisation.
8. Exception handling supports Rethrowing an exception from one catch block to another catch
block.
9. The exception handling supports certain security on specified exceptions, that means the
restrictions can be applied on throwing exceptions.

Question Bank for Self-Practice


1. What is an exception? When it is needed in the program?
2. How exceptions are handled in C++?
3. Explain try, catch and throw statements.
4. What is Exception? State its two types, explain them with example.
5. Whether multiple catch blocks can be used? Justify your statement with example.
6. Explain how exceptions can be Rethrown with example. What are advantages of Rethrowing exceptions?
7. Explain how we can restrict to a particular exception. OR How we can specify the exceptions to be used?
8. Explain use of unexpected(), terminate() & abort() function. When they are used?
9. What are the advantages of Exception Handling?


14 Standard Template Library

Chapter

Chapter Outline
14.1 Introduction
14.2 Component of STL
14.3 Containers
14.4 Algorithms
14.5 Iterators
14.6 Applications of Container Classes

14.1 Introduction
Templates are used to create generic classes and functions. Templates are used to create classes
(data structures) and functions (algorithms).
The collection of these classes and function is called Standard Template Library (STL).
STL components are part of standard C++ Library defined in the namespace std.
Hence to include this namespace we can write.
using namespace std;
This statement is like include statement. It indicates to the complier that we want to use standard
C++ library.
STL has three foundational items:
(a) Containers (b) Algorithms (c) Iterators.
Containers are object that hold another objects like vector (dynamic array), deque (double-ended
queue) and linear list.
Algorithms act on containers. They provide the means by which you will manipulate the content
of containers. Here sorting, searching of contents of containers can be done.
Iterators are objects that act, more or less, like pointers.
Standard Template Library  193

14.2 Component of STL


The STL contains several components. It’s core has three key components.
1. Containers
2. Algorithms
3. Iterators
These three components work in conjunction with one another to provide support to a variety of
programming solutions.
Container
Algorithm 1 Algorithm 2

iterator 1 iterator 2

object 1 object 2

object 3

iterator 3

Algorithm 3

Algorithms employ iterators to perform operations stored in containers.


1. Contain is an object that actually stores data and containers are objects that hold other
objects. It is a way data is organised in memory.
The STL containers are implemented by easily customised to hold different types of data.
2. Algorithms  Algorithms act on containers. They provide the means by which you will
manipulate the contents of containers. An algorithm is a procedure that is used to process the
data contained in the containers. The STL includes many different kinds of algorithms to
provide support to tasks such as initializing, searching, copying, sorting and merging.
Algorithms are implemented by template functions.
3. Iterators  Iterators are objects that acts, more or less like pointers. Iterator is a pointer that
points to an element in a container. We can use iterators to move through the contents of
containers. Since iterators are like pointers, we can increment or decrement them. Iterators
connect algorithms with containers and play a key role in the manipulation of data stored in
the containers.

14.3 Containers
Containers are objects that hold other objects of same type. It contains vector class, defines
dynamic array, deque create double ended queue and list provides a linear list.
The STL defines ten containers which are grouped into three categories
194  OOPs with C++ Programming

Con tainers

(A) (B) (C)

Sequ ence Asso ciative Derived


contain ers contain ers contain ers
• vecto r • set • stack
• d eq ue • m u ltiset • q ueue
• list • m ap • p riority-
• m u ltim ap q ueue

Sequence Containers:
Vector is a dynamic array. It allows insertions and deletions at back, permits direct access to any
element. List is linear list, allows insertions and deletion anywhere. deque is double-ended queue,
allows insertions and deletions at both the ends, permits direct access to any element.
Associative Containers:
Set  It is an associate container for storing unique sets. No duplication is allowed. It allows
rapid Lookup & Search.
Multiset  It is an associate container for storing non-unique sets. (Duplicate allowed)
Map  An associate container for storing unique key/value pairs. Each key is associated with
only one value (one-to-one mapping).
Multimap  It is an associate container for storing key/value pairs in which one key may be
associated with more than one value (one-to-many mapping). Allows key-based Lookup.
Derived Containers:
1. stack  A standard stack LAST IN FIRST OUT (LIFO).
2. queue  A standard queue FIRST IN FIRST OUT (FIFO).
3. priority queue  A priority queue. The first element out is always the highest priority
element.
(A) Sequence Containers:
(i) Sequence containers store elements in a linear sequence.
(ii) Each element is related to other elements by its position along the line.
(iii) These all elements can expand themselves to allow insertion of elements and number of
operations can be applied.
elem ent 0 elem ent 1 elem ent 2 last elem en t

Iterator

begin() end()

(iv) STL provides three types of sequence containers: (1) vector (2) list (3) deque as already
explained.
(B) Associative Containers:
Associative Containers are designed to support direct assess to elements using keys. They are not
sequential.
Standard Template Library  195

There are four types of associative containers:


1. set
2. multiset
3. map
4. multimap
All these containers stores a data in a structure called tree, through that fast searching, deletion
and insertion can be possible.
Set and Multiset Containers can store a number of items and provide operations for manipulating
them using values as the keys. If we want to search for a particular student name details, the name is
the Key to Search Record. Set does not allow duplicate items whereas multiset allow duplicate sets.
(C) Derived Containers
The STL provides three derived containers namely stack, queue and priority queue. They are also
known as container adaptors.
Stacks, queues and priority queues can be created from different sequence containers. The
derived containers can not be used for Data Manipulation.
Hence they support two member functions pop() and push() for implementing, deleting and
inserting operations.

14.4 Algorithms
Algorithms are functions that can be used generally across a variety of containers for processing
their contents.
Each container provides functions for its basic operations.
A standard algorithms provide more extended or complex actions.
In this we can work with two different types of containers at the same time.
STL has different algorithms, and these algorithms are template functions and can be applied to
any type of container.
STL algorithms are categorised as follows:
1. Retrieve or non-mutating algorithms
2. Mutating algorithms
3. Sorting algorithms
4. Set algorithms
5. Relational algorithms
1. Retrieve OR Non Mutating Algorithms:
(a) adjacent_find(): This method finds adjacent pair of objects that are equal.
(b) count(): This method counts occurence of a value in a sequence.
(c) count_if(): It counts number of elements based on condition.
(d) equal(): This method returns true if two ranges are the same.
(e) find(): This method finds first occurence of a value in sequence.
(f) find_end(): This method finds last occurence of a value in sequence.
196  OOPs with C++ Programming

(g) for_each(): This method applies operation to each element.


(h) mismatch(): It finds first elements for which two sequences differ.
(i) search ()  This method searches within a sequence.
(j) search_n(): This method finds a sequences of a specified number of similar elements.
2. Mutating Algorithms:
(a) copy()  This method copies a sequence.
(b) copy_backward()  This method copies a sequence from the end.
(c) fill()  This method fills a sequence with a specified value.
(d) fill_n()  This method fills first n elements with a specified value.
(e) generate()  It replaces all elements with the result of an operation.
(f) iter_swap()  This method swaps elements pointed by iterators.
(g) remove()  This method deletes elements of a specified value.
(h) remove_copy  It copies a sequence after removing elements matching.
(i) replace()  It replaces elements with a specified value.
(j) reverse()  It reverses the order of elements.
(k) rotate()  This method rotates elements.
(l) swap()  This method swap two elements.
(m) swap_ranges()  swap two sequences.
(n) transform()  This method applies an operation to all elements.
(o) unique()  Deletes equal adjacent elements.
(p) unique_copy()  This method copies after removing equal adjacent elements.
3. Sorting algorithms:
(a) binary_search  This method conducts binary search on an ordered sequence.
(b) merge()  It mergers two sorted sequence.
(c) sort()  sorts a sequence.
(d) sort_heap()  It sorts a heap.
(e) partial_sort()  Sorts part of a sequence.
(f) pop_heap()  It deletes the top element.
(g) push_heap()  It adds a element to heap.
(h) upper_bound()  Finds the last occurence of a specified value.
4. Set Algorithms:
(a) include()  It finds whether a sequence is a subsequence of another.
(b) set_difference()  It constructs a sequence that is difference of two ordered sets.
(c) set_union()  It produces sorted union of two ordered sets.
5. Relational Algorithms:
(a) equal()  It finds whether two sequences are the same.
(b) max()  Gives maximum of two values.
(c) max_element()  Finds the maximum element within a sequence.
(d) min()  Gives minimum of two values.
(e) min_elements()  Finds the minimum element within a sequence.
Standard Template Library  197

14.5 Iterators
Iterators are like pointers, they are used to access container elements. These pointer while
accessing container elements can move or traverse from one element to another.
Traversing form one element to another element is known as Iterating through the container.
While Iterating pointer can traverse forward only or may be backward also.
Iterator & their characteristics:
Iterator Access method Direction of movement I/O Capability Remark
1. Input Linear Forward only Read only Cannot be saved
2. Output Linear Forward only Write only Cannot be saved
3. Forward Linear Forward only Read/Write Can be saved
4. Bidirectional Linear Forward only Read/Write Can be saved
5. Random Random Forward & Backward Read/Write Can be saved
Only sequence associative containers are traversable with iterators.
Each type of iterator is used for performing specific functions.
Ra ndom acce ss

bidire ctiona l

forw ard

In put O utput

Functionality Venn diagram of iterators.


The input and output iterators support the least functions. They are used only to traverse in a
container. The forward iterator supports all operations of input and output iterators and retains the
position in the container. A bidirectional iterator supports forward as well backward direction in the
container.
A random access iterator combines the functionality of a bidirectional iterator with an ability to
iump to an arbitary or specific location.

14.6 Applications of Container Classes


Application of container class has namely:
1. vector
2. list
3. map
1. vector  The vector is most widely use container. It stores elements in contiguous memory
locations and enables direct access to any element using the subscript operator [ ].
A vector can change the size dynamical and allocates memory locations as needed at Run time.
class vector supports a number of constructor for creating vector objects.
198  OOPs with C++ Programming

In vector class the following member functions are supported.


1. begin 2. clear 3. capacity 4. size 5. swap 6. Resize
7. end 8. erase 9. empty 10. back 11. insert
2. List  The list is another container. It supports bidirectional, linear list and provides an
efficient implementation for deletion and insertion operations.
It does not supports as random access.
A list can be accessed sequentially only. List supports input, output, forward and bidirectional
iterators can operate in a list.
Common functions used are:
1. back 2. begin 3. clear 4. empty 5. end 6. erase
7. insert 8. merge 9. remove 10. resize 11. size 12. Sort
13. swap 14. unique 15. pop-back 16. pop-front 17. push-back 18. push-front
3. Maps  A map is a sequence (Key, Value) pairs where a single value is associated with each
unique key.
Retrival of values is based on the key and is very fast.
It is normally called as associative array.
The key specified using subscript operator [ ].
Key 1 Va lue 1

Ke y 2 V alue 2

Ke y N Value N

The common functions used are:


1. begin 2. clear 3. empty 4. end 5. erase
6. find 7. insert 8. size 9. swap

Question Bank for Self-Practice


1. Explain STL Library in detail.
2. Explain component of STL in C++.
3. Explain Algorithms component of STL in detail.
4. Explain three different categories.
(a) sequential
(b) associative
(c) derived
5. Explain Iterators in detail.
6. Define what are the applications of container classes.


Practical List
A. Write Programs to Illustrate Simple C++ Concepts without Classes.
Q.1 Write C++ program to print sum and average of 3 numbers.
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c,sum;
float avg;
cout<<”Enter three numbers”<<endl;
cin>>a>>b>>c;
sum=a+b+c;
avg=sum/3.0;
cout<<”The sum of three numbers is”<<sum<<endl;
cout<<”The Average of three numbers is”<<avg;
getch();
}
Output:
Enter three numbers
10 18 02
The sum of three numbers is 30
The Average of three numbers is 10

Q.2 Write C++ program to print greatest of 3 numbers using nested if.
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
cout<<”Enter three numbers”<<endl;
cin>>a>>b>>c;
if(a>b)
{
200  OOPs with C++ Programming

If(a>c)
{
Cout<<a<<”is greater”;
}
}
If(b>a)
{
If(b>c)
{
Cout<<b<<”is greater”;
}
}
If(c>a)
{
If(c>b)
{
Cout<<c<<”is greater”;
}
}
gecth();
}
Output:
Enter three numbers
10 18 02
18 is greater

Q.3 Write C++ program to print greatest of 3 numbers using logical operators.
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
cout<<”Enter three numbers”<<endl;
cin>>a>>b>>c;
if(a>b && a>c)
{
Cout<<a<<”is greater”;
Practical List  201

}
elseif(b>a && b>c)
{
Cout<<b<<”is greater”;
}
else
{
Cout<<c<<”is greater”;
}
getch();
}
Output:
Enter three numbers
19 18 02
19 is greater

Q.4 Write C++ program to accept 3 subjects marks from user (Assuming of 100 marks paper)
calculate total, percentage & print grade accordingly.
Per Grade
75 and above Distinction
60 and 74 Ist class
50 and 59 IInd class
40 and 49 Pass class
Below 40 Fail
#include<iostream.h>
#include<conio.h>
void main()
{
int m1,m2,m3,tot;
float per;
clrscr();
cout<<”Enter three subjects marks”<<endl;
cin>>m1>>m2>>m3;
tot=m1+m2+m3;
per=tot/3.0;
if (per>=75)
cout<<”Distinction”;
else if (per>=60 && per<75)
cout<<”Ist class”;
else if ( per>=50 && per <=59)
202  OOPs with C++ Programming

cout<<”IIns class”;
else if ( per>=40 && per<=49)
cout<<”Pass class”;
else
cout<<”Fail”;
getch();
}
Output:
Enter three subjects marks
80 90 80
Distinction

Q.5 Write C++ program to print even numbers integers between 1 to 100
#include<iostream.h>
#include<conio.h>
void main()
{
int i,j,prime;
clrscr();
cout<<"The Even numbers from 1 to 100 are"<<endl;
for(i=1;i<=100;i+=2)
{
cout<<i<<" ";
}
Output:
The Even numbers from 1 to 100 are
2 4 6 8 10 12 14 16 18 20
22 24 26 28 30 32 34 36 38 40
42 44 46 48 50 52 54 56 58 60
62 64 66 68 70 72 74 76 78 80
82 84 86 88 90 92 94 96 98 100

Q.6 Write C++ program to print odd numbers integers between 1 to 100.
#include<iostream.h>
#include<conio.h>
void main()
{
int i,j,prime;
clrscr();
Practical List  203

cout<<"The Even numbers from 1 to 100 are"<<endl;


for(i=1;i<=100;i+=2)
{
cout<<i<<" ";
}
cout<<"\n\n"<<"The Odd numbers from 1 to 100 are"<<endl;
for(i=2;i<=100;i+=2)
{
cout<<i<<" ";
}
Output:
The Odd numbers from 1 to 100 are:
1 3 5 7 9 11 13 15 17 19
21 23 25 27 29 31 33 35 37 39
41 43 45 47 49 51 53 55 57 59
61 63 65 67 69 71 73 75 77 79
81 83 85 87 89 91 93 95 97 99
The Odd numbers from 1 to 100 are
2 4 6 8 10 12 14 16 18 20
22 24 26 28 30 32 34 36 38 40
42 44 46 48 50 52 54 56 58 60
62 64 66 68 70 72 74 76 78 80
82 84 86 88 90 92 94 96 98 100

Q.7 Write C++ program to print prime integers between 1 to 100.


#include<iostream.h>
#include<conio.h>
void main()
{
int i,j,prime;
clrscr();
cout<<"\n\n"<<"The Prime numbers from 1 to 100 are"<<endl;
for(i=1;i<=100;i++)
{
prime=1;
for(j=2;j<=i-1;j++)
{
if(i%j==0)
{
prime=0;
204  OOPs with C++ Programming

break;
}
}
if(prime==1)
{
cout<<i<<" ";
}
}
getch();
}
Output:
The Prime numbers from 1 to 100 are
1 2 3 5 7 11 13 17 19
23 29 31 37 41 43 47 53 59
61 67 71 73 79 83 89 97

Q.8 Write C++ program to print factorial of a number.


#include<iostream.h>
#include<conio.h>
#include<iostream.h>
#include<conio.h>
void main()
{
long i,j,n,fact=1;
clrscr();
cout<<"Enter a number"<<endl;
cin>>n;
for(i=1;i<=n;i++)
{
fact=fact*i;
}
cout<<"The factorial of a number is"<<fact;
getch();
}
Output:
Enter a number
5
The factorial of a number is120
Enter a number
Practical List  205

8
The factorial of a number is40320

Q.9 Write C++ program to print even numbers, odd numbers & prime integers between 1 to 100
in one program.
void main()
{
int i,j,prime;
clrscr();
cout<<"The Even numbers from 1 to 100 are"<<endl;
for(i=2;i<=100;i+=2)
{
cout<<i<<" ";
}
cout<<"\n\n"<<"The Odd numbers from 1 to 100 are"<<endl;
for(i=1;i<=100;i+=2)
{
cout<<i<<" ";
}
cout<<"\n\n"<<"The Prime numbers from 1 to 100 are"<<endl;
for(i=1;i<=100;i++)
{
prime=1;
for(j=2;j<=i-1;j++)
{
if(i%j==0)
{
prime=0;
break;
}
}
if(prime==1)
{
cout<<i<<" ";
}
}
getch();
}
206  OOPs with C++ Programming

Output:
The Even numbers from 1 to 100 are
2 4 6 8 10 12 14 16 18 20
22 24 26 28 30 32 34 36 38 40
42 44 46 48 50 52 54 56 58 60
62 64 66 68 70 72 74 76 78 80
82 84 86 88 90 92 94 96 98 100
The Odd numbers from 1 to 100 are
1 3 5 7 9 11 13 15 17 19
21 23 25 27 29 31 33 35 37 39
41 43 45 47 49 51 53 55 57 59
61 63 65 67 69 71 73 75 77 79
81 83 85 87 89 91 93 95 97 99
The Prime numbers from 1 to 100 are
1 2 3 5 7 11 13 17 19 23
29 31 37 41 43 47 53 59 61 67
71 73 79 83 89 97

Q.10 Write C++ program to give example of switch case by accepting a character from the user.
/* Program : The switch statement */
#include <iostream.h>
void main()
{
char c ;
cout<<"Enter any one character from the word 'worry': ";
cin>>c;
switch (c)
{
case 'W':
case 'w':cout<<"I am in case w\n";
break ;
case 'O':
case 'o':cout<<"I am in case o\n";
break ;
case 'R':
case 'r':cout<<"I am in case r\n";
break ;
case 'Y':
case 'y':cout<<"I am in case y\n";
break ;
Practical List  207

default:cout<<"U entered the wrong letter !!\n";


}
}
Output:
Enter any one character from the word 'worry': ";
W
I am in case w

Q.11 Write C++ program to give example of Airthmertic, Relational & Logical operations using
switch case by providing menu driven facility.
/* Program: The switch statement */
#include <iostream.h>
#include<conio.h>
void main()
{
int select , choice , x , y , i ;
clrscr();
cout<<"Enter any two integer values : ";
cin>>x>>y;

cout<<"\nVarious Operators : \n";


cout<<"=================\n";

cout<<"1. Arithmetic\n";
cout<<"2. Relational\n";
cout<<"3. Logical\n";

cout<<"Enter your choice :\n";


cin>>select;
switch (select)
{
case 1 :cout<<"\tMenu-Arithmatic operations\n";
cout<<"1. Addition\n";
cout<<"2. Subtraction\n";
cout<<"3. Division\n";
cout<<"4. Multiplication\n";
cout<<"5. Modulus\n";
cout<<"Enter your choice : ";
cin>>choice;
208  OOPs with C++ Programming

switch (choice)
{
case 1 : cout<<"Addition of "<<x<<" and "<<y<<" : "<<x+y;
break ;
case 2 : cout<<"Subtraction of "<<x<<" and "<<y<<" : "<<x-y;
break ;
case 3 : cout<<"Division of "<<x<<" and "<<y<<" : "<<float(x)/float(y);
break ;
case 4 : cout<<"Multiplication of "<<x<<" and "<<y<<" : "<<x*y;
break ;
case 5 : cout<<"Modulus of "<<x<<" and "<<y<<" : "<<x%y;
break ;
default : cout<<"Wrong choice !!";
}
break ;
case 2 : cout<<"\tMenu-Relational opeations\n";
cout<<"1. Greater than\n";
cout<<"2. Less than\n";
cout<<"3. Equal to\n";
cout<<"4. Less than or equal to\n";
cout<<"5. Greater thn or equal to\n";
cout<<"Enter your choice : ";
cin>>choice;
switch (choice)
{
case 1 :
cout<<"Result of x greater than y : "<<(x>y);
break ;
case 2 :
cout<<"Result of x less than y : "<<(x<y);
break ;
case 3 :
cout<<"Result of x equal to y : "<<(x==y);
break ;
case 4 :
cout<<"Result of x less than or equal to y : "<<(x<=y);
break ;
case 5 :
cout<<"Result of x greater than or equal to y : "<<(x>=y);
Practical List  209

break ;
}
break ;
case 3 : cout<<"\tMenu-Logical operations\n";
cout<<"1. Logical AND\n";
cout<<"2. Logical OR\n";
cout<<"Enter your choice : ";
cin>>choice;
switch (choice)
{
case 1 :
cout<<"Result of x AND y : "<<(x&&y);
break ;
case 2 :
cout<<"Result of x OR y : "<<(x||y);
break ;
}
break ;
}
getch () ;
}
Output:
Enter any two integer values
42
1. Arithmetic
2. Relational
3. Logical
Enter your choice
1
Menu-Arithmatic operations
1. Addition
2. Subtraction
3. Division
4. Multiplication
5. Modulus
Enter your choice
cin>>choice
1
Addition of 4 and 2 : 6
210  OOPs with C++ Programming

Q.12 Write C++ program to print following pattern.


1
12
123
1234
Answer:
#include<iostream.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
cout<<j<<" ";
}
cout<<endl;
}
getch();
}

Q.13 Write C++ program to print following pattern.


1
12
123
1234
Answer:
#include<iostream.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
Practical List  211

cout<<j<<" ";
}
cout<<endl;
}
getch();
}

Q.14 Write C++ program to print following pattern.


4444
333
22
1
Answer:
#include<iostream.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=4;i>=1;i--)
{
for(j=1;j<=i;j++)
{
cout<<i<<" ";
}
cout<<endl;
}
getch();
}

Q.15 Write C++ program to print following pattern.


1
22
333
4444
Answer:
#include<iostream.h>
#include<conio.h>
void main()
212  OOPs with C++ Programming

{
int i,j;
clrscr();
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
cout<<i<<" ";
}
cout<<endl;
}
getch();
}

Q.16 Write C++ program to print following pattern.


****
***
**
*
Answer:
#include<iostream.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=4;i>=1;i--)
{
for(j=1;j<=i;j++)
{
cout<<"*"<<" ";
}
cout<<endl;
}
getch();
}
Practical List  213

Q.17 Write C++ program to print following pattern.


1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
Answer:
#include<iostream.h>
#include<conio.h>
void main()
{
int r,c,s;
clrscr();
for(r=1;r<=6;r++)
{
for(s=1;s<=(6-r);s++)
{
cout<<" ";
}
for(c=1;c<=r;c++)
{
cout<<r;
cout<<" ";
}
cout<<"\n";
}
getch();
}

B. Write C++ Programs to Illustrate Concepts Pointers, Functions and Function


Overloading Classes.
Q.1 Write C++ program to area of circle using function.
#include<iostream.h>
#include<conio.h>
void main()
{
float r,a1;
float area(float r1);
214  OOPs with C++ Programming

clrscr();
cout<<"enter radius"<<endl;
cin>>r;
a1=area(r);
cout<<"The area is "<<a1;
getch();
}
float area(float r1)
{
float pi=3.1415,area;
area=pi*r1*r1;
return area;
}
Output:
Enter radius
5
The area is 78.53

Q.2 Write C++ program to print maximum of two numbers using function.
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,m;
int max(int x ,int y);
clrscr();
cout<<"enter the value of a &b"<<endl;
cin>>a>>b;
m=max(a,b);
cout<<"the maximum no. is"<<m;
getch();
}
int max(int x, int y)
{
if(x>y)
{
return x;
}
Practical List  215

else
{
return y;
}
}
Output:
enter the value of a &b
58
the maximum no. is 8

Q.3 Write C++ program to print factorial of a number using function.


#include<iostream.h>
#include<conio.h>
void main()
{
int fa,n;
int fact(int n1);
clrscr();
cout<<"enter a number"<<endl;
cin>>n;
fa=fact(n);
cout<<"the factorial is "<<fa;
getch();
}
int fact(int n1)
{
int f1=1,i;
for(i=1;i<=n1;i++)
{
f1=f1*i;
}
return f1;
}
Output:
enter a number
5
the factorial is 120
216  OOPs with C++ Programming

Q.4 Write C++ program to print sum and average of three numbers using function.
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c;
void sumavg(int x, int y, int z);
clrscr();
cout<<"enter 3 numbers"<<endl;
cin>>a>>b>>c;
sumavg(a,b,c);
getch();
}
void sumavg(int x, int y, int z)
{
int s;
float avg;
s = x+y+z;
avg=s/3.0;
cout<<"The sum of three numbers is "<<s<<endl;
cout<<"The average of three numbers is "<<avg<<endl;
}
enter 3 numbers
80 90 80
The sum of three numbers is 250
The average of three numbers is 83.333

Q.5 Write C++ program to swap two integers, two floats, two characters using function
overloading.
#include<iostream.h>
#include<conio.h>
void swap(int a,int b);
void swap(float a,float b);
void swap(char a,char b);
void main()
{
int x,y;
float fx,fy;
char cx,cy;
clrscr();
cout<<"enter x y"<<endl;
Practical List  217

cin>>x>>y;
cout<<"enter fx fy"<<endl;
cin>>fx>>fy;
cout<<"enter cx cy"<<endl;
cin>>cx>>cy;
swap(x,y);
swap(fx,fy);
swap(cx,cy);
getch();
}
void swap(int a, int b)
{
int temp;
temp=b;
b=a;
a=temp;
cout<<"the value of x is "<<a<<endl;
cout<<"the value of y is "<<b<<endl;
}
void swap(float a, float b)
{
float temp;
temp=b;
b=a;
a=temp;
cout<<"the value of fx is "<<a<<endl;
cout<<"the value of fy is "<<b<<endl;
}
void swap(char a, char b)
{
char temp;
temp=b;
b=a;
a=temp;
cout<<"the value of cx is "<<a<<endl;
cout<<"the value of cy is "<<b<<endl;
}
218  OOPs with C++ Programming

Q.6 Write C++ program to calculate area of circle, area of rectangle, area of right angle triangle
using function overloading
#include<iostream.h>
#include<conio.h>
float area(int r1);
float area(double b1,double h1);
int area(int l1, int b1);
void main()
{
int r,l,b2,a3;
double b,h,a1,a2;
clrscr();
cout<<"enter the radius"<<endl;
cin>>r;
cout<<"enter the breath & height"<<endl;
cin>>b>>h;
cout<<"enter the length & breath"<<endl;
cin>>l>>b2;
a1=area(r);
a2=area(b,h);
a3=area(l,b2);
cout<<"\n the area of circle is "<<a1;
cout<<"\n the area of triangle is "<<a2;
cout<<"\n the area of rectangle is "<<a3;
getch();
}
float area(int r1)
{
float a;
a = 3.1415*r1*r1;
return a;
}
float area(double b1, double h1)
{
float z;
z=0.5*b1*h1;
return z;
}
int area(int l1, int b1)
Practical List  219

{
int z;
z=l1*b1;
return z;
}

Q.7 Write C++ program to give demo pointer variable by displaying the address of variables and
incrementing the addresses of pointer variables.
#include<iostream.h>
#include<conio.h>
void main()
{
int i=3,*x;
float j=1.5,*y;
char k='c',*z;
clrscr();
cout<<"value of i is "<<i<<endl;
cout<<"value of j is "<<j<<endl;
cout<<"value of k is "<<k<<endl;
x=&i;
y=&j;
z=&k;
cout<<"original value of x is "<<x<<endl;
cout<<"original value of y is "<<y<<endl;
cout<<"original value of z is "<<z<<endl;
cout<<"original value of x is "<<*x<<endl;
cout<<"original value of y is "<<*y<<endl;
cout<<"original value of z is "<<*z<<endl;
x--;
y--;
z--;
cout<<"new value of x is "<<x<<endl;
cout<<"new value of y is "<<y<<endl;
cout<<"new value of z is "<<z<<endl;
getch();
}

Q.8 Write C++ program to give demo of pointer Arithmetic.


#include<iostream.h>
#include<conio.h>
void main()
220  OOPs with C++ Programming

{
int i=3,*x;
float j=1.5,*y;
char k='c',*z;
clrscr();
cout<<"value of i is "<<i<<endl;
cout<<"value of j is "<<j<<endl;
cout<<"value of k is "<<k<<endl;
x=&i;
y=&j;
z=&k;
cout<<"original value of x is "<<x<<endl;
cout<<"original value of y is "<<y<<endl;
cout<<"original value of z is "<<z<<endl;
x++;
y++;
z++;
cout<<"new value of x is "<<x<<endl;
cout<<"new value of y is "<<y<<endl;
cout<<"new value of z is "<<z<<endl;
getch();
}

Q.9 Write C++ program to print area & circumference of a circle using functions.
#include<iostream.h>
#include<conio.h>
void arear(int r,float *a,float *c);
void main()
{
int radius;
float area,circum;
cout<<"enter the radius"<<endl;
cin>>radius;
arear(radius,&area,&circum);
cout<<"area is"<<area<<endl;
cout<<"circumference is "<<circum<<endl;
getch();
}
void arear(int r,float *a,float *c)
Practical List  221

{
*a=3.14*r*r;
*c=2*3.14*r;
}

Q.10 Write C++ program to print square of a number using functions.


#include<iostream.h>
#include<conio.h>
void square(int *x);
void main()
{
int a;
cout<<"enter the value of a"<<endl;
cin>>a;
square(&a);
cout<<"the square is "<<a<<endl;
getch();
}
void square(int *x)
{
*x=*x*(*x);
}

Q.11 Write C++ program to declare array elements & display array element through pointer.
#include<iostream.h>
#include<conio.h>
void main()
{
int b[]={10,20,30,40,50};
int i;
for(i=0;i<=4;i++)
{
cout<<*(b+i)<<endl;
}
getch();
}
222  OOPs with C++ Programming

Q.12 Write C++ program to combine two strings using function using pointers.
#include<iostream.h>
#include<conio.h>
#include<string.h>
char *combine(char *,char *);
void main()
{
char a[10],b[10],*p;
strcpy(a,"horse");
strcpy(b,"fly");
p=combine(a,b);
cout<<p;
getch();
}
char *combine(char *s,char *t)
{
int x,y;
char r[100];
strcpy(r,s);
y=strlen(r);
for(x=y;*t!='\0';x++)
{
r[x]=*t++;
}
r[x]='\0';
return r;
}

C. Function Overloading with Class


Q.1 Write C++ program to swap two integers, two floats & two characters using function
overloading with class.
#include<iostream.h>
#include<conio.h>
void swap(int a,int b);
void swap(float a,float b);
void swap(char a,char b);
void main()
{
int x,y;
float fx,fy;
Practical List  223

char cx,cy;
clrscr();
cout<<"enter x y"<<endl;
cin>>x>>y;
cout<<"enter fx fy"<<endl;
cin>>fx>>fy;
cout<<"enter cx cy"<<endl;
cin>>cx>>cy;
swap(x,y);
swap(fx,fy);
swap(cx,cy);
getch();
}
void swap(int a, int b)
{
int temp;
temp=b;
b=a;
a=temp;
cout<<"the value of x is "<<a<<endl;
cout<<"the value of y is "<<b<<endl;
}
void swap(float a, float b)
{
float temp;
temp=b;
b=a;
a=temp;
cout<<"the value of fx is "<<a<<endl;
cout<<"the value of fy is "<<b<<endl;
}
void swap(char a, char b)
{
char temp;
temp=b;
b=a;
a=temp;
cout<<"the value of cx is "<<a<<endl;
cout<<"the value of cy is "<<b<<endl;
}
224  OOPs with C++ Programming

Q.2 Write C++ program to print area of circle, area of rectangle, area of right angle triangle
using function overloading with class.
#include<iostream.h>
#include<conio.h>
float area(int r1);
float area(double b1,double h1);
int area(int l1, int b1);
void main()
{
int r,l,b2,a3;
double b,h,a1,a2;
clrscr();
cout<<"enter the radius"<<endl;
cin>>r;
cout<<"enter the breath & height"<<endl;
cin>>b>>h;
cout<<"enter the length & breath"<<endl;
cin>>l>>b2;
a1=area(r);
a2=area(b,h);
a3=area(l,b2);
cout<<"\n the area of circle is "<<a1;
cout<<"\n the area of triangle is "<<a2;
cout<<"\n the area of rectangle is "<<a3;
getch();
}
float area(int r1)
{
float a;
a = 3.1415*r1*r1;
return a;
}
float area(double b1, double h1)
{
float z;
z=0.5*b1*h1;
return z;
}
int area(int l1, int b1)
Practical List  225

{
int z;
z=l1*b1;
return z;
}

D. Write C++ Programs to Illustrate the Concepts: Classes, Friend Functions.


Q.1 Write C++ program to create a class on Point, member function as to scalar multiply with
Point and Add two points.
Source Code:
#include<iostream.h>
#include<conio.h>
class point
{
int a,b,r1,r2,r3,r4,x;
public:
void input()
{
cout<<"\n Enter Point:";
cin>>a>>b;
}
void display()
{
cout<<"\npoint="<<"("<<a<<"."<<b<<")";
}
void scalar(point h,pointg)
{
cout<<"\n Enter the value of scalar x:";
cin>>x;
r1=x*h.a;
r2=x*h.b;
r3=x*g.a;
r4=x*g.b;
cout<<"Result 1="<<"("<<r1<<","<<r2<<")";
cout<<"Result 2="<<"("<<r3<<","<<r4<<")";
}
void add(point g,point h)
{
r1=g.a+h.a;
r2=g.b+h.b;
cout<<"\n Addition="<<"("<<r1<<","<<r2<<")";
226  OOPs with C++ Programming

}
};
void main()
{
point p1,p2,p3,x1;
cout<<"\n\n";
[Link]();
[Link]();
[Link]();
[Link]();
[Link](p1,p2);
p3scalar(p1,p2);
getch();
}
Output:
Enter Point: 2 3
point=(2.3)
Enter Point: 5 4
point=(5.4)
Addition=(7,7)
Enter the value of scalar x: 6
Result 1=(12,18)
Result 2=(30,24)
Enter Point: 2 3

Q.2 Write C++ program to create a class bill, accept the number of units from the user through
get member function. The amount is calculated on the basic of following slabs:
Units Amount
First 100 60 Rs. Per Unit
Next 100 80 Rs. Per unit
Next 100 90 Rs. Per unit
Above 300 5000 Fix amount
#include<iostream.h>
#include<conio.h>
class bill
{
int unit;
float amt;
public:
void get()
Practical List  227

{
cout<<"enter the units used"<<endl;
cin>>unit;
}
void amount()
{
if(unit<=100)
{
amt=60*unit;
}
else if(unit>100 && unit<=200)
{
amt=60;
unit=unit-100;
amt=amt+(unit*80);
}
else if(unit>200 && unit<=300)
{
amt=60+80;
unit=unit-200;
amt=amt+(unit*90);
}
Else
{
Amt=5000;
}
}
void disp()
{
cout<<"ur amount is "<<amt<<endl<<endl;
}
};
void main()
{
bill b;
[Link]();
[Link]();
[Link]();
getch();
}
228  OOPs with C++ Programming

Q.3 Write a C++ program to create class called Rectangle data members as width, height,
member function to find area and Perimeter.
Source Code:
#include<iostream.h>
#include<conio.h>
class rectangle
{
private:
int h,w;
public:
void input()
{
cout<<"Enter the values of h and w";
cin>>h>>w;
}
void display()
{
cout<<"h-"<<h<<"\tw-"<<w;
}
void area()
{
int area;
area=h*w;
cout<<"\n Area Is:";
cout<<area<<"\n";
}
void peri()
{
int peri;
peri=2*(h+w);
cout<<"Perimeter Is:"<<peri;
}
};
void main()
{
rectangle r;
[Link]();
[Link]();
[Link]();
Practical List  229

[Link]();
getch();
}
Output:
Enter the values of h and w 5 40
h-5 w-40

Area Is:200
Perimeter Is:90

Q. 4 Write a C++ program to print cube of a number using friend function.


#include<iostream.h>
#include<conio.h>
class fir
{
int x;
public:
void get()
{
cout<<"enter the value of x "<<endl;
cin>>x;
}
friend void cube(fir f);
};
void cube(fir f)
{
int z;
z=f.x*f.x*f.x;
cout<<"the cube of "<<f.x<<" is "<<z;
}
void main()
{
fir f1;
clrscr();
[Link]();
cube(f1);
getch();
}
230  OOPs with C++ Programming

Q.5 Write a program to calculate mean value of two numbers with friend function by using
nesting member function.
#include<iostream.h>
#include<conio.h>
class fir
{
int x,y;
public:
void get()
{
cout<<"enter the value of x & y"<<endl;
cin>>x>>y;
}
friend float mean(fir f);
};
float mean(fir f)
{
return (f.x+f.y)/2;
}
void main()
{
fir f1;
clrscr();
[Link]();
cout<<"the mean value is "<<mean(f1);
getch();
}

Q. 6 Write a C++ program to create class cel, Accept temperature in Celsius through setc member
function. getc function is used to read the celsium temperature. Create class feh, Accept
temperature in Fahrenheit through setc member function. Getc function is used to read the
Fahrenheit temperature. Provide common friend function sum of both the classes to display the
sum of Celsius & Fahrenheit temperature.
#include<iostream.h>
#include<conio.h>
class feh;
class cel
{
float c;
public:
Practical List  231

void setc()
{
cout<<"Enter temp in Celsius ";
cin>>c;
}
float getc()
{
return c;
}
friend float sum(feh f,cel c);
};
class feh
{
float f;
public:
void setf()
{
cout<<"Enter temp in Feh ";
cin>>f;
}
float getf()
{
return f;
}
float display()
{
cout<<"Feh Temp is = "<<f<<endl;
return f;
}
friend float sum(feh f,cel c);
};
float sum(feh f,cel c)
{
return (f.f+c.c);
}
void main()
{
cel c1;
[Link]();
232  OOPs with C++ Programming

cout<<"Temp in cel is "<<[Link]()<<endl;


feh f1;
[Link]();
float ff=sum(f1,c1);
cout<<"FF is"<<ff<<endl;
getch();
}

Q. 7 Write a C++ program to print maximum of the number from class first and class second
through common friend max of both the classes
#include<iostream.h>
#include<conio.h>
class sec;
class fir
{
int x;
public:
void get()
{
cout<<"enter the value of x"<<endl;
cin>>x;
}
void disp()
{
cout<<"the value of x "<<x<<endl;
}
friend void max(fir,sec)
};
class sec
{
int y;
public:
void get()
{
cout<<"enter the value of y "<<endl;
cin>>y;
}
void disp()
{
Practical List  233

cout<<"the value of y is "<<y<<endl;


}
friend void max(fir,sec);
};
void max (fir f,sec s)
{
if(f.x >s.y)
{
cout<<"x="<<f.x <<"is greater than y="<<s.y;
}
else
{
cout<<"y="<<s.y<<"is greater than x="<<f.x;
}
}
void main()
{
fir f1;
sec s1;
clrscr();
[Link]();
[Link]();
[Link]();
[Link]();
max(f1,s1);
getch();
}

E. Write C++ Programs to Illustrate the Concepts: Constructors, Constructor


Overloading and Destructors.
Q. 1 Constructor Write a C++ program to accept two numbers through constructor and print
sum of two numbers through sum member function. Create two objects of a class.
#include<iostream.h>
#include<conio.h>
class number
{
int x,y;
public:
number()
234  OOPs with C++ Programming

{
cout<<"enter the value of x & y"<<endl;
cin>>x>>y;
}
void sum()
{
int z;
z=x+y;
cout<<"the sum is "<<z<<endl;
}
};
void main()
{
number s1,s2;
[Link]();
[Link]();
getch();
}

Q. 2 A bookshop maintains the inventory of books that are being sold at the shop. The list
includes details such as author, tilte, price,and publisher and stock position. Whenever a
coustomers wants a book, the sales person inputes the title and author and system searches the list
and display whether it is available or not. If it is not the appropriate message is desplayed. If it is
available then the system display the book details and request for the number of copies required.
If the number of copies are available the total cost off the requested copies is displayed; otherwise
error message is displayed. Design a system using a class called inventory with suitable member
functions and constructors.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class inventory
{
private :
char author[10],title[10],publisher[10];
int price,stock;
public :
inventory()
{
cout<<"enter title and author";
cin>>title>>author;
Practical List  235

cout<<"enter publisher,price & stock";


cin>>publisher>>price>>stock;
}
void display()
{
cout<<"the title is"<<title<<endl;
cout<<"the author is"<<author<<endl;
cout<<"the publisher is"<<publisher<<endl;
cout<<"the price is"<<price<<endl;
cout<<"the stock is"<<stock;
}
void search(char t1[10], char a1[10])
{
int noc,tcost=0;
if (strcmp(title,t1)==0)
{
if(strcmp(author,a1)==0)
{
display();
cout<<"enter number of copies";
cin>>noc;
if(noc<=stock)
{
tcost=price*noc;
cout<<"the total cost is"<<tcost;
}
else
{
cout<<"number of copies not available";
}
}
}
}
};
void main()
{
inventory n[3];
int i;
char t[10],a[10];
236  OOPs with C++ Programming

char wish='y';
while(wish=='y')
{
cout<<"enter title and author of book for purchasing"<<endl;
cin>>t>>a;
for(i=0;i<3;i++)
{
n[i].search(t,a);
}
cout<<"do u want to purchase more";
cin>>wish;
}
getch();
}

Q. 3 Create a Following Class.


Class TCountry:
{
String Name;
Double population;
Long Double Area;
String Capital;
Char Government;
}
Write default, parameterized and parameters with default arguments constructors for the
above class.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class string
{
public:
char s[20];
};
class tcountry
{
string name,capital;
long double population,area;
char govt[10];
Practical List  237

public:
tcountry()
{
strcpy(name.s,'\0');
strcpy(capital.s,'\0');
population =0;
area=0;
strcpy(govt,'\0');
}
tcountry(char *n, char *c)
{
strcpy(name.s,n);
strcpy(capital.s,c);
population =50000;
area=45.56;
strcpy(govt,'\0');
}
tcountry(char *n, char *c,long double p, long double a=89.56, char g[10]="congress")
{
strcpy(name.s,n);
strcpy(capital.s,c);
population =p;
area=a;
strcpy(govt,g);
}
void display()
{
cout<<"the name is "<<name.s<<endl;
cout<<"the capital is "<<capital.s<<endl;
cout<<"population is "<<population<<endl;
cout<<"area is "<<area<<endl;
cout<<"govt is "<<govt<<endl;
}
};
void main()
{
tcountry t();
tcountry t1("hello","hi");
[Link]();
238  OOPs with C++ Programming

tcountry t2("india","delhi",100000);
[Link]();
getch();
}

Q. 4 Create a class student accept two numbers through parameterized constructor. Calculate
sum, subtraction, Multiplication, division through separate member function.
#include<iostream.h>
#include<conio.h>
class student
{
int x,y;
public :
student(int a, int b)
{
x=a;
y=b;
}
void sum()
{
int z=x+y;
cout<<"the sum is "<<z;
}
void sub()
{
int z=x-y;
cout<<"the sub is "<<z;
}
void mul()
{
int z=x*y;
cout<<"the multiplication is "<<z;
}
void div()
{
int z=x/y;
cout<<"the division is "<<z;
}
};
void main()
{
Practical List  239

student s(5,3);
[Link]();
[Link]();
[Link]();
[Link]();
getch();
}

Q. 5 Create a class student accept rollno, name & marks through parameterized constructor. And
display through display member function.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class student
{
int rollno;
char name[10];
float marks;
public:
student(int r, char n[10],float m)
{
rollno=r;
strcpy(name,n);
marks=m;
}
void disp()
{
cout<<"the rollno is"<<rollno<<endl;
cout<<"the name is "<<name<<endl;
cout<<"the marks is "<<marks;
}
};
void main()
{
student s=student(10,"chirag",98); // Explicit call of constructor
[Link]();
getch();
}
240  OOPs with C++ Programming

Q. 6 Create a class first accept one integer number through parameterized constructor, Overload
that constructor to accept two integers and calculate and print sum of two numbers, Overload
that constructor to accept three float numbers and calculate sum of three float numbers and print
sum.
#include<iostream.h>
#include<conio.h>
class first
{
private:
int x,ix,iy;
float fx,fy,fz;
public :
first(int x1)
{
x=x1;
cout<<"the value of x is "<<x<<endl;
}
first(int x1,int y1)
{
ix=x1;
iy=y1;
cout<<"the value of ix & iy is "<<ix<<" "<<iy<<endl;
int sum=ix+iy;
cout<<"the sum of ix & iy is "<<sum<<endl;
}
first(float fx1, float fy1, float fz1)
{
fx=fx1;
fy=fy1;
fz=fz1;
cout<<"the value of fx,fy & fz is "<<fx<<" "<<fy<<" "<<fz<<endl;
int sum1=fx+fy+fz;
cout<<"the sum of fx,fy & fz is :"<<sum1<<endl;
}
};
void main()
{
clrscr();
first f(8);
first f1(2,3);
first f2(6.0,7.2,8.3);
getch();
}
Practical List  241

Q. 7 Write a program in C++ to create class date1 having data members day, month and year,
default value year = 2002, display date for default, for another overwrite year value to the deafult
and display the date for second object.
#include<iostream.h>
#include<conio.h>
class date1
{
private:
int day,month,year;
public:
date1(int d,int m,int y=2002)
{
day=d;
month=m;
year=y;
}
void disp()
{
cout<<"the date is: "<<day<<"/"<<month<<"/"<<year<<endl;
}
};
void main()
{
date1 d(5,9);
[Link]();
date1 d1(8,11,2003);
[Link]();
getch();
}

Q. 8 Wirte a C++ program to create a class show assign a public variable value x through main
function. Display the value of x through disp function and provide a Destructor to display the
destructor message.
#include<iostream.h>
#include<conio.h>
class show
{
public:
int x;
void disp()
242  OOPs with C++ Programming

{
cout<<x<<endl;
}
~show()
{
cout<<"Destructor is called"<<endl;
}
};
void main()
{
a obj;
clrscr();
obj.x=10;
[Link]();
getch();
}

Q. 9 Create class bank having data members name, accno, type of account and balance. Accept
details through constructor, Provide a member functions (1) deposit amount, (2) withdraw
amount after checking bal (3) disp name & balance.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class bank
{
char name[15];
int accno;
char type[10];
float bal;
public :
bank(char n[15], int ac, char t[10],float b)
{
strcpy(name,n);
accno=ac;
strcpy(type,t);
bal=b;
}
void deposit()
{
Practical List  243

int y;
cout<<"enter the amount to deposit"<<endl;
cin>>y;
bal = bal +y;
}
void withdraw()
{
int y;
cout<<"enter the amount to withdraw"<<endl;
cin>>y;
if((bal-y)>500)
{
bal =bal-y;
}
else
{
cout<<"no balance available";
}
}
void display()
{
cout<<"the name is "<<name<<endl;
cout<<"the balance is "<<bal;
}
};
void main()
{
clrscr();
bank b("kiran",819,"saving",10000);
bank b1("chirag”,485,"current",50000);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
getch();
}
244  OOPs with C++ Programming

F. Write C++ Programs to Illustrate the Concepts: Operator Overloading (Both


Unary and Binary).
Q. 1 Write a C++ program to overload unary - operator using operator function as a member
function
#include<iostream.h>
#include<conio.h>
class abc
{
int x,y;
public:
abc(int a,int b)
{
x=a;
y=b;
}
void operator -(void)
{
x=-x;
y=-y;
}
void disp(void)
{
cout<<" x is "<<x<<endl;
cout<<" y is "<<y<<endl<<endl;
}
};
void main()
{
int x,y;
clrscr();
abc s(2,3);
[Link]();
cout<<"after operator over-loading"<<endl<<endl;
-s;
[Link]();
getch();
}
Practical List  245

Q. 2 Write a C++ program to overload unary ++ operator using operator function as a member
function
#include<iostream.h>
#include<conio.h>
class abc
{
int x,y;
public:
abc(int a,int b)
{
x=a;
y=b;
}
void operator ++(void)
{
x=++x;
y=++y;
}
void disp(void)
{
cout<<" x is "<<x<<endl;
cout<<" y is "<<y<<endl<<endl;
}
};
void main()
{
int x,y;
clrscr();
abc s(2,3);
[Link]();
cout<<"after operator over-loading"<<endl<<endl;
++s;
[Link]();
getch();
}

Q.3 Write a C++ program to overload unary - operator using operator function as a friend
function
#include<iostream.h>
#include<conio.h>
class abc
246  OOPs with C++ Programming

{
int x,y;
public:
abc(int a,int b)
{
x=a;
y=b;
}
void friend operator ++(abc &s)
{
s.x=++s.x;
s.y=++s.y;
}
void disp(void)
{
cout<<" x is "<<x<<endl;
cout<<" y is "<<y<<endl<<endl;
}
};
void main()
{
int x,y;
clrscr();
abc s(2,3);
[Link]();
cout<<"after operator over-loading"<<endl<<endl;
++s;
[Link]();
getch();
}

Q. 4 Write a C++ program to overload binary - operator using operator function as a member
function
#include<iostream.h>
#include<conio.h>
class abc
{
int x,y;
public:
Practical List  247

abc()
{
}
abc(int a,int b)
{
x=a;
y=b;
}
abc operator +(abc &s)
{
abc s3;
s3.x=x+s.x;
s3.y=y+s.y;
return(s3);
}
void disp(void)
{
cout<<" x is "<<x<<endl;
cout<<" y is "<<y<<endl<<endl;
}
};
void main()
{
clrscr();
abc s1(2,3);
abc s2(4,5);
abc s3;
[Link]();
[Link]();
cout<<"after operator over-loading"<<endl<<endl;
s3=s1+s2;
[Link]();
getch();
}

Q. 5 Write a C++ program to overload unary >> & << operators by giving suitable example.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class bird
{
248  OOPs with C++ Programming

private :
char *name, *flying, *color;
int size;
public :
bird()
{
strcpy(name,'\0');
strcpy(flying,'\0');
strcpy(color,'\0');
size=0;
}
friend istream & operator >>(istream &din, bird &b);
friend ostream & operator <<(ostream &dout, bird &b);
};
istream & operator >>(istream &din, bird &b)
{
din>>[Link];
din>>[Link];
din>>[Link];
din>>[Link];
return din;
}
ostream & operator <<(ostream &dout, bird &b)
{
dout<<[Link]<<endl;
dout<<[Link]<<endl;
dout<<[Link]<<endl;
dout<<[Link]<<endl;
return dout;
}
void main()
{
bird b;
cout<<"enter the elements name,flying,color & size";
cin>>b;
cout<<"the elements are:"<<"\n";
cout<<b;
getch();
}
Practical List  249

Q. 6 Write a C++ program to overload unary ! operator so that it will return the length of the
string.
/* overload! operator so that it will return the length of the string
without pointers */
#include<iostream.h>
#include<conio.h>
#include<string.h>
class string
{
char n[10];
public :
string(char b[10])
{
strcpy(n,b);
}
void operator!(void)
{
cout<<"the length of entered string is "<<strlen(n);
}
};
void main()
{
clrscr();
char k[10];
cout<<"enter the string"<<endl;
cin>>k;
string n(k);
!n;
getch();
}

Q. 7 Write a C++ program to overload binary + operator using to combine two strings. /*
overload the + operator so that the two srings can be concatenated e.g. "Chirag "+"Gurbani"
="Chirag Gurbani" */
#include<iostream.h>
#include<conio.h>
#include<string.h>
class string
{
250  OOPs with C++ Programming

char *n;
char *n1;
public :
string()
{
}
string(char *b, char *b1)
{
n=b;
n1=b1;
}
void operator+(void)
{
cout<<"After adding the two strings are "<<strcat(n,n1);
}
};
void main()
{
clrscr();
char *k,*k1;
cout<<"enter the first string"<<endl;
cin>>k;
cout<<"enter the second string "<<endl;
cin>>k1;
string n(k,k1);
+n;
getch();
}

G. Write C++ Programs to Illustrate the Concepts: Simple, Multiple, Multilevel


Inheritance.
Q. 1 write a program in C++ to create a class cAdd to add two numbers and derive another class
cSubtract that subtract two numbers which are read through cAdd.
Source Code:
#include<conio.h>
#include<iostream.h>
class cAdd
{
public:
Practical List  251

int x,y;
void setdata()
{
cout<<"\n Enter two numbers";
cin>>x>>y;
}
void display()
{
cout<<"x="<<x<<"y="<<y ;
}
int add()
{
return(x+y);
}
};
class cSubtract:public cAdd
{
public:
int sub()
{
return(x-y);
}
};
void main()
{
clrscr();
cAdd a;
[Link]();
int b=[Link]();
cout<<"Addition="<<b<<endl;
cSubtract p;
[Link]();
int c=[Link]();
cout<<"Subtraction="<<c<<endl;
getch();
}
Output:
Enter two numbers 4 54
Addition=58
252  OOPs with C++ Programming

Enter two numbers


4 54
Subtraction= -50
Q. 2 Write a program in C++ to create a base class emp to accept and print employee id, name
from the user through member functions, create another base class empun to accept the member
id & print member id
#include<iostream.h>
#include<conio.h>
class emp
{
protected:
int eid;
char ename[20];
public:
void get()
{
cout<<"enter the employee id and name "<<endl;
cin>>eid>>ename;
}
void disp()
{
cout<<"the emp id id "<<eid<<endl<<" and name is "<<ename<<endl;
}
};
class empun
{
protected:
int memid;
public:
void get()
{
cout<<"enter member id"<<endl;
cin>>memid;
}
void disp()
{
cout<<"the emp member id is "<<memid<<endl;
}
};
Practical List  253

class empin:public emp,public empun


{
Private:
int m;
void display()
{
M=90;
Cout<<”the value of m is”<<m;
};
void main()
{
clrscr();
empin e1;
[Link]::get();
[Link]::disp();
[Link]::get();
[Link]::disp();
[Link]();
getch();
}

Q.3 Write a program in C++ to create a class stud to read the rollno & print rollno through
member functions, create derived class art from stud base class to accept & display the arts
marks, same way create medi derived class & engg. derived class from stud base class to accept
and print the marks. In engg. provide a member functions for mechanical electrical & civil.
Provide a hierarchical inheritance to create a menu options from the user for selecting the
category.
#include<iostream.h>
#include<conio.h>
class stud
{
protected:
int roll;
public:
void getst()
{
cout<<"enter roll no"<<endl;
cin>>roll;
}
void dispst()
254  OOPs with C++ Programming

{
cout<<" ur roll no is "<<roll<<endl;
}
};
class art:public stud
{
protected:
int marks;
public:
void getart()
{
getst();
cout<<"enter ur marks"<<endl;
cin>>marks;
}
void dispart()
{
dispst();
cout<<"ur marks in arts are "<<marks<<endl;
}
};
class medi:public stud
{
protected:
int marks;
public:
void getmedi()
{
getst();
cout<<"enter ur marks"<<endl;
cin>>marks;
}
void dispmedi()
{
dispst();
cout<<"ur marks in medical are "<<marks<<endl;
}
};
class engg:public stud
Practical List  255

{
protected:
int marks;
public:
void mech()
{
getst();
cout<<"enter the marks of mechanical subj "<<endl;
cin>>marks;
}
void elec()
{
getst();
cout<<"enter the marks of electrical subj "<<endl;
cin>>marks;
}
void civil()
{
getst();
cout<<"enter the marks of civil subj "<<endl;
cin>>marks;
}
void dispengg()
{
dispst();
cout<<"the marks of subj are "<<marks<<endl;
}
};
void main()
{
engg e1;
art a1;
medi m1;
int ch;
clrscr();
[Link]();
[Link]();
[Link]();
[Link]();
256  OOPs with C++ Programming

[Link]();
[Link]();
cout<<" 1. mechanical"<<endl;
cout<<" 2. electrical"<<endl;
cout<<" 3. civil "<<endl<<endl;
cout<<"enter ur choice"<<endl;
cin>>ch;
switch(ch)
{
case 1:
[Link]();
break;
case2:
[Link]();
break;
case 3:
[Link]();
break;
default :
cout<<"enter correct number "<<endl;
break;
}
[Link]();
getch();
}

H. Write C++ Programs to Illustrate the Concepts: Polymorphism (Virtual


Functions, Pure Virtual Functions).
Q. 1 Write a program in C++ to create a class base having sum virtual function to accept two
numbers & print the sum of two numbers. Create a der1 class which should be derived from base
class having sum function. Create der2 class from der1 class with sum function by showing the
use of virtual function.
#include<iostream.h>
#include<conio.h>
class base
{
public:
int a,b;
virtual void sum()
{
Practical List  257

int sum;
cout<<"Enter a& b"<<endl;
cin>>a>>b;
sum=a+b;
cout<<"the sum is "<<sum;
}
};
class der1:public base
{
public:
int c;
void sum()
{
int sum;
cout<<"Enter a,b,c"<<endl;
cin>>a>>b>>c;
sum=a+b+c;
cout<<"the sum is "<<sum;
}
};
class der2:public der1
{
public:
int d;
void sum()
{
int sum;
cout<<"enter the a,b,c,d"<<endl;
cin>>a>>b>>c>>d;
sum=a+b+c+d;
cout<<"the sum is"<<sum;
}
};
void main()
{
clrscr();
base *p,s;
der1 d1;
der2 d2;
258  OOPs with C++ Programming

p=&s;
p->sum();
p= &d1;
p->sum();
p=&d2;
p->sum();
getch();
}

Q. 2 write a program to create class cPolygon having pure virtual function Area(). Derive two
classes from it called cRectangle and cTriangle to override Area().
Source Code:
#include<iostream.h>
#include<conio.h>
#include<math.h>
class cPolygon
{
public:
int l,b;
virtual void Area()=0;
virtual void display()=0;
};
class cRectangle:public cPolygon
{
int A,b;
public:
cRectangle(int l1,int b1)
{
l=l1;
b=b1;
}
void display()
{
cout<<"\n Length="<<l;
cout<<"\n Breadth="<<b;
}
void Area()
{
A=l*b;
Practical List  259

cout<<"\n Area Of Rectangle="<<A;


}
};
class cTriangle:public cPolygon
{
int c;
float A;
public:
cTriangle(int l1,int b1,int c1)
{
l=l1;
b=b1;
c=c1;
}
void display()
{
cout<<"\n L="<<l;
cout<<"\n B="<<b;
cout<<"\n C="<<c;
}
void Area()
{
float s;
s=(l+b+c)/2;
A=sqrt(s*(s-l)*(s-b)*(s-c));
cout<<"\n Area Of Triangle="<<A;
}
};
void main()
{
clrscr();
cPolygon *base;
cRectangle r(2,5);
base=&r;
base->display();
cout<<"\n";
base->Area();
cout<<"\n";
cTriangle t(4,5,6);
260  OOPs with C++ Programming

base=&t;
base->display();
cout<<"\n";
base->Area();
getch();
}
Output:
Length=2
Breadth=5
Area Of Rectangle=10
L=4
B=5
C=6
Area Of Triangle =6.480741

I. Write Programs to Illustrate the File Handling in C++.


Q. 1 Write a C++ program to accept the name from user & write into a file called [Link] File.
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
char name[10];
clrscr();
cout<<"enter name"<<"\n";
cin>>name;
ofstream out("[Link]");
out<<name;
[Link]();
getch();
}

Q. 2 Example of C++ program with command line arguments of main function by passing array
& storing into a file.
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdlib.h>
void main(int argc, char * argv[])
Practical List  261

{
int number[9]={11,22,44,33,55,66,77,88,99};
if(argc!=3)
{
cout<<"argc="<<argc<<"\n";
cout<<"error in argument";
exit(1);
}
ofstream fout1,fout2;
[Link](argv[1]);
if([Link]())
{
cout<<"could not open file"<<argv[1]<<"\n";
exit(1);
}
[Link](argv[2]);
if([Link]())
{
cout<<"could not open file"<<argv[2]<<"\n";
exit(1);
}
for(int i=0;i<9;i++)
{
if(number[i]%2==0)
{
fout2<<number[i]<<" ";
}
else
{
fout1<<number[i]<<" ";
}
}
[Link]();
[Link]();
ifstream fin;
char ch;
for(i=1;i<argc;i++)
{
[Link](argv[i]);
262  OOPs with C++ Programming

cout<<"contents are of :"<<argv[i]<<"\n";


do
{
[Link](ch);
cout<<ch<<" ";
}
while(fin);
cout<<"\n\n";
[Link]();
}
getch();
}

Q. 3 Example of C++ program accepting the details name, code and cost from user, store the
details in a file and reading the contents & displaying the details.
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<iomanip.h>
class inventory
{
char name[10];
int code;
float cost;
public:
void readdata();
void writedata();
};
void inventory :: readdata()
{
cout<<"enter name code cost"<<"\n";
cin>>name>>code>>cost;
}
void inventory:: writedata()
{
cout<<setw(10)<<name<<"\n";
cout<<setw(10)<<code<<"\n";
cout<<setw(10)<<setprecision(2)<<cost<<"\n";
}
void main()
{
Practical List  263

inventory item[3];
fstream file;
clrscr();
[Link]("[Link]",ios::in|ios::out);
cout<<"enter the details" <<"\n";
for(int i=0;i<3;i++)
{
item[i].readdata();
[Link]((char *) &item[i],sizeof(item[i]));
}
[Link](0);
for(i=0;i<3;i++)
{
[Link]((char*) &item[i],sizeof(item[i]));
item[i].writedata();
}
[Link]();
getch();
}

Q. 4 Write a C++ program to read the contents of [Link] & [Link] file & display the
contents of country & capital by reading both the files.
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdlib.h>
void main()
{
const n=80;
char line[80];
clrscr();
ifstream f1,f2;
[Link]("[Link]");
[Link]("[Link]");
for(int i=1;i<10;i++)
{
if([Link]()!=0)
{
cout<<"exit from country"<<endl;
exit(1);
264  OOPs with C++ Programming

}
[Link](line,n);
cout<<"country of"<<line;
if([Link]()!=0)
{
cout<<"exit from capital"<<endl;
exit(1);
}
[Link](line,n);
cout<<"capital of"<<line;
}
getch();
}

Q. 5 Write a C++ program to create [Link] file & store the names of the countries. Create
another file [Link] & store the names of capitals of the countries. Read the contents of both
the files & display on the output.
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
const n=80;
char line[80];
clrscr();
ofstream out;
[Link]("[Link]");
out<<"united state of america"<<"\n";
out<<"united kingdom"<<"\n";
out<<"south korea";
[Link]();
[Link]("[Link]");
out<<"london"<<"\n";
out<<"paris"<<"\n";
out<<"delhi";
[Link]();
ifstream fin;
[Link]("[Link]");
while(fin)
{
[Link](line,n);
Practical List  265

cout<<line;
}
[Link]();
[Link]("[Link]");
while(fin)
{
[Link](line,n);
cout<<line;
}
[Link]();
getch();
}

Q. 6 Write a C++ program to create a file to store Cricketers name in it and then display them on
screen.
Source Code:
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
clrscr();
char name[80];
int i;
cout<<"\n Enter number of Cricketers";
cin>>i;
int n=0;
ofstream of("Cricketer");
do
{
cout<<"\n Enter Name:";
cin>>name;
of<<name<<"\n";
n++;
}while(n<i);
[Link]();
ifstream ifs("Cricketer");
cout<<"\n Data From file is:\n";
while(ifs)
{
266  OOPs with C++ Programming

[Link](name,80);
cout<<name;
}
[Link]();
getch();
}
Output:
Enter number of Cricketers 4
Enter Name: Sachin
Enter Name: Saurabh
Enter Name: Piyush
Enter Name: Dhoni
Data From file is:
SachinSaurabhPiyushDhoni

J. Write Programs to Illustrate the Templates in C++.


Q. 1 Write a program in C++ by using template which finds Minimum of two numbers
Source Code:
#include<iostream.h>
#include<conio.h>
template<class T>
class number
{
T a,b;
public:
void setdata(T aa,T bb)
{
a=aa;
b=bb;
}
void display()
{
cout<<"\n a="<<a<<endl;
cout<<"\n b="<<b<<endl;
}
void minimum()
{
if(a>b)
cout<<b<<" is Minimum";
Practical List  267

cout<<a<<" is Minimum";
}
};
void main()
{
clrscr();
number<int>x;
[Link](2,3);
[Link]();
[Link]();
number<float>y;
[Link](10.0,20.5);
[Link]();
[Link]();
getch();
}
Output:
a=2
b=3
2 is Minimum
a=10
b=20.5
10 is Minimum

K. Write Programs to Illustrate the Exceptions in C++.


Exception Handling:
Q. 1 Write a C++ program in which a function to read two double type numbers and calculate
division of those numbers and a try block to detect and throw exception if the condition divide by
“zero” occurs
Source Code:
#include<iostream.h>
#include<conio.h>
void main()
{
double a,b,c=1;
cout<<"Enter Two Numbers";
cin>>a>>b;
try
{
if(b==0)
268  OOPs with C++ Programming

throw b;
cout<<"c="<<a/b;
}
catch(double b)
{
cout<<"\n As Division By Zero Occured";
}
getch();
}
Output:
(a) Enter Two Numbers: 4 0
As Division By Zero Occurred
(b) Enter Two Numbers: 12 4
c=3

L. Write Programs to Illustrate Manipulators used in C++.


Q. 1 Write a program to display the use of setw, setprecision, setiosflags manipulators.
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main()
{
[Link](ios::showpoint);
cout<<setw(5)<<"n"<<setw(15)<<" inverse of n "<<setw(15)<<" sum of terms "<<"\n";
double term,sum=0;
for(int n=1;n<=10;n++)
{
term=1.0/float(n);
sum=sum+term;
cout<<setw(5)<<n<<setw(15)<<setprecision(4)<<setiosflags(ios::scientific)<<term<<setw(13)<<res
etiosflags(ios::scientific)<<sum<<endl;
}
getch();
}

Q. 2 Write a program to display the use of fill precision, width manipulators.


#include<iostream.h>
#include<conio.h>
void main()
{
Practical List  269

clrscr();
[Link]('<');
[Link](3);
for(int n=1;n<=6;n++)
{
[Link](5);
cout<<n;
[Link](10);
cout<<1.0/float(n)<<endl;
if(n==3)
{
[Link]('>');
}
}
cout<<"padding changed ";
[Link]('#');
[Link](15);
cout<<12.345678<<"\n";
getch();
}

Q. 3 Write a program to display the use of width manipulators.


#include<iostream.h>
#include<conio.h>
void main()
{
int item[4]={10,40,88,74};
int cost[4]={44,88,96,12};
clrscr();
[Link](5);
cout<<"items ";
[Link](8);
cout<<"cost ";
[Link](15);
cout<<"total value "<<"\n";
int sum=0;
for(int i=0;i<4;i++)
{
[Link](5);
cout<<item[i];
270  OOPs with C++ Programming

[Link](8);
cout<<cost[i];
int value=item[i] * cost[i];
[Link](15);
cout<<value<<"\n";
sum=sum+value;
}
cout<<"grand total is ";
[Link](2);
cout<<sum;
getch();
}


Model Question Paper
Note: (1) All questions are compulsory.
(2) Figures to the right indicate marks.
(3) Write suitable programs wherever necessary.
Q. 1 Answer the following (Attempt any 3) (15)
(a) Explain object oriented concept with data encapsulation and data inheritance
by explaining features of C++ language.
(b) Explain how data polymorphism can be achieved by function overloading and
operator overloading by giving suitable example.
(c) Explain how file handling is provided in C++ language and what are different
classes for file stream operations.
(d) Explain difference between Cin and Cout objects with example, also explain #
include directives used in C++.
Q. 2 Answer the following (Attempt any 3) (15)
(a) Explain what is Class, how to define data members and member functions with
the different scope of variables. Draw a Class diagram to represent it by giving
suitable example.
(b) Explain how objects can be created and destroyed with example, also explain
with example how parameterised constructor can be called.
(c) Explain what do you mean by function declaration with prototype statement,
function call and function definition. How it can be achieved using default
arguments?
(d) Explain how non member function can access the properties and methods of
the class. How you can achieve this. What are the rules followed to achieve
this?
Q. 3 Answer the following (Attempt any 3) (15)
(a) Explain inheritance with reusability concept and state types of inheritance.
Give suitable example of multilevel inheritance by creating a base class
student having data members Rollno, name. Inherit student base class create
derived class Sem1 to accept Semester 1 Marks from the user. Created derived
class Sem2 to accept Semester 2 marks. Create derived class result to display
total marks of Sem1 and Sem2 along with Rollno and Name and Percentage of
the student.
(b) Explain what is the use of virtual function, what is difference between virtual
function and pure virtual function.
272  OOPs with C++ Programming

(c) Explain C++ streams and manipulator used for managing output with suitable
example.
(d) Explain how pointer to object and pointer to derived class can be achieved with
suitable example.
Q. 4 Explain the following (Attempt any 3) (15)
(a) Explain open() and Close() methods of files, how to detect end of file. Write a
program to create a file. Store the data and display contents of a file.
(b) Explain function templates with multiple parameters.
(c) Explain use of Exception handling with try, catch and throw block. Give
suitable example how re-throwing of an Exception is provided.
(d) Explain what is STL and what are components of STL.


ISBN: 978-93-5433-335-4

ISBN: 978-93-5433-335-4 ESM 0744

You might also like