You are on page 1of 611

PAN African e-Network Project

PGDIT
Object Oriented Programming
Semester 2nd
Session - 1

Dr. Bhawna Minocha

Welcome
to
Object Oriented
Programming

Session Outline

Genesis of C++
Structured vs. Object Oriented Programming
Basics Concepts of Object Oriented Programming
Structure of C++ program
C++ Comments
A simple C++ program with explanation
Using streams for input and output (cin , cout)
Placement of variable declarations
The const qualifier
Executing a C++ program
A Class in C++
Synonyms
Practice Questions & answers

GENESIS OF C++
Factors that contributed to the evolution
Increasing complexity of the problem domain.
Difficulty in capturing the complexity of the problem domain
through procedural languages(like C, Fortran, Pascal)
Difficulty in modeling real-world objects through procedural
languages.

GENESIS OF C++
Growing demands on software in terms of
Correctness
Maintainability
Reusability
Scalability
Openness and interoperability
Integrity

GENESIS OF C++
Commercial viability
A huge investment in C lead to the incorporation of object
oriented features with C leading to
C++ is a superset to C and C++ = C +OOPs.
C++ provides object-oriented programming (OOP).
OOPs was invented to overcome the drawbacks of the
pop(Procedure-Oriented Programming).

Structured
Vs
Object-oriented
Development

Structured Programming
In the structured approach, the problem is
viewed as a sequence of things to be done,
such as reading, calculating and printing.
A number of functions are written to
accomplish these tasks.
The primary focus is on functions.
A typical program structure for procedural
programming is shown in the next slide.

Typical structure of structureoriented programs


Main Program

Function - 1

Function - 2

Function - 4

Function - 3

Function - 5

Function - 6

Structured programming basically consists of


writing a list of instructions for the computer
to follow, and organizing these instructions
into group known as functions.
While we concentrate on the development of
functions, very little attention is given to the
data that are being used by various functions.
In a multi-function program, many important
data items are placed as global so that they
may be accessed by all the functions.
Each function may have its own local data.

Relationship of data and functions in


Structured programming
Global Data

Global Data

Function - 1

Function - 1

Function - 1

Local Data

Local Data

Local Data

Global data is more vulnerable to an inadvertent


change by a function.
In a large program it is very difficult to identify what
data is used by which function.
In case we need to modify an external data structure,
we should also revise all functions that access the
data.
Another serious drawback with the Structured
approach is that it does not model real world
problems very well.
This is because functions are action-oriented and do
not really correspond to the elements of the problem.

Object-Oriented programming paradigm


Object-oriented programming (OOP) is
organized around "objects" rather than
"actions, data rather than logic.
OOP treats data as a critical element in the
program development and does not allow it to
flow freely around the system.
OOP allows us to decompose a problem into a
number of entities called objects and then
builds data and functions around these entities.

Organization of data and functions in


OOP
Data

Data
Functions

Functions
Object A

Object B
Functions

Data

Object C

Comparison of the Two


Approaches
Software projects are complex, and decomposition
(divide-and-conquer) is the primary strategy to deal
with its complexity by breaking a problem up into
manageable units.
Prior to object-oriented analysis and design, the
most popular approach to decomposing a problem
was Structured Analysis and Design, whose
dimension of decomposition is primarily by function
or process, resulting in a hierarchical breakdown of
processes composed of sub-processes.

Object-oriented analysis and design


emphasizes decomposing a problem space
by objects rather than by functions.
The following figure illustrates the primary
distinction between the two approaches
presented.

Library
Management
System

Comparison
b/w OOAD &
SSAD

Object-Oriented A/D

Structured A/D

Decompose by
objects or concepts

Decompose by
functions or processes

Book

Catalog

System

Library
Librarian

Record
Issues

Add To
Stock

Report
Fines

Distinction between POP and OOP


Programming
POP

OOP

Procedure oriented programming.

Object oriented programming.

Emphasis is on procedure.

Emphasis is on data rather than


procedure

Follows top-down approach.

Follows bottom-up approach.

Data is not secure.

Data is secure by encapsulation.

Large programs are divided in to


smaller programs known as
functions

Programs are divided in to what are


known as objects.

Basic Concepts of Object Oriented Programming

1.
2.
3.
4.
5.
6.
7.

Objects
Classes
Encapsulation
Abstraction
Inheritance
Polymorphism
DynamicBinding&
MessagePassing

1
2

7
5

Objects
Objects are often used to model real world entities
that we normally find in everyday life.
An object can be a person , place , thing ,concept or
anything we see in the real world . Some common
examples of an object include car ,book, computer ,
apple etc.
The principal building blocks of object-oriented
programming.
Each object is a programming unit consisting of data
(variables) and functionality (methods).

OBJECT:STUDENT

Data

A. Name
B. Date Of Birth
C. Marks
....................

A
2

B
Functions

1. Total
2. Average
3. Display
................

Objectscontaindata(likeName,DOB,Marks)andfunctions
(likeTotal,averageanddisplay)tomanipulatethatdata.

Objects
Each object possess the following characteristics.
Each object has an identity and are distinguishable.
Data and functions are binded together to form an
object.
Objects in the system communicate with each other
using the concept of message passing.
Objects store data which is manipulated by its
functions.
Since all software applications serve people living in the
real world, then that software should mirror the real world
as closely as possible, both in its workings and in its
appearance :: thats the reason to use objects

Class
A class is a general specification or description for a
set of objects that defines their common structure
(data), behaviour (methods), and relationships
(inheritance).
A class is a prototype that defines the variables and
methods common to all objects of a certain kind.
Once a class has been defined, we can create any
number of objects belonging to that class.
If fruit has been defined as a class, then the
statement fruit mango; will create an object mango
belonging to the class fruit.

Why use classes?


The object is a basic key concept of Object
Oriented Programming but still we focus on
classes because classes provide us the ability
to generalize similar type of objects.
Classes provide us a set of common
definitions for similar type of objects.
Operations can be written once for each class ,
so that all the objects in a class can take
benefit from the code reuse.

Distinction between Object and Class


Object

Class

Objects may be created and destroyed at run


time.

Once we have defined a class, it


exists all the time a program is
running

Data and functions that operate on that data


are binded together to form an object.

A collection of similar type of objects


is called a class

Object is an instance of a class.

Class is a set of object that share


common attributes and behaviours.

Table , chair , sofa are examples of objects.

Furniture is an example of class


which has table ,chair , sofa objects.

Encapsulation
Encapsulation

Encapsulation is the wrapping up of data and function


into single unit called object.
The only way to access the data of an object is through
the function which are wrapped in the class.
Consider two classes.Library class and a Student Class.
The Library class encapsulates data (like Book Id,book
author book title, no. of copies) and functions like
issue(),book_status() and book_description () in to a
single unit. As shown in next slide. In the similar manner
the Student class encapsulates data and functions as
shown in next slide. The two classes are independent of
each other.

Encapsulation
Book Id
Book author
Book title

Issue()
Book_status
Book_description

Library Class

Roll no
Name
Class

Input()
Show()

Student Class

ADVANTAGES OF ENCAPSULATION

With Encapsulation Data Hiding can be accomplished.


It protects the data of a class from accidental manipulation
or misuse by the functions which are outside the class.
Any changes made in the data and functions of a class does
not make any effect to other classes.
Classes are independent of each other.

Abstraction
Abstraction Simplicity is good; complexity is bad.
Abstraction is a process that involves identifying the essential
features without including the internal details.
A good abstraction is the one that emphasizes details that are significant
and suppresses details that are not.
Let us take a real world example ::
Consider an example of a Television which consists of features such as
changing the channel ,ON/OFF switch etc. User interacts with television
using interfaces like channel changer, volume controller, and power button
without going in to internal details of the working of each of the interface.
The user is not concerned about how it receives signals over the air.
,translate them and display on the screen. So,it shows how the internal
complexity of working of the television is hidden from the user.

Abstraction
Abstraction
In object oriented programming , classes uses the concept of Abstraction.
A class encapsulates the relevant data and functions that operate on data
by hiding the complex implementation details from the user . In other
words ,user needs to focus on what a class does rather than how it will be
implemented.
The following diagram shows that the basic concept of Abstraction.

Inheritance
Inheritance is the process by which objects of one class
acquire properties of objects of another class.
Types of class in inheritance.
1. Base class.
2. Derived class.

Grand Father

Father

// Base class

// Derived class

Inheritance
Inheritance is the process by which one
object acquires the properties of one or more
other object. It supports the concept of
hierarchical classification (top-down).
An object need to define only those qualities
that make it unique within its class.
It implements "is-a" relationships between
objects.
Inheritance creates a hierarchy of related
classes (types) which share code and
interface.

INHERITANCE EXAMPLES
Base Class

Derived Class

Employee

Manager
Researcher
Worker

Account

Checking Account
Saving Account

Generalization/Specialization
Generalization/Specialization represents the is
a relationship set, an essential element of the
object oriented paradigm. The main idea in
Generalization/ Specialization is that one
object class (the specialization) is a subset of
another (the generalization).
A generalization-specialization (gen-spec)
relationship states that one object is a kind-of
(or is-a) the other, and that the other is a
generalization of the object

Specialization
Specialization is either:
the process of defining a new object based on a
(typically) more narrow definition of an existing
object, or
an object that is directly related to, and more
narrowly defined than, another object.
A specialization relation requires that every
instance of the subtype be an instance of the
supertype.
It is common to say that everything that is true for a
generalization is also true for its corresponding
specialization.

POLYMORPHISM
The word Polymorphism is derived from two Greek
words Poly means many and morphs means forms.
So , polymorphism means the ability to take many
forms.
Polymorphism means one name, multiple forms. It
allows us to have more than one function with the
same name in a program .
It also allows overloading of operators so that an
operation can exhibit different behaviors in different
instances.

Basics of OOP
Polymorphism Example
Ex:-addition(+)
For two numbers ,the operation will generate a sum.
For two strings , then the operation would produce a
third string by concatenation.

Basics of OOP
Dynamic Binding

Binding refers to the linking of a function call to the


code of the function to be executed in response to
the function call. Binding is of two types::
Static Binding or Early Binding
Dynamic Binding or Late Binding
Static Binding:: In static Binding, the linking of
function call to the code of the function to be
executed in response to the function call is made at
compile time.
Static Binding:: In static Binding, the linking of
function call to the code of the function to be
executed in response to the function call is made at
run time.

MESSAGE PASSING
In Object oriented programming (OOP) different objects
communicate with each other using the concept of Message
Passing. From the programmer point of view ,message passing
provides an easy way of modeling real world problems on the
computer. Objects communicate with each other in the same way as
human beings exchange messages among themselves.
A message comprises of the name of the object , name of the
function and any information (arguments) to be sent to the object.
For example :If a user wants to check the balance of his account ,
he simply sends the message getbalance to the object account by
passing the information account_no. as shown below
account. getbalance (account_no)
account:: Object
Getbalance:: Message
account_no :: Argument or Onformation

Structure Of C++ Program


Documentation Section :: which includes the comments to tell the programs
purpose. It improves the readability of the program.
Preprocessor Directive :: includes preprocessor directives like # include, #
define which is a message to the preprocessor
Global Declaration Section:: includes global variables which are visible
throughout the program. In general, use of global variables should be avoided.
Class Section :: describes information about classes present in the program.

Main Program Section:: from here the execution of program actually starts.
Eg:: int main()
{ // Executable Part
}
SubProgram Section :: includes user defined functions.

C++ Comments
C++ supports the C comment format where /* begins a
comment and */ ends it.
The // also starts a comment in C++ (unless it is inside a
string). Everything to the end of the current line is a
comment.
e.g.,
/* This is a comment */
//

This is also a C++ comment

//

This is invalid
in the next line

/*

This is valid in
the next line */

C++ Comments
Good practice: C++ style of comment is recommended as can
be seen in the following example.
C++ style
if(a>b)
{ //int temp=a;
//swap a, b
//a=b;
//b=temp;
}
C style
if(a>b)
{ /*
int temp=a; /*swap a,b*/
a=b;
b=temp; */
}

A Simple program in C++ to add two numbers


// To add two numbers
#include <iostream.h> // preprocessor directive
#include <conio.h>
int main() // main() function heading
{
int a , b , sum; // variable declaration
cout << Enter number a = ; // Output statement
cin >> a; // Input statement
cout << Enter number b = ;
cin >> b;
sum=a+b;
cout << Sum is <<sum; // Output statement
getch();
return 0;

Explanation of the previous program


The first line :: specifies the comment describing the purpose of the program. It
is non executable statement.
The second line :: contains a preprocessor directive that instructs the compiler to
include the file iostream.h(Input /Output header file) at this point. This file must be
included in the program to perform any Input /Output operations.
Similarly the header file conio.h is handled.
The fourth line :: main () is a entry point of a programs execution. Every C++
program must contain only one main function.
It is necessary to specify the return data type of every function used in C++. The
return type of main is always int. the last statement return 0; tells main to return
value 0 to the calling environment. Any other value specified with return statement
indicates that the program has not run properly.
The remaining lines :: comprises the set of statements which includes variables
declaration , input statements, and output statements.
cin statement is used to input any value from the keyboard and
cout statement is used to display any message or value on the screen.

On executing previous C++ program , we


get
Enter Number a=7 //(press enter)
Enter Number b=7 //(press enter)
Sum is 14

Streams

The Standard Output Stream


The name cout represents the standard output stream. It can be
used to send messages to the standard output (the screen).

The Standard Error Stream


The name cerr represents the standard error stream. It can be
used to send messages to the screen, especially from programs
that have their standard output redirected to another file or device.

The Standard Input Stream


The name cin represents the standard input stream. It can be used
to read data typed from the keyboard.
Any built-in data type may be used with cout, cerr and cin without a
format string, unlike printf.

Getting output onto the screen


include the <iostream.h> header file
use cout <<
use additional << to combine multiple
elements together eg
cout << you entered << x;

use endl to add newline


cout << you entered << x << endl;

47

Getting input from the keyboard


include the <iostream.h> header file
declare a variable of a suitable type
eg int num_in;

use cin
eg cin >> num_in;

48

Getting input from the keyboard


##include <iostream.h>
int main( )
{
int x;
cout << "please enter an integer" << endl;
cin >> x;
cout << "you entered " << x << endl;
return 0;
}

49

Placement of Variable Declaration

C requires that all variables be declared at the beginning of a


block.
C++ allows the declaration of a variable anywhere in the code, but
before it is referenced.
Allows the placement of a variable closer to the code that uses it,
which makes the program more readable.
e.g.,

main()
{
cout << Enter a number ;
int num;
// declaration of variable within block
cin >> num;
cout << Number = << num;
}

Basic Data Types


Type

Bytes

Range

Char

-128 to 127

Unsigned char

0 to 255

Signed char

-128 to 127

Int

-32768 to 32767

Unsigned int

0 to 65532

signed int

-31768 to 32767

Short int

-31768 to 32767

Unsigned short int

0 to 65535

Basic Data Types


signed short int

-32768 to 32767

Long int

-2147483648 to
2147483647

signed long int

-2147483648 to
2147483647

signed long int

0 to 4294967295

Float

3.4E-38 to 3.4E+38

Double

1.7E-308 to
1.7E+308

Long double

10

3.4E-4932 to
1.1E+4932

BOOL
It takes only two values: true or false
true=1;
false=0;
eg: #include<iostream.h>
#include<conio.h>
void main()
{
bool b=32;
bool i=false;
cout<<b<<i;
int j=b+b;
bool k=b+b;
cout<<j<<k;
getch();
}

output
10
2 true

NOTE: Some compilers(such as


TurboC++ 3.0)do not support bool data
type.However ,compilers like Devc++,Bortland C++ 5.5 etc support this data
type.

PROGRAM TO SHOW RANGE OF


INTEGER DATATYPE
#include<limit.h>
void main()
{
cout<<Min value of int=<<INT_MIN<<\n;
cout<<Max value of int=<<INT_MAX<<\n;
cout<<Min value of uint=<<UINT_MIN<<\n;
cout<<Max value of uint=<<UINT_MAX<<\n;
cout<<Min value of long=<<LONG_MIN<<\n;
cout<<Max value of long=<<LONG_MAX<<\n;
getch();
}

output

Minimum value of int = -32768


Maximum value of int = 32767
Maximum value of unsigned int =65535
Maximum value of long int =2147483647
Maximum value ogf long int =-2147483648

The const Qualifier


used to declare constants, as in ANSI C
specifies that the variable is read-only, except during its onetime initialization.
const variables can only be given values at initialization time.
can be used as a replacement for constants defined with the
#define directive.
C++ allows const declarations in header files, unlike C
E.g.:
const int a=123;
Good practice:
Prefer const to preprocessor macro since const variable value is
available to symbolic debugger unlike # defined values

DIFFERENCE BETWEEN #DEFINE AND


CONST
1. Const is better than #define.
2. If we place const inside the function i.e. effect will
be localized in that function whereas if it is placed
outside the function, its effect will be global.
3. But #define is always global. It cant be localized.

Executing any High level C++ involves


following steps
Developing the source code program
Selecting and saving the appropriate file name .This saved file is known as source
code file.
Compile the program. After compilation the program changes to a object file if
there are no errors.
Now link the object code and other library codes that are required for execution.
On linking correctly an executable code is formed.
Now run the program to obtain the desired results.
If answer is correct then stop otherwise check for some logical error.

Executing your C++ Program


Invoking Compiler:: there are many C++ compilers like Borland C++,Turbo C++
etc. Well take Turbo C++ as an example.
Change the directory to C:\cd TC (If TC directory)
And then C:\TC\ cd BIN
Result :: C:\TC\BIN
Making a New Program:: Select New from the file menu in the editor and type
the file name as First.CPP (Note the extension)
Typing your Program:: Type the program as specified in the discussed example
in the editor window.
Saving the Program:: After typing the C++ source code (program) save it to the
disk by selecting SAVE from FILE menu.
Running the program:: Once we type and edit our C++ program source code,
we must compile the program by using ALT + F9

Executing your C++ Program


Compiling the Program:: Whenever you compile a program, a compilation
window appear on the screen. If there are no errors during compilation ,it will
display Success :Press any key message. The entries for warning and errors will
be zero and an object file with extension (.OBJ) is created. This Object file
contains machine language instructions that can be executed by the computer.
Running the program:: To Run A C++ program after compilation we use the
RUN option of Run menu item or press CTRL + F9 keys from the keyboard. It will
result in creating a file with the same name as the source file but with >EXE
extension like FIRST.EXE
The getch function:: in the program helps to display the result on the screen
automatically.

A Class in C++
Class is a user define data type.
Class is a collection of objects of similar type.
Class Declarations.
class name
{
Data types;
Member functions
};

What is a class ?
A class is
An abstract datatype similar to a C structure.
A representation of objects and the sets of operations that can
be applied to such objects.

Class consists of Data members and methods.

Definition of a class

General form of a class :


Class class_name
{
Data Members;
Methods;
};

e.g.,
Class A
{
int i ;
char *strng;
Void f (int , char *);
int g() ;
};

Definition of a class (Contd)


e.g.,
Class Circle
{
int radius;
int XCentre;
int YCentre;
int GetRadius ();
int SetData;
int GetXCentre ();
int GetYCentre ();
};

Definition of a class (Contd)


private, protected,public are called visibility labels.

The members that are declared private can be accessed


only from within the class.

Public members can be accessed from outside the class


also.
In C++, data can be hidden by making it private.
Encapsulation is thus achieved.

Definition of a class (Contd)


Private area
No entry

Data
Functions
Public area

Entry
allowed

Data
Functions

Synonyms
Operations - "method selectors," "method
interfaces," "messages," or "methods",
services,member function, Instance Method
Object - instance, class instance, surrogate,
entity.
Class - type
Base Class - Super Class, Parent Class.
Derived Class - subtype, subclass, Child
class.

Member Variable - state variable, instance


variable, data member, attribute, field, slot.
Inheritance - subclassing, derivation, prefixing.
Abstract Class - interface, protocol, type,
virtual class, signature.
Object name - object reference, Handle, object
identifier.

Practice Questions 1
Q1 Identify the drawback of using
procedure-oriented programming, if any:
a) Data is hidden from external functions
b) New functions can be added whenever
necessary
c) Does not reflect real world problems
d) All of the above

Practice Questions 2
Q2 Which one of the following OOP
concepts enables reusability of
components?
a) Inheritance
b) Encapsulation
c) Polymorphism
d) All of the above

Practice Questions 3
Q3 The concept of hierarchical
classification is related to:
a) Abstraction
b) Inheritance
c) Function overloading
d) None

Practice Questions 4
Q4 Comments in C++ starts with
_______ symbol.
a) //
b) \\
c) **
d) None of the above

Practice Questions 5
Q5 return is an example of a
a) Keyword
b) Function
c) Statement
d) Comment

Practice Questions 6
Q6 The declaration of global variables
must be made
a)inside the function
b) outside the function
c) in a function header line
d) None of the above

Practice Questions 7
Q7 Consider the following code:
cout<< Welcome;
This is an example of
a) Return type
b) Function
c) Both a and c
d) C++ statement

Answers

Q1 c
Q2 a
Q3 b
Q4 a
Q5 a
Q6 b
Q7 d

Programming Practice Question


Q1 Create a simple C++ program to
display your name and fav. Color
Q2 Create a simple C++ program to
perform the four basic operations like
(+,-,*,/).
Q3 Write a program to read two
numbers from the keyboard and display
the larger value on the screen.

Thank You
Please forward your query
To :bminocha@amity.edu
Cc: manoj.amity@panafnet.com

PAN African e-Network Project


PGDIT
Object Oriented Programming
Semester 2nd
Session - 2

Dr. Bhawna Minocha

Session Outline

Tokens
Expression
Decision Control Structures
Loop Control Structures
Practice Questions & answers

C++ TOKENS
Tokens are the smallest individual units in a
program.
Tokens are the various C++ program elements
which are identified by the compiler.
Various C++ Tokens are as:
Keywords
Identifiers
Constants
Operators
Special characters (#,?)

KEYWORDS

Keywords are the reserved words which have


standard predefined meaning in C++.
These cant be used as the names for the
program variables or other user defined
programs.

Eg. float, int, enum, long ,double, switch etc.

IDENTIFIERS
Identifiers refers to the names of variables, functions,
arrays, class etc created by the programmer.
Rules for writing identifiers:
Only alphabetic characters, digits and underscores are
permitted.
The name cannot start with a digit.
Uppercase and lowercase letters are distinct(C++ is a
case sensitive). Like RESULT variable is not the same
as the result variable or the Result variable. These are
three different variable identifiers.
A declared keyword cant be used as a variable name.

VARIABLES

Variable is the name given to location in memory

where value of variable is stored.


eg. a=20, stores the value 20 at memory location
named as a.
We must first declare a variable specifying which data
type we want it to be.
The syntax to declare a new variable is
datatype variable-name;
Example
int a;
float mynumber;
char a,b,c;

Declaration of variables
The integer data types short, long and int can be
either signed or unsigned based on the range of
numbers needed
Signed types can represent both +ve and ve
values,
unsigned types can only represent +ve values (and
zero)
unsigned short int num; // only +ve values
signed int balance; // +ve & -ve values

CONSTANTS
Constants refers to the fixed values that do not change
during the execution of a program.

int a= 123 // decimal integer


float b =12.34 // floating point integer
char *s= AB // string constant-occupies 3
bytes(includes the null character)
char c= A // character constant- occupies only 1
byte.

QUALIFIERS
Qualifiers are the additional attributes to the data
type.
Eg. 12345L // long integer constant
7865435UL // unsigned long integer

Expressions
An expression is a combination of constants , variables
and operators to form an executable statement which
computes a value.
The resultant value must be of valid data type that can
be assigned to a variable.

For example :
sum=a+b;
In the given statement ,the expression a+b consists of
an operator + and operands a and b. The result of this
expression will be assigned to variable sum.

Some Valid C++ Expressions


Algebraic Expression

C++ Expression

(ab)/(c+d)

( a b ) / (c + d )

4 x2 + 3x + 5

4 *x*x +3*x +5

(sin2x cos2x)1/3

pow (( sin (x) * sin (x) cos (x) * cos (x)),1/3)

X2 + y2
2 cos x

(x * x + y * y) / (2 * cos (x))

Operators
An operator is a special symbol that specifies what

operation is performed on one or more operands


where an operand can be a variable , constant or
expression.
An operation is an action(s) performed on one or
more operands that evaluates mathematical
expression or change the data
In C++, the operator can be unary , binary or ternary.
If an operator operates on single operand then it is
termed as an unary operator .
If an operator operates on two operands ,it is called
binary operator.

Operators
C++
provides
a
rich
set
of
operators.
Some of C++ operators are inherited from C language while
many other new operators are introduced in to it.
Operators Inherited from C

Additional C++ Operators

Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Conditional Operators
Unary Operators
Type cast operator

Stream Input Output Operator(>>,


<<)
Scope Resolution Operator( ::)
Line feed Operator (endl)
Memory Allocation operator (new)
Memory Deallocation operator
(delete)

Operators in C++

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Increment/Decrement
Operator
6. Assignment Operators
7. Conditional Operators
8. Comma Operator
9. Sizeof Operator
10 Scope Resolution
Operator
11 Type cast operator

3
7

4
5

Arithmetic Operators
The Arithmetic operators are used for mathematical calculations
The arithmetic operators are binary operators that work on any builtin types.
The following data shows 5 arithmetic operators with their meanings.
Operator

Meaning

Addition

Subtraction

Multiplication

Division

Modulus division

Arithmetic Operators:
The operands acted on by arithmetic operators must represent
numeric values. Thus the operands can be integer quantities, floating
point quantities or characters. The Arithmetic operators when used
with characters ,operate on ASCII values of the characters.
If a=7 and b=3
(Integer)

If a=10.5 and b=2.0


(float)

a+b

10

12.50000

a-b

8.500000

a*b

21

21.00000

a/b

5.250000

a%b

Not applicable as
per condition

Integer Division
Integer division produces an integer result
Truncates the result
Examples
3 / 2 evaluates to 1
4 / 6 evaluates to 0
10 / 3 evaluates to 3
MOD :: Produces the remainder of the division
Examples
5 % 2 evaluates to 1
12 % 4 evaluates to 0
4 % 5 evaluates to 4

Sample program
#include<iostream.h>
int main()
{
int months,days;
cout << enter the days ;
cin >> days;
months = days/30;
days = days%30;
cout << months=<<months;
cout << days= <<days;
return 0;
}

Output:
Enter the days 365
months = 12, days = 5

Operators and Precedence


Consider mx + b
Consider m*x + b which of the following is it equivalent to
(m * x) + b
m * (x + b)
Operator precedence tells how to evaluate expressions
Standard precedence order
()
Evaluate first, if nested innermost
done first
* / %
Evaluate second. If there are several,
then evaluate from left-to-right
+ Evaluate third. If there are several,
then evaluate from left-to-right

Operator Precedence
Example
20 - 4 / 5
(4
((4
((4
((4
(20 -((4
(20 -((4

Answer 17

* 2
/
/
/
/
/
/

5)
5)
5)
5)
5)
5)

*
*
*
*
*

3 * 5

2)
2)
(3 * 5)
2)
((3 * 5) % 4)
2))
((3 * 5) % 4)
2)) + ((3 * 5) % 4)

% 4

Relational Operators
We often compare two quantities and depending on their relation
take certain decision.
Comparing the age of two person, price of two items.
Relational operators are used to check relation between two
operands.
In other words, the operators used to make comparisons between
two operands are called Relational Operators.
Relational operators are binary operators and hence require two
operands.
The value of relational expression is either true or false.
If It is 1(non zero) the specified relation is true and 0(zero) If the
specified relation is false.

Relational Operators
Operator Operation
Symbol Performed

Use

Result

<

less than

Exp1<exp2

True if expr1 is less than expr2


else false

<=

Less than or equal to

Exp1<=exp2

True if expr1 is less than or


equal to expr2 else false

>

Greater than

Exp1>exp2

True if expr1 is greater than


expr2 else false

>=

Greater than or equal


to

Exp1>=exp2

True if expr1 is greater than or


equal to expr2 else false

==

Equal to

Exp1= =exp2

True if expr1 is equal to expr2


else false

!=

Not equal to

Exp1 != exp2

True if expr1 is not equal to


expr2 else false

Relational Operators:
Operators
First Group

<,<=,>,>=

Second Group

==, !=

Examples
If i=2, f=3.5 where I is integer type variable and f
is floating type variable
(i+f)>=5
will give result true and return
value 1.
f>3
Will interpret it to be true and
result is 1.

Logical Operators:
Logical operators are used to combine one or more relational
expressions that results in formation of complex expressions known
as logical expressions.
Like Relational operators, the logical operators evaluate the result of
logical expressions in terms of Boolean values that can only be true
(non zero) or false(zero) according to the result of the logical
expression.
Operator

Operation Performed

Use

&&

Logical AND

Expr1 && Expr 2

||

Logical OR

Expr1 || Expr 2

Logical NOT

! (expr)

Logical Operators:
The following table shows the operation of Logical AND ,logical
OR and Logical NOT
Expr1

Expr2

Expr1 &&
EXpr2

Expr1 ||
Expr2

! (Expr 1)

False

False

False

False

True

False

True

False

True

True

True

False

False

True

False

True

True

True

True

False

Logical Operators:
Examples
Consider an example where x has an integer
value 3 and y has a character value b then
(x==3) && (y==b)

True

(x<2 ) && (y==a)

False

(x>4) || (y=a)

False

! (x==3)

False

Logical Operators Evaluation:


In case of Logical AND expression if the first
condition evaluates to FALSE then there is no need to evaluate the
other conditions. Similarly in case of logical OR expression if the
first condition evaluates to TRUE then there is no need to evaluate
the other condition.

Logical Operators Precedence:


The Logical NOT (!) operator has a higher precedence
than the others. The Logical AND (&&) operator has higher
precedence than logical OR (||) operator.
The Logical AND and OR operators have lower precedence than the
relational and arithmetic operators.

Bitwise Operators:
C++ provides an extensive bit manipulation
operators for programmers who want to communicate directly with
the hardware. These operators are used for testing bits or shifting
them either right to left or left to right. The Bitwise operators are
Operator
&
|

Meaning
Bitwise AND
Bitwise OR

Bitwise exclusive OR

<<

>>
~

Shift left
Shift right
ones complement

Assignment Operator:
Assignment operator (=) is the most commonly used binary
operator in C++. It evaluates the operand on right hand side and
then assigns the resulting value to a variable on the left hand side.
The right operand can be a variable, constant ,function call or
expression. The general form of representing assignment operator
is :: variable = expression/constant/function call
For example ::
A=3 ; // constant
X=y+10; // expression
Consider a statement x=y=z=3;
Such type of statement in which a single value is given to a
number of variables is called multiple assignment statement.

Assignment Operator (contd):


That is value 3 is assigned to the variables x, y and z .The
assignment operator (=) has a right to left associativity , so the
above expression is interpreted as
(x=(y=(z=3)));
C has set of shorthand assignment operators of the form
Assignment Operator

Shorthand Operator

a=a+1

a+=1

a=a-1

a-=1

a=a*(n+1)

a*=n+1

a=a/(n+1)

a/=n+1

a=a%b

a%=b

Advantages of using shorthand operators:

* What appears on left hand side need not be repeated and


therefore it becomes easier to write.
* The statement is more concise and easier to read
* The statement is more efficient
Comparison of = and = =:
The assignment operator(=) is used to assign a value to a
variable where as the equality operator (= =) used to compare
two operands.
Note :: The assignment operator has lower precedence than
arithmetic , relational , bitwise and logical operators.

Increment (++) & Decrement (--) Operator:


In certain situations there is need to increrase or decrease a
variable by 1 continuously for some time. So , C++ provides an
Increment opertaor and decrement operator to increase or decrease
the value of the operand by 1respectively.
++ m; or

m++;

-- m;

m--;

or

++m is equal to m=m+1 shorthand form :: (m+=1)


--m is equal to m=m-1 shorthand form :: (m-=1)
m=5
y=++m
The prefix operator adds 1 to the operand and then the
result is assigned to a variable on left.

Two Ways of representing Increment (++) & Decrement (--)


Operator:
1) As a prefix i.e. operator preceded the variable Eg. ++i, --j
2) As a postfix i.e. operator follows the variable Eg. i--, j++
In case of Prefix increment operator (eg.++i) , the value of the
variable will be first incremented then incremented value will
be used in the expression in which it appears.
In case of Postfix increment operator (eg.i++) , the current value
of the variable in the expression in which it appears and then
the value is incremented by 1.
In order to understand the difference between prefix and postfix
increment operator ,let us consider an example on the next
slide.

Difference between Prefix and postfix Operators:


1) Suppose an integer variable i holds a value 10, then on
executing statement. j=i++;
results in j=10 and i=11;Since it is a postfix operator so value of
i (10) is first assigned to j and then incremented by 1 (i.e.
10+1=11)
2) If instead of the above statement , we have a statement j=++i;
then it results in j=11 and i=11 .Since it is a prefix increment
operator so value of i is first incremented by 1 (i.e. 10+1=11)
and then it is assigned to j(11).
Note :: In the similar way , the postfix and the prefix
decrement operator works.

Difference between Prefix and postfix Operators:


Prefix increment operator

Post fix increment operator

#include<iostream.h>
#include<conio.h>
void main()
{
int i=1;
printf(i=%d\n,i);
printf(i=%d\n,++i);
printf(i=%d\n,i);
getch();
}

#include<iostream.h>
#include<conio.h>
void main()
{
int i=1;
printf(i=%d\n,i);
printf(i=%d\n,i++);
printf(i=%d\n,i);
getch();
}

Prefix increment operator

Post fix increment operator

Output1(No change)
2(Alteration before
execution)
2 (No change)

Output1(No change)
1(No change because
alternation after execution)
2 (New incremented value
by 1)

Conditional Operator or Ternary Operator:


A conditional operator or Ternary operator (which operates
on three operands) pair in C(?:) used to construct conditional
expression of the form
exp 1 ? exp 2 : exp 3
Where exp 1 exp 2 and exp 3 are expressions.
How it works:
here exp1 is a test condition which is evaluated first. If it is
true then expr2 is evaluated and this becomes the value of
conditional expression. However if it is false then expr3 is evaluated
and this becomes the value of conditional expression. The value of
conditional expression can also be assigned to another variable.

Conditional Operator or Ternary Operator:


Example: c= (a>b) ? a:b;
j= (i>10)? 1:100;
k= (a>b) ? cout<< a: cout <<b;
In the first example if (a>b) is true then a becomes value of the
conditional expression and if it is false then b becomes value of the
conditional expression which is finally assigned to c. The
conditional operator is a short hand version of if-else statement. The
first example can be represented as ::
if (a> b)
c=a;
else
c=b;

Conditional Operator or Ternary Operator

To find greatest number among three numbers.


e.g
(a>b)?((a>c)?a:c):(b>c)?b:c)

e.g
7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5.
7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2.
5>3 ? a : b // returns the value of a, since 5 is
greater than 3.

Conditional Operator or Ternary Operator

#include<iostream.h>
#include<conio.h>
void main()
{
int a=10 ,b=5,c;
c=a>b?a:c;
cout<<c=<<c;
getch();
}

The Comma Operator


The comma operator is used quite differently from
most C++ operators. The Comma operator is used to
declare more than one variable in a single line. The
comma operator associates from left to right and
therefore the first variable is declared before the second
variable and so on.
For example :: int x , y, z;
float a,b,c
Here the comma operator is a separator in the variable
declaration. This operator is also used in the for loop for
multiple initialization.

The sizeof Operator


is a unary operator that returns the number of bytes required to store a variable
or a data type. The syntax of using sizeOf operator is

Sizeof ( data type or variable)


Consider the variables a,b of int and float data ypes respectively
Sizeof (a); // returns 2
Sizeof (b) ; // returns 4
Sizeof( double) ; // returns 8
The sizeof operator is very useful when transferring a program from one
computer to another as number of bytes allocated to various data types may
vary from computer to computer having different compilers.

EXAMPLE OF SIZEOF OPERATOR:


void main()
{
int a;
float b;
double c;
char d;

output:

cout<<sizeof (a);

// 2

cout<<sizeof (b);

//4

cout<<sizeof (c);

//8

cout<<sizeof (d);

//1

getch();
}

Scope resolution operator: is used to access


the global variable.
int a=20;
int main()
{
int a=10;
cout<<a=<<a;
cout<<::a;
getch();
}

output: a=10 20

Explicit type casting operator


Type casting operators allow you to convert a
data of a one type to another type.
The simplest one, which has been inherited from
the C language, is to precede the expression to
be converted by the new type enclosed between
parentheses (()):

Explicit type casting operator - Example


Below code converts the float number 3.14 to an integer value
(3), the remainder is lost.
int i;
float f = 3.14;
i = (int) f;
Here the typecasting operator was (int).
Another way to do the same thing in C++ is using the
functional notation: preceding the expression to be converted
by the type and enclosing the expression between parentheses:
i = int ( f );

Language Constructs

Control Structures

Control Statements are used to control the flow of


program's execution. Control Structures enable us to
execute a certain set of commands based on a
condition.
The condition should be specified at the design time and
at run time ,the condition is evaluated, and depending on
the result of the condition ,the block of code following the
condition is executed . These structures are also known
as decision structures.
There are various control statements supported by C++
which are broadly categorized in to two ways :
Decision control Statements
Loop Control Statements

Decision Control Statements

The decision control statements alter the normal


sequential execution of statements of the program
depending upon the test condition to be carried out at a
particular point in the program. The decision to be taken
regarding where the control should transfer depends
upon the outcome of the test condition.
C++ supports following decision constructs
If
If else statement
Switch statement
Go to statement

Selections & Decision

If then selection structure


The If...Then selection structure performs an
indicated action only when the condition is
True; otherwise the action is skipped.
Syntax of the If...Then selection
If <condition>
{
statement(s);
}
The keyword if tells the compiler that a
decision control statement(s) to be executed.

If then selection structure


If the condition is true (non zero) then the
statement immediately following is executed.
If the condition is false then the statement is
ignored and control passes to the next
statement following the if construct.
In case of a single statement , we may or may
not require to enclose it in braces.

Program to check whether a


number is even or not?
#include <iostream.h>
#include <conio.h>
int main()
{
clrscr();
int num;
cout<< Enter the number=;
cin>>num;
if (num % 2 ==0)
{

Program to check whether a


number is even or not? (contd)
{
cout << Number is even <<endl;
}
cout<< End of program;
getch();
return 0;
}
Output:
Enter the number=10
Number is even
End of program

If else selection structure


In case of if statement , the block of statements are
executed only when the condition is true otherwise
the control is transferred to the next statement
following the if block. But if some specific statements
are to be executed in both the cases ( either
comdition is TRUE or FALSE) the else statement is
used.
The if statement consists of keyword if followed by a
statement or a block of statements, then a keyword
else followed by another statement or a block of
statements.

If then else selection structure


Syntax of the If...else selection
If <condition>
{
statement 1;
statement 2;
}
else
{
statement 3;
statement 4;
}

Program to check whether a


number is even or odd?
#include <iostream.h>
#include <conio.h>
Int main()
{
clrscr();
int num;
cout<< Enter the number=;
cin>>sum;
if (num % 2 ==0)
cout << Number is even ;

Program to check whether a


number is even or not? (contd)
else
cout << Number is odd ;
getch();
return 0;
}
Output:
Enter the number=10
Number is even

Nested IfElse selection structure


In the if-else statement, the body of if block and else
block consists of a set of statements. It is also
possible that an entire if-else statement can occur
either within the body of if statement or/and in the
body of else statement
Syntax of the Nested If...Then...Else selection
structure
You can use Nested If either of the methods as
shown in next slides

Nested IfElse selection structure


Method 1
If ( condition 1 )
{
if (condition 2 )
statement 1;
else
statement 2;
}
else
statement 3;

Nested IfElse selection structure


Method 2
If ( condition 1 )
statement 1;
else
{
if (condition 2 )
statement 2
else
statement 3;
}

Program to calculate the greatest of three


numbers using nested if-else statement
#include <iostream.h>
#include <conio.h>
Int main()
{
clrscr();
int a,b,c;
cout<< Enter three numbers (A,B,C);
cin>>a>>b>>c;
if (a>b)
{
if (a>c)

Program to calculate the greatest of three


numbers using nested if-else statement
cout<< A= <<a <<is greatest<<endl;
else
cout<< C= <<c <<is greatest<<endl;
}
else
{
if (b>c)
cout<< B= <<b <<is greatest<<endl;
else
cout<< C= <<c <<is greatest<<endl;
}

Program to calculate the greatest of


three numbers using nested if-else
statement
getch();
return 0;
}
Output:
Enter three numbers (A,B,C) : 10 20 30
C= 30 is greatest

IfElse if ladder
In the programs involving multiple test conditions ,
the nested if-else statements makes the program
very difficult to write and understand especially if they
are nested more deeply because as the number of
test conditions go on increasing ,care must be taken
to match multiple if-else constructs. In order to solve
the problem ,there is another way to write the same
statements using if else-if ladder.
The Syntax of if else if ladder is shown in next slide.

IfElse if ladder Syntax


If (condition 1)
statement 1;
else if (condition 2)
statement 2;
else if (condition 3)
statement 3;
.
.
.
else
default statement;

Using a switch statement

Which variable are you going to switch on?


Which cases will you respond to?
Can provide a default case
Type the skeleton of the switch statement first
and compile
then flesh it out with cases
remember the break statement at the end of
each case
67

Using a switch statement


switch(x)
{
case 1:
//statements here ...
break;
case 2:
//statements here ...
break;
default:
//statements here ...
break;
}

68

Using the switch statement


switch(x)
{
case 1:
cout << "you entered 1" << endl;
break;
case 2:
cout << "you entered 2" << endl;
break;
default:
cout << "you didn't enter 1 or 2" << endl;
break;
}

69

The comparison of switch and if else


statements
The switch statement is a multi way decision making
statement which selects one of several alternatives
based on the value of single variable or expression.
The switch statement is mainly used to replace
multiple if else if statement. The if-else-if statement
causes performance degradation as several
conditions need to be evaluated before a particular
condition is satisfied.
The switch structure starts with a keyword switch
followed by the expression enclosed in the
parentheses. The value of the expression is
compared with each of the labels . A case is normally
terminated with the break statement.

LOOPs

Loops make it possible to repeat a


section of code a number of times. This
is used for doing calculations, searching
and sorting lists etc.
Start of Loop
Code
End of loop

LOOPs
In order to understand the concept of loops , let us
consider a simple program which calculates the cube
of first 3 natural numbers.
#include <iostream.h>
#include <conio.h>
int main()
{
int a,b,c;
a=1;
cout << Cube of 1= << a*a*a;
b=1;

LOOPs (contd..)
b=2;
cout << Cube of 2= << b*b*b;
c=3;
cout << Cube of 3= << c*c*c;
getch();
return 0;
}
But if we want to find out the cubes first 10000 natural
nos. then we would have to repeat the steps again
and again which would be cumbersome and time
consuming process.

Loop Structures
Loop structures allow you to execute one or more lines
of codes repetitively. Many tasks consist of trivial
operations that must be repeated over and over again,
and looping structures are an important part of any
programming language.
C++ supports the following Loop statements.
dowhile Loop
whileloop
forloop

Loop structures do while


The do while loop is similar to the while loop
except that its test condition is evaluated at the end
of the loop instead at the beginning as in the case of
while loop. So in the case of do while the body of
the loop always executes atleast once even if the
test condition evaluates to false during the first
iteration.
If the test condition evaluates to TRUE , the body of
the loop is executed and it keeps on executing until
the test condition is FALSE and then control transfer
to the next executable statement following the do
while loop.
75

Loop structures do while


The do while loop:
do {
statement;
statement;
} while( condition);
statement;

Equivalent to:
// something
while( condition) {
// something
}
76

Loop structures while.... loop


The while loop is used to carry out looping
operations. It lets you execute a set of statements
repeatedly as long as condition evaluates to true. It
is mostly used in those cases where the
programmer doesnt know in advance how many
times the loop will be executed.
If the test condition evaluates to TRUE , the body of
the loop is executed and it keeps on executing until
the test condition is FALSE and then control transfer
to the next executable statement following the do
while loop.
77

loop Structures - Iteration


The while loop:
while ( condition )
{
statement1;
statement 2;
}
OR
while ( condition )
statement;

Equivalent to:
for( ; condition ; ) {
// do something
}
78

Practice Questions
Q1 What will be the value ox x after the
following two operations::
a = 10, b = 15
x=(a<b) ? a :b

Practice Questions
Q2 If x=2,y=4,z=10 then compute the
following expression:
a) x < y + z
2 < 4 +10
2< 14
true (1)

Practice Questions
Q3 If x=2,y=4,z=10 then compute the
following expression:
a) y + z = = x - y

Practice Questions
Q4 Which loops body is executed
atleast once?

Practice Questions
Q4 What is the difference between
if (i= = j) and if (I = j) ?

Practice Questions 7
Q5 ++x is an example of
prefix operator
postfix operator

Programming Practice Question


Q1 Calculate the factorial of a number using
for loop.
Q2 Print the multiplication table of a given no.
using do while loop
Q3 Calculate the division of a student
according to marks obtained in 4 subjects.
Q4 Evaluate the expression ::
d / b + a b % c * 5 where a=6 b=5 c=3 and
d=10.

Thank You
Please forward your query
To :bminocha@amity.edu
Cc: manoj.amity@panafnet.com

PAN African e-Network Project


PGDIT
Object Oriented Programming
Semester 2nd
Session - 3

Dr. Bhawna Minocha

Session Outline

for loop
Functions
Storage classes
Reference variable
Parameter passing mechanism
Function overloading
Inline function
Class
Friend function

For Loop
The for Next loop is one of the oldest loop
structures in programming languages. do Loop works
well when we dont know how many times we need to
execute the statements in the loop. When we know
we must execute a specific no. of times ,however a
for loop is a better choice.
This is a loop with an in-built counter. The syntax is:
for (initialization ; condition; increment/decrement)
{
statements;
}

ForNext Loop

where
initialization expression is used to initialize the loop
control variable.
Condition is a relational or logical expression that
determines the number of iterations desired and
whether the loop should continue iterating or not.
The Increment/decrement expression modifies the
value of the loopcontrol variable each time the loop is
executed.

The three expressions of the loop are


separated ay two semi colons.

Loop Structures - Iteration


The for loop:
Terminating condition
Start condition

for(k = 0; k < 10; k++ ) {


cout << The square of << k << is
<< k * k << endl;
}
Action taking place at
the end of each iteration

Program to calculate the average of


n numbers:
#include <iostream.h>
#include <conio.h>
int main()
{
clrscr();
int n,num,sum=0;
cout<< How many numbers=;
cin>>n;
cout<< Enter the numbers=<<endl;

Program to calculate the average of n


numbers:
for (int i=1; i<=n; i++)
{
cin >>num;
sum=sum+num;
}
float avg= float(sum)/n;
cout<< Average is=<<avg<<endl;
getch();
return 0;
}

Program to calculate the average of


n numbers:
Output:
How many numbers? :5
Enter the numbes
10 12 20 30 60 // press enter
Average is = 26.4

Functions
Functions are building blocks of the programs.
They make the programs more modular and
easy to read and manage.
All C++ programs must contain the function
main( ).
The execution of the program starts from the
function main( ).

Function
There are two kinds of functions
1. library functions or built-in functions
2.user defined functions
Library functions string functionstrcpy(),strcmp,strcat .
mathematical functions-pow,sqrt,sin(x) etc

Functions
The general form of the function is: return_type function_name(parameter list)
{
body of the function
}

Functions
The function consists of two parts function
header and function body. The function
header is:

return_type function_name(parameter);

Functions
For example,
int factorial(int n, float j)
is the function header of the function
factorial.
The return type is of integer which means
function should return data of type integer.
The parameter list contains two variables
n and j of type integer and float
respectively.

Functions
Three things to remember
Function Declaration
Function Calling
Function Definition

Function Declaration
A call to the function cannot be made unless
it is declared. The general form of the
declaration is:return_type function_name(parameter list);

Function
For example function declaration
int factorial(int n1,float j1);
Another method
int factorial(int , float);
Arguments contain the actual value which is to be
passed to the function when it is called should
correspond with the data types of the parameters.

Syntax of function calling is


function name(argument list);

Types of Function
Function with no argument and no return
type
Function with argument and no return type
Function with no argument and return type
Function with argument and return type

Function
The Return Statement and Return values
A return statement is used to exit from the
function where it is.
It returns the execution of the program to the
point where the function call was made.
It returns a value to the calling code.
The general form of the return statement is:return expression;

Function
The expression evaluates to a value which
has type same as the return type specified
in the function declaration. For example
the statement,
return(n);
If a function has return type as void then
return statement does not contain any
expression. It is written as:
return;

//programtoaddtwonumbersusingfunctionswith
argumentandnoreturntype.
#include<stdio.h>
#include<conio.h>
voidadd(int,int);
voidmain()
{
intc,d;
printf(Entertwonumbers:);
scanf(%d%d,&a,&b);
add(a,b);
getch();
}

voidadd(intc,intd)
{
inttemp;
temp=c+d;
printf(%d,temp);
}

//programtoaddtwonumbersusingfunctionswith
argumentandreturntype.
#include<stdio.h>
#include<conio.h>
intadd(int,int);
voidmain()
{
intc,d,sum;
printf(Entertwonumbers:);
scanf(%d%d,&a,&b);
sum=add(a,b);
printf(%d,sum);
getch();
}

intadd(intc,intd)
{
intsum;
sum=c+d;
return(sum);
}
//programtoaddtwonumbersusingfunctionswithno
argumentsbutreturntype.
#include<stdio.h>
#include<conio.h>
intadd();
voidmain()
{

intsum;
sum=add();
printf(%d,sum);
getch();
}
intadd()
{
inta,b,sum;
printf(Entertwonumbers:);
scanf(%d%d,&a,&b);
sum=a+b;
return(sum);
}

//programinwhichafunctionacceptsnoargumentsandreturns
novalue.
#include<stdio.h>
#include<conio.h>
voidfunc1();
voidfunc2();
voidmain();
{
func1();
func2();
func1();
getch();
}
voidfunc1()
{

inti;
for(i=1;i<10;i++)
printf(%d,i);
printf(\n);
}
voidfunc2()
{
intj;
for(j=1;j<10;j++)
printf(*);
printf(\n);
}

Reference Variable
Provides an alternative name for a previously defined
variable.
Reference variable is created as follows
Datatype &reference name = variable name

For example: float &sum=total


total is a float type variable
sum is the alternative name declared to represent the
variable total

Application in passing arguments to function


Example void f(int &x)
{
x=x+10;
}

void main()
{
int m=10;
f(m);
}
When the function call f(m) is executed ,the following initialization
occurs.
int &x=m;
x becomes an alias of m after executing the statement f(m)
Such function calls are known as call by reference.

Storage Classes and Scope


The storage class of a variable specify how long
a variable remains in memory. In other words ,it
determines the lifetime during which memory is
associated with a variable.
A variable which is defined inside a function is
called a local variable. The memory is allocated
to local variable each time the control enters the
function and released when the control leaves
the function.
Also ,the scope of local variable is limited to
the function in which it is declared and it
cannot be accessed in other function.

#include<iostream.h>
#include<conio.h>
int x=5,y=10;//global variable
int main()
{
int z=15//local variable of main()
void abc();
abc();
cout<<z=<<z;
cout<<\nx=<<x;
abc();
getch();
}
void abc()
{
int w;
w=x+y;
cout<<\nw=<<w;
}

In this program ,z is local variable in the


function main() and w is a local variable in
function abc().Their scope is limited only in
the functions in which they are
declared.Hence variable z cannot be
accessed in the body of the function
abc().Similarly ,variable w cannot be
accessed in main().The lifetime of variable
w lasts from the time function abc() is
invoked to the time the control exits from
the function.

Global Variable-A variable which is defined outside all functions are


called global variables .Global variable are also called external
variables as they are defined externally to all the functions. i.e at the
beginning.

#include<iostream.h>
#include<conio.h>
int x=10; //Global variable
int main()
{
int x=5; //local variable in function main()
cout<<local x=<<x; //accessing local variable
cout<<\n Global x=<<::x; //accessing global variable
getch();
} outputlocal x =5
Global x=10

Automatic Variable
Automatic variable(s) are declared inside a
block or function in which they are to be
used.In other words,their scope is limited to
only the block or function where they are
declared.
Automatic variables are called so because
they are created (i.e assigned memory
automatically when the control enters the
block or function and are destroyed (i.e
release memory) automatically when the
control exits from the function.

Program to demonstrate the scope and lifetime of


#include<iostream.h>
automatic variables?
#include<conio.h>
int main()
{
auto int j=15; //declaration of automatic variable
{
auto int j=20;
cout<<in innermost block j=<<j;
}
abc();
cout<<\nIn outer block j=<<j;
getch();
}

void abc()
{
auto int j=25;
cout<<\n In function j=<<j;
}

Output:
In innermost block j=20
In function j=25
In outer block j=15
Declaration of automatic variable
auto int x=1; //or int x=1;
auto float z; // or float z; z is not initialized to
any value in the declaration so it contains
a garbage value.

Extern variable
The global variable can be accessed by all
the functions that follows its definition in a
source file.These variable can be used to
share information in a program that
expands across multiple files .
If a global variable is defined in some file
and you want to use this variable in some
other file in your multifile program then
declare such variable as extern variable
using the keyword extern.

Suppose FileA.cpp which contains definition of global


variable x
int x; //global variable definition
void f1()
{
}
void f2()
{
}
//fileb.cpp that uses global variable x
extern int x;//external variable declaration
void f3()
{
x=20; // //Accessing external variable x defined in FileA.cpp
}

Static variables
A static variable when declared within a
function retains its value between the
successive function calls.
The scope of static variables declared
inside the function is same as that of
automatic variable and its lifetime is same
as that of global variable except that it
comes into existence when the first
invocation is made to the function
containing it.

Program of static variable


#include<iostream.h>
#include<conio.h>
void main()
{
void fun_count();
fun_count();
fun_count();
fun_count();
getch();
}
void fun_count()
{
static int i;
i=i+1;
cout<<\nthis is function call no<<i;
}

OutputThis is function call no =1


This is function call no =2
This is function call no =3

Register variables
Automatic variables are normally stored in
memory but in order to speed up the
memory access to the variable ,we store it
in register using register storage class
specification.
A register variable can be declared as
register int counter=1;
By default ,it is initialized to a garbage value,
same as that of automatic variable.

Parameter passing mechanismCall by value vs. call by reference


When we write a function like
f ( int x ) {
cout<<value of x<<x;
x =3;
cout << value of X in f() : << x;

}
Here x is passed by value that means if we change
the value of x in f(), there will be no effect on the
value of argument that is sent at the time of f()
call.
This is called as pass-by-value

If we call function f() in main as


main() {
int i =10;
cout >> value of I before calling f() : >> i;
f(i);
cout >> value of I after calling f() : >> i;
}
Output will be :
value of I before calling f() : 10
Value of x 10
value of X in f() : 3
value of I after calling f() : 10

The value of i is set to 10 that is what is printed.


When we pass I to f(), its value is set to X so X is
10.
Later we change X to 3, that is what is printed.
The control comes back to main after calling f(),
the I is still 10.
Though we changed the value of parameter X in
f(), but the changes are not reflected in i.
This is because X is passed by value.

Pass by reference
When we write a function like
f ( int& x ) {
cout >> value of X in f() before change : >> x;

x =3;
cout >> value of X in f() before change : >> x;

}
Here x is passed by reference and not by value
that means if we change the value of x in f(),
there will be change in the value of argument
that is sent at the time of f() call. This is called as
pass-by-reference

If we call function f() in main as


main() {
int i =10;
cout >> value of i before calling f() : >> i;
f(i);
cout >> value of i after calling f() : >> i;
}
Output will be :
value of I before calling f() : 10
value of X in f() before change : 10
value of X in f() before change : 3
value of I after calling f() : 3

The value of i is set to 10 that is what is printed.


When we pass I to f(), its value is set to X so X is
10.
Later we change X to 3, that is what is printed.
The control comes back to main after calling f(),
the I is 3 now.
We changed the value of parameter X in f(), the
changes are now reflected in i.
This is because X is passed by reference.

Function Overloading
Function overloading is the practice of
declaring the same function with
different signatures. The same function
name will be used with different number
of parameters and parameters of
different type. But overloading of
functions with different return types are
not allowed.

Function Overloading
A function is overloaded when same name
is given to different function. However, the
two functions with the same name will
differ at least in one of the following.
a) The number of parameters
b) The data type of parameters
c) The order of appearance

Function Overloading
In general functions are overloaded when :
1. Functions differ in function
signature.
2. Return type of the functions is the
same.

#include <iostream>
class arith {
public:
void calc(int num1)
{
cout<<"Square of a given number: " <<num1*num1 <<endl;
}
void calc(int num1, int num2 )
{
cout<<"Product of two whole numbers: " <<num1*num2 <<endl;
}
};
void main() //begin of main function
{
arith a;
a.calc(5);
a.calc(6,7);
}

Function Overloading
If an exact match is not found ,the
complier uses the integral promotion to the
actual argument such as
float to double

Function Overloading
Where ambiguity arises
long square(long n);
double square(double x);
square(10);
will cause error because int argument can be
converted to either long or double (ambiguity)

Inline Function
Inline functions are functions where the
call is made to inline functions, the actual
code then gets placed in the calling
program.

Inline Function
What happens when an inline function is
written?
When the program is compiled, the code
present in function body is replaced in the
place of function call

Reason for the need of Inline Function:


a function call transfers the control from the calling
program to the function and after the execution of the
program returns the control back to the calling program
after the function call.
These concepts of function saved program space and
memory space are used because the function is stored
only in one place and is only executed when it is
called.
This concept of function execution may be time
consuming since the registers and other processes
must be saved before the function gets called.

The extra time needed and the process of saving is


valid for larger functions

Inline Function
Inline function eliminates the cost of calls
to small function
The general format of inline function is as
follows:
inline datatype function_name(arguments)

Inline Function

#include <iostream.h>
int multi(int);

void main( )
{
int x;
cout << \n Enter the Input Value: ;
cin>>x;
cout<<\n The Output is: << multi(x);
}
inline int multi(int x1)
{
return 5*x1;
}

Inline Function
Inline functions will save time and are
useful if the function is very small. If the
function is large, use of inline functions
must be avoided.
The inline directive will be totally of no use
when used for functions which are:
recursive
long
composed of loops

Introduction to CLASS
Class: A Class is a user defined data type
to implement an abstract object. Abstract
means to hide the details. A Class is a
combination of data and functions.
Data is called as data members and
functions are called as member functions.

Data Members
Data member or member functions may be
public, private or protected.
Public means data members or member
functions defining inside the class can be used
at outside the class.( in different class and in
main function)

Data Members
Private means data members and member
functions cant be used outside the class.
Protected means data member and
member functions can be used in the
same class and its derived class (at one
level) (not in main function).

Data Members
PRIVATE

PUBLIC

Class Example (Problem)


#include<iostream.h>
#include<stdio.h>
class student
{
int rollno;
char name[20];
};

void main()
{
student s;
cout<<enter the rollno.:;
cin>>s.rollno;
cout<<enter the name:;
gets(s.name);
cout<<rollno:<<s.rollno;
cout<<\nname:;
puts(s.name);
}

Class Example (Solution)


#include<iostream.h>
#include<stdio.h>
class student
{
public:
int rollno;
char name[20];
};

void main()
{
student s;
cout<<enter the rollno.:;
cin>>s.rollno;
cout<<enter the name:;
gets(s.name);
cout<<rollno:<<s.rollno;
cout<<\nname:;
puts(s.name);
}

Member Function Defining Inside the Class


#include<iostream.h>
#include<stdio.h>
class student
{
int rollno;
char name[20];
public:
void getdata()
{
cout<<enter the rollno.:;
cin>>rollno;
cout<<enter the name:;
gets(name);
}
void putdata()
{
cout<<rollno:<<rollno;
cout<<\nname:;
puts(name);
}
};
void main()
{
student s;
s.getdata();
s.putdata();
}

Data Members (Private : in this example)

Member Functions (Public: in this example)

Calling member function

Member Function Defining Outside the Class


#include<iostream.h>
#include<stdio.h>
class student
{
int rollno;
char name[20];
public:
void getdata();
void putdata();
};
void student :: getdata()
{
cout<<enter the rollno.:;
cin>>rollno;
cout<<enter the name:;
gets(name);
}

void student: :: putdata()


{
cout<<rollno:<<rollno;
cout<<\nname:;
puts(name);
}
void main()
{
student s;
s.getdata();
s.putdata();
}

Array of Class Objects


Problem:

#include<iostream.h>
#include<stdio.h>
class student
{
int rollno;
char name[20];
public:
void getdata();
void putdata();
};
void student :: getdata()
{
cout<<enter the rollno.:;
cin>>rollno;
cout<<enter the name:;
gets(name);
}

void student: :: putdata()


{
cout<<rollno:<<rollno;
cout<<\nname:;
puts(name);
}
void main()
{
student s1,s2;
s1.getdata();
s2.getdata();
s1.putdata();
s2.putdata();
}

Array of Class Objects

Solution:

#include<iostream.h>
#include<stdio.h>
class student
{
int rollno;
char name[20];
public:
void getdata();
void putdata();
};
void student :: getdata()
{
cout<<enter the rollno.:;
cin>>rollno;
cout<<enter the name:;
gets(name);
}
void student: :: putdata()
{
cout<<rollno:<<rollno;
cout<<\nname:;
puts(name);
}

void main()
{
student s[10];
int i: // index variable
for ( i = 0; i< 10; i++)
{
s[i].getdata ( );
}
for (i = 0 ; i < 10 ; i ++)
{
s[i].putdata( );
}
}

Memory Allocation of Object


class student
{
int rollno;
char name[20];
int marks;
};
student s;

rollno 2 bytes

name- 20 bytes

marks- 2 bytes

24 bytes

Friend function
In principle, private and protected
members of a class cannot be accessed
from outside the same class in which they
are declared.
However, this rule does not affect friends.
Friends are functions or classes declared
with the friend keyword.

Friend Function
A friend function has full access rights to
the private members of the class.
invoked like normal function
Cant access member names directly and
has to use an object name and dot
membership operator with each member
name.

Friend Function
Declared in either public or the private part
of a class
Object as its arguments

Class sample
{
int a,b;
Friend Function
public: void setdata()
{ a=25;
b=40;
}
friend float mean(sample s);
};
float mean (sample s)
{ return float (s.a+s.b)/2.0;
}
void main()
{sample x;
x.setvalue();
cout<<mean value=<<mean(x)<< \n;
getch();
}

A function friendly to two classes


Class ABC; //forward declaration
Class XYZ
{
int x;
public: void setvalue(int i)
{
x=i;
}
friend void max(XYZ,ABC);
};

A function friendly to two classes


Class ABC
{
int a;
public:
void setvalue(int i)
{
a=i;
}
friend void max(XYZ,ABC);
};
void max(XYZ m , ABC n)
{
If (m.x>=n.a)
cout<<m.x;
else
cout<<n.a;
}

A function friendly to two classes


void main()
{
ABC a;
a.setvalue(10);
XYZ x;
x.setvalue(20);
max(x,a);
getch();
}

1.

Which of the following is/are storage class


a)Automatic
b)static
c)register
d)all of the above

Q.no 2 When you pass a variable _____, C++


passes only the contents of the variable to the
receiving function
A.
B.
C.
D.

by reference
by value
globally
locally

What

is

function

overloading

a)calling a function from another function


b)Having more than one function of same name
c)calling

function

d)there is no such term in c/c++

from

itself

4 When the compiler cannot differentiate between


two overloaded constructors, they are called
A overloaded
B.destructed
C.ambiguous
D.dubious

Thank You
Please forward your query
To :bminocha@amity.edu
Cc: manoj.amity@panafnet.com

PAN African e-Network Project


PGDIT
Object Oriented Programming
Semester 2nd
Session - 4

Dr. Bhawna Minocha

Session outline

Inline Functions
Class
Array of class objects
Memory Allocation of objects
Friend function
Static data member and Static functions
Default Arguments
Constructor (Constructors in Array of Objects, Constructor overloading,
Copy Constructor)

Destructor

Inline Function
Inline functions are functions where the
call is made to inline functions, the actual
code then gets placed in the calling
program.

Inline Function
What happens when an inline function is
written?
When the program is compiled, the code
present in function body is replaced in the
place of function call

Reason for the need of Inline Function:


a function call transfers the control from the calling
program to the function and after the execution of the
program returns the control back to the calling program
after the function call.
These concepts of function saved program space and
memory space are used because the function is stored
only in one place and is only executed when it is
called.
This concept of function execution may be time
consuming since the registers and other processes
must be saved before the function gets called.

The extra time needed and the process of saving is


valid for larger functions

Inline Function
Inline function eliminates the cost of calls
to small function
The general format of inline function is as
follows:
inline datatype function_name(arguments)

Inline Function

#include <iostream.h>
int multi(int);

void main( )
{
int x;
cout << \n Enter the Input Value: ;
cin>>x;
cout<<\n The Output is: << multi(x);
}
inline int multi(int x1)
{
return 5*x1;
}

Inline Function
Inline functions will save time and are
useful if the function is very small. If the
function is large, use of inline functions
must be avoided.
The inline directive will be totally of no use
when used for functions which are:
recursive
long
composed of loops

Introduction to CLASS
Class: A Class is a user defined data type
to implement an abstract object. Abstract
means to hide the details. A Class is a
combination of data and functions.
Data is called as data members and
functions are called as member functions.

Introduction to CLASS
Class: A Class is a user defined data type
to implement an abstract object.
Abstract means to hide the details.
A Class is a combination of data and
functions.
Data is called as data members and
functions are called as member functions.

Data Members
Data member or member functions may be
public, private or protected.
Public means- data members or member
functions defining inside the class can be used
at outside the class.( in different class and in
main function)
Private means -data members and member
functions cant be used outside the class.
Protected means data member and member
functions can be used in the same class and its
derived class (at one level) (not in main
function).

Data Members
PRIVATE

PUBLIC

Class Example (Problem)


#include<iostream.h>
#include<stdio.h>
class student
{
int rollno;
char name[20];
};

void main()
{
student s;
cout<<enter the rollno.:;
cin>>s.rollno;
cout<<enter the name:;
gets(s.name);
cout<<rollno:<<s.rollno;
cout<<\nname:;
puts(s.name);
}

Class Example (Solution)


#include<iostream.h>
#include<stdio.h>
class student
{
public:
int rollno;
char name[20];
};

void main()
{
student s;
cout<<enter the rollno.:;
cin>>s.rollno;
cout<<enter the name:;
gets(s.name);
cout<<rollno:<<s.rollno;
cout<<\nname:;
puts(s.name);
}

Member Function Defining Inside the Class


#include<iostream.h>
#include<conio.h>
class student
{
int rollno;
char name[20];
public:
void getdata()
{
cout<<enter the rollno.:;
cin>>rollno;
cout<<enter the name:;
gets(name);
}

void putdata()
{
cout<<rollno:<<rollno;
cout<<\nname:;
puts(name);
}
};
void main()
{
student s; Calling member function
s.getdata();
s.putdata();
getch();
}

Member Function Defining Outside the Class


#include<iostream.h>
#include<stdio.h>
class student
{
int rollno;
char name[20];
public:
void getdata();
void putdata();
};
void student :: getdata()
{
cout<<enter the rollno.:;
cin>>rollno;
cout<<enter the name:;
gets(name);
}

void student: :: putdata()


{
cout<<rollno:<<rollno;
cout<<\nname:;
puts(name);
}
void main()
{
student s;
s.getdata();
s.putdata();
}

Array of Class Objects


#include<iostream.h>
#include<conio.h>
class student
{
int rollno;
char name[20];
public:
void getdata();
void putdata();
};
void student :: getdata()
{
cout<<enter the rollno.:;
cin>>rollno;
cout<<enter the name:;
gets(name); }
void student: :: putdata()
{
cout<<rollno:<<rollno;
cout<<\nname:;
puts(name);
}

void main()
{
student s[10];
int i: // index variable
for ( i = 0; i< 10; i++)
{
s[i].getdata ( );
}
for (i = 0 ; i < 10 ; i ++)
{
s[i].putdata( );
}
}

Memory Allocation of Object


class student
{
int rollno;
char name[20];
int marks;
};
student s;

rollno 2 bytes

name- 20 bytes

marks- 2 bytes

24 bytes

Friend function
In principle, private and protected
members of a class cannot be accessed
from outside the same class in which they
are declared.
However, this rule does not affect friends.
Friends are functions or classes declared
with the friend keyword.

Friend Function
A friend function has full access rights to the
private members of the class.
invoked like normal function
Cant access member names directly and has
to use an object name and dot membership
operator with each member name.

Friend Function
Declared in either public or the private part
of a class
Object as its arguments

A function friendly to two classes


Class ABC; //forward declaration
Class XYZ
{
int x;
public: void setvalue(int i)
{
x=i;
}
friend void max(XYZ,ABC);
};

A function friendly to two classes


Class ABC
{
int a;
public:
void setvalue(int i)
{
a=i;
}
friend void max(XYZ,ABC);
};

void max(XYZ m , ABC n)


{
If (m.x>=n.a)
cout<<m.x;
else
cout<<n.a;
}
void main()
{
ABC a;
a.setvalue(10);
XYZ x;
x.setvalue(20);
max(x,a);
getch();
}

STATIC DATA MEMBERS


Same as static variables in C
Its value is initialized to zero when the first
object of its class is created.
When a class field is static, only one
memory location is allocated
All members of the class share a single
storage location for a static data member
of that same class.
24

Using Static Class Members


When you create a non-static variable
within a function, a new variable is created
every time you call that function
When you create a static variable, the
variable maintains its memory address
and previous value for the life of the
program
Static variables are normally used to
maintain values common to entire class.

class Product
{
static int count;
int number;
public:
void getdata(int a)
{
number=a;
count++; }
void getcount()
{
cout<< count= <<count<<endl;
}
};

int Product:: count;

void main()
{
Product a, b, c;
a.getcount();
b.getcount();
c.getcount();
a.getdata(100);
b.getdata(200);
c.getdata(300);
cout<<after reading data<<\n;
a.getcount();
b.getcount();
c.getcount();
}

Static Class Member


Output:count: 0
count :0
count:0
After reading data
count:3
count :3
count :3

The type and scope of each static variable


must be defined outside the class
definition.
While defining static variable some initial
value can also be assigned to the variable.
Eg.
int Product:: count=10;

Using Static Functions


Member function can be declared as static.
A static function can have access to only other
static members declared in the same class.
A static member function can be called using the
class name instead of its objects.
Class_name:: function_name();
Static functions cannot access non-static
variables
Non-static functions can access static variables
(provided there is an object)
29

Class Test
{
int code;
static int count;
public:
void setcode()
{
code= ++count;
}
void showcode()
{
cout<< code= <<code;
}
static void showcount()
{
cout<<count=<<count<<\n;
} };

int Test :: count;


void main()
{
Test T1, T2;
T1.setcode();
T2.setcode();
Test :: showcount();
Test T3;
T3.setcode();
Test::showcount();
T1.showcode();
T2.showcode();
T3.showcode();
getch();
}

Output count = 2
count = 3
code=1
code=2
code=3

Default Arguments
Default argument is useful in situations
where a argument has the same value in
most function calls.
When the desired value is different from
the default value, the desired value can be
specified explicitly in function call. This
changes the default value of the argument
to be overridden for the duration of
function call.

Default Arguments
e.g- Consider example of a bank which
introduces a new money deposit scheme where
rate of interest is fixed to 5.5% per annum.
If we want to calculate the simple interest on
amount deposited by different customers under
this scheme, we have to make a function SI()
containing three parameters Principal(P),Rate of
Interest r and Time period t .On calling this
function for different values, we find the values
of arguments r and t remain the same for each
time, we need to pass only one argument.

Default Arguments
#include<iostream.h>
#include<conio.h>
float SI(float p,float r=5.5,float t=1.0);// function
declaration
void main()
{
float k;
k=SI(10000); //equivalent to k=SI(10000,5.5,1.0);
cout<<simple interest is=<<k<<endl;
k=SI(15000,6.0,0.5);
cout<<simple interest=<<k;
getch();
}

Default Arguments
float SI(float p,float r,float t)
{
float sil=(p*r*t)/100;
return sil;
}
Output- Simple interest=550
Simple interest=720

Constructor
A constructor is a special member function
having same name as that of the class to
which it belongs.
It is used to initialize some valid values
and allocate resources to the data
members of an object.
It is executed automatically when an
object of a class is created.
It does not have any return data type, not
even void.

Class classname
{
.
public:
classname(parameter list); // constructor
declaration .
};
Classname:: classname(parameter list)
//constructor definition.
{
}
They can also be defined inside the class as other
member functions.

#include<iostream.h>
class Rectangle
{
private:
int len, br;
public:
Rectangle()
{
len=5, br=4;
}
int area()
{
return (len*br);
}
};

void main()
{
Rectangle r1;
cout<<Area of
rectangle = ;
cout<<r1.area();
}
Output- Area of
rectangle = 20

The constructor to which no arguments are


passed is also called default constructor
Each time an object is created, a constructor
is invoked.
We can declare more than one constructor in
a class (constructor overloading)
Constructors can have default arguments.
Constructors should always be declared in
the public section of class.
Constructors cannot be inherited.

Parameterized constructors
class Rectangle
{
private:
int len, br;
public:
Rectangle(int a, int b)
{
len=a, br=b;
}
int area()
{
return (len*br);
}
};

void main()
{
Rectangle r1(5,4);
Rectangle r2(8,6);
cout<< \n Area of rectangle1
= << r1.area();
cout<<\n area of
rectangle2=<<r2.area();
}
Output:
Area of rectangle 1 =20
Area of rectangle 2= 48

Constructor Overloading
It allows a class to have more than one
constructors that have same name but
differ in terms of number of parameters or
parameters datatype or both.

#include<iostream.h>
Class Rectangle
{
private:
int len, br;
public:
Rectangle()
{
len=0, br=0;
}
Rectangle(int a)
{
len=br=a;
}
Rectangle(int a, int b)
{
len=a, br=b;
}

int area()
{
return (len*br);
} };
void main()
{
Rectangle r1;
Rectangle r2(5);
Rectangle r3(7,8);
cout<<\nArea of first
rectangle =<< r1.area();
cout<<\n Area of
square=<< r2.area();
cout<<\n area of second
rectangle<<r3.area();
}

OutputArea of first rectangle=0


Area of square =25
Area of second rectangle=56

Constructors in Array of Objects


When an array of objects is defined then a
default constructor is defined for each
object of array.
It means that each object of a array is
initalized with same set of values using
default argument constructor.
Rectangle r[20]; // Each object of array
invokes default constructor for initializing
its data members.

class Rectangle
{
private:
int length, breadth;
public:
Rectangle(int a, int b)
{
length=a, breadth=b;
}
void showarea()
{
cout<<area is
<<length*breadth;
}
};

void main()
{
Rectangle r[3]={Rectangle
(5,6), Rectangle(4,2),
Rectangle(5,3)};
cout<< displaying areas of
rectangle\n
for(int i=0;i<3;i++)
{
r[i].showarea();
}
}

OutputDisplaying Areas of rectangles


area is 30
area is 08
area is 15

Copy Constructor
It is a constructor that creates a copy of an
existing object.
It creates a new object using an existing
object of the same class and initialize each
data member of newly created object with
corresponding data members of existing
object.

e.g counter c1(10);


counter c2(c1);
The above statement creates object c2 and
initialize it with values of c1.
When c2 is created, a copy constructor is
invoked

class counter
{
int count;
public: counter(int c)
{ counter=c;}
counter(counter &ob)
{
cout<<copy const.
invoked;
count=ob.count;
}

void show()
{cout<<count= <<
count;}
};
void main()
{ counter c1(10);
counter c2(c1); //or
counter c2=c1;
c1.show();
c2.show();
getch();
}

OutputCopy constructor Invoked


count =10
count =10

counter c2(c1) is equivalent to


counter c2=c1;
Imp: object passed to copy constructor.
should be passed by reference and not by
value.
counter(counter &ob) is copy constructor
which takes single argument ob which is
reference to object c1 of class counter.

Destructor
A destructor is a member function which helps
to deallocate the memory allocated to an object.
It has the same name as that of a const. but
preceded by a tilde(~) symbol.
It is executed automatically when objects of a
class is destroyed.
Like constructor, it does not have any return
data type and not even void.
A destructor does not accept any parameters.
A class can have only one destructor and hence
cannot be overloaded.

Syntax:
class classname
{
.
public:
~ classname(); //destructor declaration

};
classname:: ~classname() //destructor definition
{.
}

Destructor must be declared in public


section of the class so that it is accessible
to all its users.
If we dont supply our own destructor ,
compiler will supply one implicit (default)
destructor.
Destructors are invoked automatically
whenever the objects leave the block
where they are defined. (means as soon
as it encounters curly brace} )
Objects are always destroyed in the
reverse order of their creation

class counter
{
int id;
public:
counter(int i)
{
id =i;
cout<< constructor of object with
id << id <<runs;
}
~counter()
{
cout<<\n object with id <<id<<
destroyed;
}};

void main()
{
counter c1(1);
counter c2(2);
counter c3(3);
cout<<end of main();
}

OutputConstructor of object with id 1 runs


Constructor of object with id 2 runs
Constructor of object with id 3 runs
end of main
Object with id 3 destroyed
Object with id 2 destroyed
Object with id 1 destroyed

Q.No 1) Which of the following is not a type


of constructor?
A.
B.
C.
D.

Friend Constructor
Copy constructor
Parameterized constructor
Default constructor

Q.No 2) Which of the following concept of


oops allows compiler to insert arguments
in a function call if it is not specified?
A.
B.
C.
D.

Call by value
Call by pointers
Default arguments
Call by reference

Q.No 3) Which of the following statement is


correct?
A. Constructor is called at the time of declaration
of an object.
B. A constructor is called at the time of use of an
object.
C. A constructor is called at the time of declaration
of a class.
D. A constructor is called at the time of use of a
class.

Q.No 4) Which of the following functions are


performed by a constructor?
A.
B.
C.
D.

Construct a new class


Construct a new object
Construct a new function
Initialize objects

Q.No 5) Two access specifiers in C++ are


A. public and private
B. void and free
C. formal and informal
D. public and string

Q.No 6) Which of the following access


specifier is used as a default in a class
definition?
A. Protected
B. Public
C. Private
D. friend

Answers:
1A
2C
3A
4 B,D
5A
6C

Contents

Exception Introduction
Exception handling
Try, catch
Throw
Exception specification

Exception Handling - Introduction


The errors that occur at run time are known as
exceptions. They occur due to different situations such
as division by zero, accessing elements that is out of
bound of an array, unable to open an file, running out of
memory and many more.
An exception is a situation that would be unusual for the
program that is being processed.
As a programmer, you should anticipate any abnormal
behavior that could be caused by the user entering
wrong information that could otherwise lead to
unpredictable results.

An error result or an unpredictable behavior on


your program not caused by the operating
system but that occurs in your program is called
an exception.

The ability to deal with a programs eventual


abnormal behavior is called exception handling.

Whenever an exception occurs in a c++


program, the portion the program that detects
the exception can inform that exception has
occurred by throwing it.
On throwing an exception ,the program controls
immediately stops the step by step execution of
the code and jump to the separate block of code
known as exception handler.
The exception handler catches the exception
and process it without troubling the user.
However ,if there is no exception handler
program terminates abnormally.

During the execution of a program, the computer


will face two types of situations: those it is
prepared to deal with and those it doesnt like.
Imagine you write a program that asks the user
to supply two numbers to perform a calculation.
This is a classic easy program. When it comes
up, the user is asked to simply type two
numbers; the program would use them to
perform a multiplication and display the result.
Here is such a program:

#include <iostream>
int main() {
double a, b, c; // Request two numbers from the user
cout << "Please provide two numbers\n"; cout << "First
Number: ";
cin >> a;
cout << "Second Number: ";
cin >> b;
// Multiply the numbers and display the result
c = a * b;
cout << "\n" << a << " * " << b << " = " << c << "\n\n";
return 0;
}

Imagine that a user, thanks to his infinite creativity or


because of just a mistake, decides to type the name of a
country or somebodys telephone number as one of the
requested values.
Since a program such as this one is not prepared to
multiply two strings or one number to a string (actually,
using operator overloading, you can tell the compiler
how to perform almost any type of operation on the
values of your program), it would not know what to do.
. As a programmer, if you can anticipate the type of error
that could occur in your program, you can catch the error
yourself and deal with it by telling the compiler what to
do when this type of error occurs

C++ provides mainly three keywords to handle an exception.

try ,catch,throw
1.

Trying the normal flow: (try block)


To deal with the expected behavior of a program, use the try
keyword as in the following syntax:
try {
normal code
that might generate an exception as well

We must place a portion of code under exception


inspection.
This is done by enclosing that portion of code in a try
block.

2. Catching the exception: (catch block)


During the flow of the program as part of the
try section, if an abnormal behavior occurs,
instead of letting the program crash or letting
the compiler send the error to the operating
system, you can transfer the flow of the
program to another section that can deal with
it.
When an exceptional circumstance arises
within that block, an exception is thrown that
transfers the control to the exception handler
i.e. the catch block here.

A complete syntax of such code could be


try {
// the program flow

}
catch (Argument) {
// Catch the exception

This section always follows the try section and


there must not be any code between the trys
closing bracket and the catch section.
The catch keyword is required and follows the
try section.

The catch behaves a little like a function.


It uses an argument that is passed by the
previous try section.
The argument can be a regular variable or a
class.
The behavior of the catch clause starts with an
opening curly bracket { and ends with a closing
curly bracket }.
The inside of the brackets is called the body of
the catch clause. Therefore, use the body of the
catch to deal with the error that was caused.

3. Throw an error: (throw statement)


An exception is thrown by using the
throw keyword from inside the try block.
A throw expression accepts one
parameter which is passed as an
argument to the exception handler i.e.
the catch block
throw argument;
We can also use a throw statement with
no argument as
throw;

try {
.
if (condition)
throw;
.
These statements
are not executed if
.
throw is executed.
}
catch(...) {
catch statement1;
catch statement2;
..
}

When a throw statement


is encountered the control
automatically transfers to
the catch block

// A simple Example - exceptions


#include <iostream>
int main () {
int x,y;
cout<<enter numerator) and denominator)=
cin>>x>>y;
try
{
if(y==0) //detects an exception
throw 10 ; //throw an exception
cout<<x/y =<<x/y;
}
catch (int i) //catches the exception
{
cout << "An exception occurred:division by zero not
allowed;
}
return 0; }

The purpose of the program is to display the result of division of two


numbers and check for division by 0 exception.
The program on execution ,first prompts the user to input numerator x
and denominator y both of type int.
In try block,we test the value of denominator y .If it is 0,an exception is
detected and thrown using the throw statement with an integer value
10.
The catch block defined in the program serves as a exception handler
for divide by 0 error.It catches the exception as the type of value thrown
matches with the parameter type of catch statement.
In catch block ,we display the appropriate message and gracefully exit
from the program.
If value of denominator is non zero then no exception occurs and
division is performed as desired which is then displayed

Catching multiple exceptions


The exceptions as we have seen so far
dealt with a single exception in a program.
Most of the time, a typical program will
throw different types of errors.
The C++ language allows you to include
multiple different catch blocks.
Each catch block can face a specific case
for error handling.

Catching multiple exceptions


Syntax for this could be as
try {
Code to Try
}
catch(Arg1) {
One Exception
}
catch(Arg2) {
Another Exception
}

The compiler would proceed in a top-down as follows:


1. Following the normal flow control of the program, the compiler
enters the try block.
2. If no exception occurs in the try block, the rest of the try block is
executed.
3. If an exception occurs in the try block, the try displays a throw that
specifies the type of error that happened.
a. The compiler gets out of the try block and examines the first
catch
b. If the first catch doesnt match the thrown error, the compiler
proceeds with the next catch. This continues until the compiler
finds a catch that matches the thrown error.
c. If one of the catches matches the thrown error, the body of that
catch block is executed and program executes further after the
catch block as a normal execution.

Default Handler catch()


If no catch matches the thrown error, you have (or the
compiler has) two
alternatives.
i. If there is no catch that matches the error (which
means that you didnt provide a matching catch), the
compiler hands the program flow to the operating
system (which calls the terminate() function).which in
turn call abort()and hence result in abnormal
termination of the program
ii.

Another alternative is to include a catch whose


argument is three periods:
catch()

The catch() catches all exceptions thrown


except for those for which separate catch blocks
are defined

If we use an ellipsis (...) as the parameter of


catch, that handler will catch any exception no
matter what the type of the throw exception is.
This can be used as a default handler that
catches all exceptions not caught by other
handlers if it is specified at last.

try {
// code here
}
catch (int param) {
cout << "int exception";
}
catch (char param) {
cout << "char exception";
}
catch (...) {
cout << "default exception";
}

In this case the last handler would catch any


exception thrown with any parameter that is
neither an int nor a char.

Exception specifications
C++ allows you to specify the list of exceptions that a
function can throw.This specifiction is known as
exception specification or a throw list .It ensures that
function will not throw other than listed exception in the
exception specification.
The exception specification can take the following form:
Datatype functionname(parameter list) throw (type list)
{
//function body
}

Program to demonstrate exception


specification
#include<iostream.h>
#include<conio.h>
void func_test(int val) throw(int,char)
{
if(val==0)
throw a; //throws char type //exception
if(val==1)
throw 10; //throws int type exception
}

void main()
{
cout<<start of main;
try
{
func_test(1);
}
catch(int )
{
cout<<int type exception
catched;
}
catch(char)
{
cout<<char type
exception catched;
}

In this program ,we have defined exception specification


in which function (func_test() )can only throw char or int
type exceptions.If any other type of exception is thrown
such as double ,program will terminate abnormally.
If exception specification or throw list is empty ,then
function cannot throw any exception.
E.g if we modify the function fun_test() of the previoud
program as
void func_test(int val) throw () { }
then this function cannot throw any exception.

Thank You
Please forward your query
To: bminocha@amity.edu.
Cc : manoj.amity@panafnet.com

88

PAN African e-Network Project


PGDIT
Object Oriented Programming
Semester 2nd
Session - 5

Dr. Bhawna Minocha

Session Outline

Inheritance & its Various Types


Ambiguity Resolution in inheritance
Virtual base class
Constructor in derived class
Overriding member function
Execution of constructor
Operator overloading
Type Conversion

INHERITANCE-Object of one class


acquire the properties of object of
another class .

There are various types of inheritance

SINGLE LEVEL
MULTI LEVEL
MULTIPLE
HYBRID
HIERARCHICAL

When we derive a class in


Public mode- public members of base
class become public in derived class.
Private mode- public members of base
class become private members of derived
class.
Protected mode- protected is accessible
by the member functions within its class
and any class immediately derived from it.

SINGLE LEVEL INHERITANCE


Ithasaderivedclasswithonlyonebaseclass.
A program showing single level in
public mode
#include<iostream.h>
#include<conio.h>
class B
{
int a;
public:
int b;
void getab();
int geta();
void show();
};
class D:public B
{
int c;
public:
void multi();
void display();
};

void B::getab()
{
a=5;
b=10;
}
int B::geta()
{
return a;
}
void B::show()
{
cout<<a=<<a;
}
void D::multi()
{
c=b*geta();
}

B
D

void D::display()
{
cout<<geta();
cout<<b=<<b;
cout<<c=<<c;
}
void main()
{
D d;
d.getab();
d.multi();
d.show();
d.display();
d.b=20;
d.multi();
d.display();
getch(); }

Outputa=5
a=5
b=10
c=50
a=5
b=20
c=100
Note- When the base class is publicly inherited, public
members of the base class become public of the derived
class.

SINGLE LEVEL INHERITANCE


Singlelevelinheritanceinprivatemode
A program showing single level inheritance

#include<iostream.h>
#include<conio.h>
class B
{
int a;
public:
int b;
void getab();
int geta();
void show();
};
class D:private B
{
int c;
public:
void multi();
void display(); };

void B::getab()
{
a=5;
b=10;
}
int B::geta()
{
return a;
}
void B::show()
{
cout<<a=<<a;
}
void D::multi()
{
c=b*geta();
}

B
D

void D::display()
{
cout<<geta();
cout<<b=<<b;
cout<<c=<<c;
}
void main()
{
D d;
d.getab(); //wont work
d.multi();
d.show(); //wont work
d.display();
d.b=20; //wontt work ;b has
become private
d.multi();
d.display();
getch(); }

Output
a=5
b=10
c=50
a=5
b=10
c=50
Note-When a base calss is privately inherited by a derived class,public
members of the base class become private members of the derived
class and
therefore the public members of the base class can only be accessed by
the menber functions of the derived class.They are inaccessible to the
objects of the derived class

Multilevel Inheritance
The class A serves as a base class for the derived class B, which in
turn serves as a base class for the derived class C.
A program showing multilevel
inheritance
class student
{
protected:int rollno;
public:void getnumber(int a)
{
rollno=a;
}
void printnumber()
{
cout<<rollno=<<rollno;
};
class test:public student
{
protected:float sub1,sub2;
public:

void getmarks(float x,float y)


{
sub1=x;
sub2=y;
}
void putmarks()
{
cout<<marks in
sub1=<<sub1;
cout<<marks in
sub2=<<sub2;
}
};
class result:public test
{
float total;
public:

student

test

result

void display()
{
total=sub1+sub2;
putnumber();
putmarks();
cout<<total=<<total;
} };
void main()
{
result r1;
r1.getnumber(20);
r1.getmarks(75.5,59.5);
r1.display();
getch();
}

Outputrollno=20
marks in sub1=75
marks in sub2=59.5
total =134.5

Multiple Inheritance
Aclasscaninherittheattributesoftwoormoreclasses.
A program showing multiple
inheritanceclass M
{
Int m;
public:
void getm(int x)
{
m=x;
}
};
class N
{
int n;
public:
void getn(int y)
{
n=y;
}

Class P::public M,public N


{
public:
void display()
{
cout<<m=<<m<<\n;
cout<<n=<<n<<\n;
cout<<m*n=<<m*n<<\n
;
}
};
void main()
{
P p1;
p1.getm(10);
p1.getn(20);
p1.display()
getch();
}

Outputm=10
n=20
m*n=200

Ambiguity Resolution in inheritance


A program showing multiple
inheritanceclass M
{
public:
void display()
{
cout<<amity;
}
};
class N
{
public:
void display()
{
cout<<aiit;
}
class P:public M,public N
{

public:

void display()
{
cout<<abcd;
A
}
};
void main()
{
p p1;
p1.display();
/*Derived calss
function will be
executed . */
getch();
}

Ambiguity Resolution
In the previous program if we want to call the display functions
of classes M and N also we have to call them in main class
void main()
{
P p1;
p1.display();
p1.M::display();
p1.N::display();
}
This is solving of
operator(::).

ambiguity

by

using

scope

resolution

Ambiguity Resolution in inheritance


When the function with same name appears in
more than one base class.
Consider the following two classes.
Class M {
public:void display()
{ cout<<class M\n;
} };
Class N {
public: void display()
{ cout<<class N\n;
} };

Class P : public M,public N


{
public: void display()
{
M::display()
}
}

void main()
{
P p;
p.display();
}

output - class M

Hybrid Inheritance
Itisacombinationofmultipleandmultilevelinheritance.
A program showing hybrid inheritancepublic:
void get_marks(float x,float y)
class student
{
{
protected:
marks1=x;
int rollno;
marks2=y;
public:
}
void get_rollno(int a)
void put_marks()
{
{
rollno=a;
cout<<marks1=<<marks1<<\n;
}
cout<<marks2=<<marks1<<\n;
void put_rollno()
}
{
cout<<rollno = <<rollno<<\n;
};
}
class sports
};
{
class test:public student
protected: int score;
{
protected:float marks1,marks2;

public:
void get_score(int c)
{
score=c;
}
void put_score()
{
cout<<score=<<score<<\n\n;
}
};
class result:public test,public sports
{
int total;
public:
void display()
{
total=marks1+marks2+score;
put_rollnumber();
put_marks();

put_score();
cout<<total=<<total; }
void main()
{ result r1;
r1.get_rollno(10);
r1.get_marks(27.5,33.0);
r1.get_score(6.0);
r1.display(); getch(); }

Student

Test

Result

Sports

Output:
rollno=10
marks1=27.5
marks2=33
score=6
Total=66.5

VIRTUAL BASE CLASS


Consider the following illustrationGRANDPARENT

PARENT 1

PARENT 2

CHILD

This illustration involves all 3 kinds of inheritance namely, multilevel,


multiple and hierarchical inheritance. Here the child has two
direct base classes parent 1 and parent 2 which themselves have
a common grandparent.
The child inherits the traits of
grandparent via two separate paths.

VIRTUAL BASE CLASS


It can also inherit directly as shown by
broken line. The grandparent is sometimes
referred to as indirect base class.
All the public and protected members of
grandparent are inherited into child twice, first
via parent1 and again via parent2.This means
child would have duplicate sets of the
members inherited from grandparent.

This introduces ambiguity and should be


avoided.

VIRTUAL BASE CLASS

This duplication can be avoided by making the common base class


as virtual base class while declaring the direct or intermediate base
classes which is shown below:
Class A
{
};
Class B1:virtual public A
{
};
Class B2:public virtual A
{
}
Class C: public B1,public B2
{
}
Using the concept of virtual base class, only one copy of that data
member is inherited regardless of how many inheritance path exist
between the virtual base class and a derived class

Program

classstudent
{
protected:
int rollno;
public:
voidgetrollno(int a)
{
rollno=a;
}
voidputrollno()
{
cout<<rollno=<<rollno<<\n
;
}

};
classtest:public virtualstudent
{
protected:
floatmarks1,marks2;
public:
voidgetmarks(int m1,intm2)
{
marks1=m1;
marks2=m2;
}

voidputmarks()
{
cout<<marks1=<<marks1<<\n;
cout<<marks2=<<marks2<<\n;
}
};
classsports:publicvirtualstudent
{
protected:
floatscore;
public:
voidgetscore(ints)
{
scores;
}
voidputscore()
{
cout<<score=<<score;
}
};

class result:public test,public sports


{
protected:
int total;
public:
void display()
{

STUDENT

TEST

total=marks1+marks2+score;
putrollno();
putmarks();
putscore();
cout<<total =<<total<<\n;
}
};

SPORTS

RESULT

CONSTRUCTOR IN DERIVED
CLASS

class alpha
{
int x;
public:
alpha(int i)
{
x=i;
cout<<alpha
initialized;
}
void showx()
{
cout<<x=<<x;
}
};
class beta
{
float y;
public:
beta(float j)
{
y=j;
cout<<beta
initialized;
}

void showy()
{
cout<<y;
}
};

classgamma:public beta,public alpha


{
int m,n;
public:
gamma(int a,floatb,int c,int d):alpha(a),
beta(b)/*constructorcalledinorderof
writingtheclass,betaconstructorinvoked
firstthenalphathengamma*/
{
m=c;n=d;
cout<<gammainitialized;
}

void shownm()
{
cout<<m;
cout<<n;
}
};
void main()
{
gamma g(5,10.75,20,30);
g.showx();
g.showy();
g.shownm();
}

Outputbeta initialized
alpha initialized
gamma initialized
x=5
y=10.75
m=20
n=30

OVERRIDING MEMBER FUNCTION


If same member function exist in base class as well as derived class then
derived class function will override the base class function.
const int max=100;
class stack
{
protected:
int st[max];
int top;
public:

stack()
{
top=0;
}
void push(int var)
{
st[++top]=var;
}
int pop()
{
return st[top--];
}
};

class stack2:public stack


{
public:
void push(int ver)
{
if(top<max)
stack::push(var); //this will call push function
// of base class
else
cout<<stack is full;
}
int pop()
{
if(top>0)
return stack::pop();
else
{
cout<<stack is empty;
exit(1);
}
}
};

void main()
{
stack2 s1; //here base constructor called first
//then derived class constructor
s1.push(11);
s1.push(12);
s1.push(13);
cout<<\ndeleted item is<<s1.pop();
cout<<\ndeleted item is<<s1.pop();
cout<<\ndeleted item is<<s1.pop();
getch();
}

Output:
deleted item is 13
deleted item is 12
deleted item is 11

Execution of constructor
Method of inheritance-order of execution
Class B: public A
{
}
Order of execution-A(): Base Constructor
B(): Derived constructor

Execution of base class constructor


Method of inheritance-order of execution
Class A: public B, public C
{
}
Order of execution-B(): Base (first)Constructor.
C(): Base (second)
A():derived

Execution of base class constructor


Method of inheritance-order of execution
Class A: public B, virtual public C
{
}
Order of execution-C() virtual base.
B(): Ordinary Base
A():derived

Introduction -Operator Overloading


The process of making an operator exhibit
different behaviour in different instances is
called operator overloading.
e .g if a and b are integers we can add two
intergers using c=a+b.
If a and b are objects then this statement c=a+b
will not work.So inorder to make the above
operation work ,we need to overload +
operator.This property of giving additional
meaning to existing operators so that they can
work with variables of user defined types is
called operator oveloading.

What Changes:
We can extend the semantics of the
operator that is being overloaded.
But we cannot change the Syntax
associated with that particular operator,
i.e., the grammatical rules that govern its
use such as the number of operands,
precedence and associativity cannot be
changed.
The original meaning of the operator
being overloaded is not lost.

Operators that cant be overloaded


We can overload all the C++ operators
except:
Class member access operator(., .*)
Scope Resolution Operator(::)
Size Operator (sizeof)
Conditional Operator (?:)

Syntax for operator function


return_type classname :: operator op (arg. list)
{
function body;
}
where,
return_type specifies the type of value returned by
the specified operation.
op is the operator being overloaded, and is
preceded by a keyword operator.
operator op is the function name.

Steps involved in operator overloading:

1. Create a class that defines the data type


that is to be used in the overloading
operation.
2. Declare the operator function operator
op() in the public class of the class. It can
either be a friend function or a member
function.
3. Define the operator function to implement
the required operations.

The operator function


The operator function defined in the public
section of the class can either be a friend
function or a member function.
Difference:
Friend function will have 1 arg. for unary
operators and 2 args. for binary operators.
Member function has no arg. for unary
operators and only one for binary operators.

Example:
Overloading Unary Operator(-ve):

class space
{ int a, b;
public:
void input(int x,int y);
void display();
void operator-();

// friend void operator-(space &s)

};

void space :: input (int x, int y)


{
a=x;
b=y;
}
void space :: display()
{
cout<<a;
cout<<b;
}
void space :: operator-()
{
a= -a;
b= -b;
}

// void operator-(space &s)


{
s.a = -s.a;
s.b = -s.b;
}

void main()
{
space S;
S.input(15,-5);
cout<<S(Before Overloading): ;
S.display();
-S;
//operator-(S);
cout<<S(After Overloading): ;
S.display();
getch();
}

OutputS (before overloading)15 -5


S (After overloading) -15 5

Example:
Overloading Binary Operator(+):
When overloading a binary operator:
the left operand is passed implicitly to the
function, and
the right operand is passed as an
argument.

//Program to add two complex numbers using operator


//overloading
class complex
{
float x,y;
public:
complex()
{
}
complex (float real, float imag)
{
x = real;
y=imag;
}
complex operator+(complex); // 1 arg. since binary
operator overloading
void display();
};

complex complex :: operator+(complex c)


{
complex temp;
temp.x = x + c.x; //x refers to obj C1,c.x refers to objC2;
// temp.x holds real part of temp

temp.y = y + c.y;
//return complex((x + c.x),(y + c.y));
return (temp);
}
void complex :: display()
{
cout<<x<<+ i <<y<<endl;
}

void main()
{
complex C1, C2 , C3;
C1 = complex(2.1,4.1);
C2 = complex(3.1,5.1);
cout<<C1= <<C1.display();
cout<<C2= <<C2.display();

C3= C1 + C2;

// C1 invokes operator function;


C2 is passed as an argument;
or, C3 = C1. operator+(C2);

cout<<C3= <<C3.display();
getch();

Output
5.2+9.2

Overloading Binary Operator(+):


class complex
{
float x, y;
public:
complex (float real, float imag)
{
x = real;
y=imag;
}
friend complex operator+ (complex A, complex B);
// 2 arg. friend function
void display();
};

complex complex :: operator+ (complex A, complex B)


{
return complex ((A.x + B.x), (A.y + B.y));
}
void complex :: display( )
{
cout<<x<<+ i <<y<<endl;
}
void main()
{
complex C1, C2 , C3;
C1 = complex(2.1,4.1);
C2 = complex(3.1,5.1);
cout<<C1= <<C1.display();
cout<<C2= <<C2.display();
C3= C1 + C2;
// C3 = operator+(C1,C2);
cout<<C3= <<C3.display();
getch();
}

Output
5.2+9.2

Concatenate 2 Strings
using logical AND &&:

class strcon
{
char str[15];

public:
strcon
{
strcpy(str, );

strcon(char a[])
{ strcpy(str,a); }
void display()
{ cout<<str;
}
strcon operator&&(strcon s)
{
strcon t;
strcpy(t.str,str);
strcat(t.str,s.str);
return t;

void main()
{
strcon obj1(epan);
strcon obj2(Amity University);
cout<<String one: ;
obj1.display();
cout<<String two: ;
obj2.display();
strcon obj3;
obj3 = obj1 && obj2;
cout<<Concatenated String is: ;
obj3.display();
}

Output
epanAmity University

Type Conversion
Converting one built- in data type to another built-in data type.
Type conversion can occur in number of situations like in
an assignment statement ,
in arithmetic expressions involving different data types and
in returning value from the function in which the type of the
expression differs from the return type.

Type conversion is usually classified in two categories.


Implicit or Automatic Type Conversion
Explicit Type Conversion or Type Casting

Implicit or Automatic Type Conversion


The conversion of a data type which is carried out
automatically by the compiler without
programmer intervention is called the implicit
type conversion.
To decide which variables data type is to be
converted, the compiler uses the hierarchy of
data types and converts the lower data type to
that of a higher data type.
The hierarchy of data types is as shown
long double > double > float> long int >int > char

#include<iostream.h>
#include<conio.h>
void main()
{
int a=5;
float b=7.6;
double c;
c=a+b;
cout<<c;
getch();
}
Hence the variable a is of int data type and b is of float data type
.So,during the evaluation of the expression a+b ,the data type of
the variable a is converted from int data type to that of float data
type and stored in temporary float variable which is created
automatically..Now,both the temporary variable and variable b is
to added have same data type so they are added and result
obtained is a float value which is again stored in a new temporary
variable which is created during its execution.

Since the datatype of variable c(i.e


double) on the lefthand side differs from
the data type on the right side(i.e float)
,so the float data type is converted into
double and stored in the temporary
variable created internally.Finally the
result is assigned to variable c.

Explicit Type Conversion(Type Casting)


Using cast operator ,we can override C++ default
type conversion by explicitly specifying our own
temporary data type according to the
requirement.
The syntax of type conversion in c++ is shown
below
datatype(operand) or (datatype)operand
e.g p=int(j); or p=(int)j;
q=float(k); or q=(float)k;

void main()
{
float f;
int c;
cout<<enter in f;
cin>>f;
c=5/9*(f-32);
cout<<temp <<c;
getch();
}
By using type casting: c= float(5)/9 + (f-32);

Datatype Conversions
Conversion from basic type to class
type.
Conversion from class type to basic
type
Conversion from one class type to
another class type

Basic to Class type

The conversion of a data type


to class type
Class time
{
int hrs;
int min;
};
time(int t)
{
hrs= t/60;
min=t%60;
}
void display()
{
cout<<hrs<<min;
}
};

void main()
{
int duration=85;
time t1=duration; //int to
//class
t1.display();
}

In this example, compiler first


searches for the overloaded
assignment operator function. And if it
doesnt exist, then compiler invokes
constructor with one parameter for
performing conversion.

Class To Basic Type


Converts a class type to typename.
The casting operator function should satisfy the following
conditions:
-It must be a class member.
-It must not specify a return type.
-It must not have any arguments.
Since it is a member function, it is invoked by the object
and, therefore, the values used for conversion inside the
function belong to the object that invoked the function.
This means that the function does not need an
argument.

Program
Class amount
{ float p,r;
int t;
public:
amount()
{}
void get(float pr, float ra, int ta)
{
p=pr;
r=ra;
t=ta; }
Operator float()
{
float s1;
s1=(p*r*t)/100;
return s1;
} };

void main()
{
amount obj;
obj.get(6.0,7.0,8);
float si;
si=obj; // class obj to float
//data type
cout<<si;
getch();
}

It converts the object of


class amount into float
which is then returned.

Conversion Function in source class


Converting value of dollar to rupees
# include<iostream.h>
#include<conio.h>
#define dollval 44.20
Class rupee
{ double rs;
public: rupee()
{
rs=0;}
rupee(double rs1)
{
rs=rs1;
}

void show()
{
cout<<\nMoney in
Rs.<<rs;
} };
Class dollar
{
double dol;
public:
dollar(double doll)
{
dol=doll;
}

Operator rupee()
{
double rs1=dol*dollval;
return (rupee(rs1));
}
void show()
{
cout<<dol;
}};
void main()
{
dollar d1(3);
d1.show();
rupee r1=d1;
r1.show();
getch();
}

Output3
Money in Rs. 132.6

Conversion function in
destination class
# include<iostream.h>
#include<conio.h>
Class dollar
{
double dol;
public:
dollar(double doll)
{ dol=doll; }
void show()
{ cout<<Money in dollar<<dol; }
double retdol()
{return dol; } };

Class rupee
{
double rs;
public:
rupee(dollar d)
{
rs= d.retdol()*dollval; }
void show()
{ cout<<Money<<rs;}};
void main()
{
dollar d1(3);
d1.show();
rupee r1= d1; //Conversion
r1.show(); }

Q.No 1) To use the strcpy function, you


must include the _____ header file in
your program
A. assign.h
B. string.h
C. copy.h

Q.No 2) Which of the following keyword is


used to overload an operator?
A. Overload
B. Operator
C. Friend
D. Override

Q.No 3) Which of the following is an invalid


visibility label while inheriting a class?
A. Public
B. Private
C. Protected
D. friend

Q.No 4) Which of the following is not a type


of inheritance?
A. Multiple
B. Multilevel
C. Distributive
D. Hierarchical

Answers:
1B
2B
3D
4C

Thank You
Please forward your query
To :bminocha@amity.edu
Cc : manoj.amity@panafnet.com

PAN African e-Network Project


PGDIT
Object Oriented Programming
Semester - II

By - Sonia Saini
Copyright Amity University

Session outline

Inheritance ( Various Types)


Ambiguity Resolution in inheritance
Virtual base class
Templates
Function Template
Class template
Exception Handling
Catching Multiple Exception
Exception Specification

Copyright Amity University

INHERITANCE-Object of one class


acquire the properties of object of
another class .

Copyright Amity University

There are various types of inheritance

SINGLE LEVEL
MULTI LEVEL
MULTIPLE
HYBRID
HIERARCHICAL

Copyright Amity University

When we derive a class in


Public mode- public members of base
class become public in derived class.
Private mode- public members of base
class become private members of derived
class.
Protected mode- protected is accessible
by the member functions within its class
and any class immediately derived from it.
Copyright Amity University

SINGLE LEVEL INHERITANCE


Ithasaderivedclasswithonlyonebaseclass.
A program showing single level in
public mode
#include<iostream.h>
#include<conio.h>
class B
{
int a;
public:
int b;
void getab();
int geta();
void show();
};
class D:public B
{
int c;
public:
void multi();
void display();
};
Copyright Amity University

void B::getab()
{
a=5;
b=10;
}
int B::geta()
{
return a;
}
void B::show()
{
cout<<a=<<a;
}
void D::multi()
{
c=b*geta();
}

B
D

void D::display()
{
cout<<geta();
cout<<b=<<b;
cout<<c=<<c;
}
void main()
{
D d;
d.getab();
d.multi();
d.show();
d.display();
d.b=20;
d.multi();
d.display();
getch(); }
Copyright Amity University

Outputa=5
a=5
b=10
c=50
a=5
b=20
c=100
Note- When the base class is publicly inherited, public
members of the base class become public of the derived
class.
Copyright Amity University

SINGLE LEVEL INHERITANCE


Singlelevelinheritanceinprivatemode
A program showing single level inheritance

#include<iostream.h>
#include<conio.h>
class B
{
int a;
public:
int b;
void getab();
int geta();
void show();
};
class D:private B
{
int c;
public:
void multi();
Amity University
};
voidCopyright
display();

void B::getab()
{
a=5;
b=10;
}
int B::geta()
{
return a;
}
void B::show()
{
cout<<a=<<a;
}
void D::multi()
{
c=b*geta();
}

B
D

void D::display()
{
cout<<geta();
cout<<b=<<b;
cout<<c=<<c;
}
void main()
{
D d;
d.getab(); //wont work
d.multi();
d.show(); //wont work
d.display();
d.b=20; //wontt work ;b has become private
d.multi();
d.display();
getch(); }
Copyright Amity University

Output
a=5
b=10
c=50
a=5
b=10
c=50
Note-When a base calss is privately inherited by a derived class,public
members of the base class become private members of the derived
class and
therefore the public members of the base class can only be accessed by
the menber functions of the derived class.They are inaccessible to the
objects of the derived class

Copyright Amity University

Multilevel Inheritance
The class A serves as a base class for the derived class B, which in
turn serves as a base class for the derived class C.
A program showing multilevel
inheritance
class student
{
protected:int rollno;
public:void getnumber(int a)
{
rollno=a;
}
void printnumber()
{
cout<<rollno=<<rollno;
};
class test:public student
{
protected:float sub1,sub2;
public:

Copyright Amity University

void getmarks(float x,float y)


{
sub1=x;
sub2=y;
}
void putmarks()
{
cout<<marks in
sub1=<<sub1;
cout<<marks in
sub2=<<sub2;
}
};
class result:public test
{
float total;
public:

student

test

result

void display()
{
total=sub1+sub2;
putnumber();
putmarks();
cout<<total=<<total;
} };
void main()
{
result r1;
r1.getnumber(20);
r1.getmarks(75.5,59.5);
r1.display();
getch();
}
Copyright Amity University

Outputrollno=20
marks in sub1=75
marks in sub2=59.5
total =134.5

Copyright Amity University

Multiple Inheritance
Aclasscaninherittheattributesoftwoormoreclasses.
A program showing multiple
inheritanceclass M
{
Int m;
public:
void getm(int x)
{
m=x;
}
};
class N
{
int n;
public:
void getn(int y)
{
n=y;
} Copyright Amity University

Class P::public M,public N


{
public:
void display()
{
cout<<m=<<m<<\n;
cout<<n=<<n<<\n;
cout<<m*n=<<m*n<<\n
;
}
};
void main()
{
P p1;
p1.getm(10);
p1.getn(20);
p1.display()
getch();
}

Outputm=10
n=20
m*n=200

Copyright Amity University

Ambiguity Resolution in inheritance


A program showing multiple
inheritanceclass M
{
public:
void display()
{
cout<<amity;
}
};
class N
{
public:
void display()
{
cout<<aiit;
}
class P:public M,public N
{
Copyright Amity University

public:

void display()
{
cout<<abcd;
A
}
};
void main()
{
p p1;
p1.display();
/*Derived calss
function will be
executed . */
getch();
}

Ambiguity Resolution
In the previous program if we want to call the display functions
of classes M and N also we have to call them in main class
void main()
{
P p1;
p1.display();
p1.M::display();
p1.N::display();
}
This is solving of
operator(::).

Copyright Amity University

ambiguity

by

using

scope

resolution

Ambiguity Resolution in inheritance


When the function with same name appears in
more than one base class.
Consider the following two classes.
Class M {
public:void display()
{ cout<<class M\n;
} };
Class N {
public: void display()
{ cout<<class N\n;
} };

Copyright Amity University

Class P : public M,public N


{
public: void display()
{
M::display()
}
}

void main()
{
P p;
p.display();
}

Copyright Amity University

output - class M

Hybrid Inheritance
Itisacombinationofmultipleandmultilevelinheritance.
A program showing hybrid inheritancepublic:
void get_marks(float x,float y)
class student
{
{
protected:
marks1=x;
int rollno;
marks2=y;
public:
}
void get_rollno(int a)
void put_marks()
{
{
rollno=a;
cout<<marks1=<<marks1<<\n;
}
cout<<marks2=<<marks1<<\n;
void put_rollno()
}
{
cout<<rollno = <<rollno<<\n;
};
}
class sports
};
{
class test:public student
protected: int score;
{
protected:float marks1,marks2;
Copyright Amity University

public:
void get_score(int c)
{
score=c;
}
void put_score()
{
cout<<score=<<score<<\n\n;
}
};
class result:public test,public sports
{
int total;
public:
void display()
{
total=marks1+marks2+score;
put_rollnumber();
put_marks();
Copyright Amity University

put_score();
cout<<total=<<total; }
void main()
{ result r1;
r1.get_rollno(10);
r1.get_marks(27.5,33.0);
r1.get_score(6.0);
r1.display(); getch(); }

Student

Test

Result

Sports

Output:
rollno=10
marks1=27.5
marks2=33
score=6
Total=66.5

Copyright Amity University

VIRTUAL BASE CLASS


Consider the following illustrationGRANDPARENT

PARENT 1

PARENT 2

CHILD

This illustration involves all 3 kinds of inheritance namely, multilevel,


multiple and hierarchical inheritance. Here the child has two
direct base classes parent 1 and parent 2 which themselves have
a common grandparent.
The child inherits the traits of
grandparent via two separate paths.
Copyright Amity University

VIRTUAL BASE CLASS


It can also inherit directly as shown by
broken line. The grandparent is sometimes
referred to as indirect base class.
All the public and protected members of
grandparent are inherited into child twice, first
via parent1 and again via parent2.This means
child would have duplicate sets of the
members inherited from grandparent.

This introduces ambiguity and should be


avoided.
Copyright Amity University

VIRTUAL BASE CLASS

This duplication can be avoided by making the common base class


as virtual base class while declaring the direct or intermediate base
classes which is shown below:
Class A
{
};
Class B1:virtual public A
{
};
Class B2:public virtual A
{
}
Class C: public B1,public B2
{
}
Using the concept of virtual base class, only one copy of that data
member is inherited regardless of how many inheritance path exist
between the virtual base class and a derived class

Copyright Amity University

Program

classstudent
{
protected:
int rn;
public:
voidgetrollno(int a)
{
rollno=a;
}
voidputrollno()
{
cout<<rollno=<<rollno<<\n
;
}

};
classtest:public virtualstudent
{
protected:
floatmarks1,marks2;
public:
voidgetmarks(int m1,intm2)
{
marks1=m1;
marks2=m2;
}
Copyright Amity University

voidputmarks()
{
cout<<marks1=<<marks1<<\n;
cout<<marks2=<<marks2<<\n;
}
};
classsports:publicvirtualstudent
{
protected:
floatscore;
public:
voidgetscore(ints)
{
scores;
}
voidputscore()
{
cout<<score=<<score;
}
};

class result:public test,public sports


{
protected:
int total;
public:
void display()
{

STUDENT

TEST

total=marks1+marks2+score;
putrollno();
putmarks();
putscore();
cout<<total =<<total<<\n;
}
};

Copyright Amity University

SPORTS

RESULT

void main()
{
result r1;
r1.getrollno(678);
r1.getmarks(30.5,25.5);
r1.getscore(7.0);
r1.display();
getch();
}
Output- rollno=678
marks1=30.5
marks2 = 25.5
score=7
total =63
Copyright Amity University

Template
In function overloading ,we use the same name
for different implementations of the function.
Overloaded functions are distinguished by
means of different parameter list.
Problem with function overloading is that in the
program we not only have to define a separate
function for each data type but also if new type is
added later on, then new functions have to be
written for each one

Templates

Solution to the problem is to make a generic


function that can work for all c++ data type.
Templates are used to write down generic
code.
When we need to write a common code for
different data type basic or class type we can
do so with the help of templates.
In c++, we will study 2 types
1.
Function templates
2.
class templates

Function Templates
Function templates are the generic functions
which can handle different data types without
the need of writing separate code for each of
them.Thus it reduces lot of manual effort in
development ,testing and
debugging of
programst.

Template parameter
A template parameter is a special kind of parameter
that can be used to pass a type as argument.
As regular function parameters can be used to pass
values to a function, template parameters allow to pass
also types to a function.
These function templates can use these parameters as if
they were any other regular type to write a code for
generic data type or class.

Function template syntax


The format for declaring function
templates that take parameter of a single
data type is as follows:
Template<class T>
T function_name( T part1,T part2..)
{
//template function body
}

Function template syntax


All function templates begin with a keyword template
which informs the compiler that we are about to define a
function template.It is followed by template type
parameter T enclosed in angled brackets and parameter
T must be preceded by keyword class which establishes
that T is a data type.
Some compilers may use keyword typename instead of
class but both refer to any built in type or user-defined
type.
It is followed by function definition instead of using
datatype such as int generic data type T is used.

For example, to create a template function that returns


the greater one of two objects we could use:
template <class T>
T Max (T a, T b)
{
return (a>b?a:b);
}
Here we have created a template function with T as its
template parameter.
This template parameter represents a type that has not
yet been specified, but that can be used in the template
function as if it were a regular type.
As you can see, the function template Max returns the
greater of two parameters of this still-undefined type.

Function template - Use


To use this function template we use the
following format for the function call:
function_name <type> (parameters);
For example, to call Max to compare two integer
values of type int we can write:
int x,y;
Max <int> (x,y);

When the compiler encounters this call to a


template function like,
Max <int> (x,y);
it uses the template to automatically generate a
function replacing each appearance of T by the
type passed as the actual template parameter
(int in this case) and then calls it.
This process is automatically performed by the
compiler and is invisible to the programmer.

// function template

#include <iostream>
#include<conio.h>
template <class T>
T Max (T a, T b)
{
T result;
result = (a>b)? a : b;
return (result);
}

int main ()
{
int i=5, j=6, k;
long l=10, m=5, n;
k= Max<int>(i,j); // create a function for int type
n=Max<long>(l,m); // create a function for long
//type
cout << k << endl;
cout << n << endl;
return 0;
}

Output is
6
10

In the example above we used the


function template Max() twice.
The first time with arguments of type int
and the second one with arguments of
type long.
The compiler has instantiated and then
called each time the appropriate version of
the function.

As you can see, the type T is used within


the Max() template function even to
declare new objects of that type:
T result;
Therefore, result will be an object of the
same type as the parameters a and b
when the function template is instantiated
with a specific type.

Our template function includes only one


template parameter (class T) and the function
template itself accepts two parameters, both of
this T type.
We cannot call our function template with
two objects of different types as arguments:
int i; long l; k = Max (i,l);
This would not be correct, since our Max
function template accepts two arguments of the
same type, and in this call to it, we use objects
of two different types.

More than one type parameter- We can also define


function templates that accept more than one type
parameter, simply by specifying more template parameters
between the angle brackets.
#include<iostream.h>
display(ch,i);
#include<conio.h>
getch();
Template<class T1,class T2>
}
void display(T1 a,T2 b)
{
cout<<\na=<<a<<\tb=<<b;
Output}
a=10 b=25.5
void main()
a=B b=20
{
int i=10;float f=25.5;
display(i,f); or display<int ,float>(i,f);
char ch=B;
i=20;

Explanation of the program


This program displays the values of two variables of any data types
using function templates.
Since the function template needs to manipulate two variables of any
data type.So function template header specifies two generic data types
T1 and T2.
template<class T1,class T2>
the name of the function template is display and it takes two parameter
one of type T1 and other of type T2.
When the compiler encounters a function call in the program ,it
replaces T1 and T2 with the data types of the arguments specified in
the function call in the same order.
So an execution of the statement , display(I,f);the compiler creates a
new version of display() and subsititutes int with T1 and float with T2
through out the template definition and two values are displayed.
Similarly next statement works.
44

Use of non type parameter in function template.


We can also use non-type parameter such as
int,char,pointers
We use non type parameter in function templates in those
situation where we know in advance that parameter can
take values of specific type.

45

#include<iostream.h>
#include<conio.h>
template <class T>
void display(T a,T b,char operation)
{
switch(operation)
{
case +
:cout<<a<<operation<<b<<=<<a+b<<endl;
break;
case - :cout<<a<<operation<<b<<=<<a-b<<endl;
break;
case * :cout<<a<<operation<<b<<=<<a*b<<endl;
break;
case / :cout<<a<<operation<<b<<=<<a/b<<endl;
break;
default: cout<<undefined operation;
}
}
46

void main()
{
clrscr();
display(20,40.+);
display(3.5,1.5,);
getch();
}

Output:
20+40=60
3.5-1.5=2.0

The function template consists of three parameters where


first two are type parameters of type T where as third
parameter is a non type parameter of data type char.
On executing the statement ,
display(20,40,+);
the compiler generates new version of display() that
operate on type int and substitutes T with int data type
throughout the template definition.
As the third argument passed is character + so it will
execute the statements corresponding to the + case of
switch statement.

47

Class Template

Like function template ,we can create generic classes using class
template that provide same functionality for different data types.
C++ class templates are normally used in the container classes such
as stacks,queues,vectors,lists etc.
Once the code is written as a class template,it can support multiple
data types.
Consider an example of stack data structure in which items can be
added and removed from the top in LIFO (last in first out) order.
A stack may store items of any data type but not a mixture of data
types. The code used for maintaining stack of integers can also work
for stack of float or character or double types.
Instead of creating separate stack class for different data types,we can
create a template for a stack class and use it to define stacks that
can store different data types.

The general form of creating class template is template <class T>


class class_name
{
class definition };
if we want to create generic stack class then class template can be written
as follows
template<class T>
class stack {
T array[20];
int top;
public:
stack();
void push(T item);
T pop();
void display();
};

49

Program that implements stack for


different data types

const int max=10;


template <class T>
class stack
{
int array[max];
int top;
public:
stack()
{
top=-1;
}
void push(T item)
{
array[++top]=item;
}
int pop()
{
return array[top--];
}
};

voidmain()
{
clrscr();
stack<int>s1;
s1.push(10);
s1.push(20);
cout<<elementtobepopped<<s1.pop();
stack<float>s2;
s2.push(5.5);
s2.push(10.7);
cout<<\nelementtobe
popped<<s2.pop());
getch();
}

The statement

stack <int> s1;

creates an object of type stack that can store int values in


the stack. This instantiation provides space to all the data
members and member functions of object s1 by replacing
each occurrence of template parameter T with int.
The next statement push and pop elements into and from
the stack.Then the contents of stack are displayed.
Similarly the statement stack <float>s2;
creates an object of type stack that can store float values in
the stack. This instantiation provides space to all the data
members and member functions of object s1 by replacing
each occurrence of template parameter T with float.
The next statement push and pop elements into and from
the stack.Then the contents of stack are displayed.
51

we can also define a member function outside


the declaration of the class template, we must
always precede that definition with the template
<...> prefix as:

template <class T>


T stack<T>::push ()

Program that implements stack for


different data types
const int max=10;
template <class T>
class stack
{
int array[max];
int top;
public:
stack()
{
top=-1;
}
T push(T item);
T pop();
};
template <class T>
T stack<T>::push ()
{array[++top]=item; }

template <class T>


T stack<T>::pop ()
{
return array[top--];
}
voidmain()
{
clrscr();
stack<int>s1;
s1.push(10);
s1.push(20);
cout<<elementtobepopped<<s1.pop();
stack<float>s2;
s2.push(5.5);
s2.push(10.7);
cout<<\nelementtobe
popped<<s2.pop());
getch();
}

Template specialization
At times we want to define a different
implementation for a template when a
specific type is passed as template
parameter
We can always declare a specialization of
that template for that particular data type
as the need be.

This is the syntax used in the class template


specialization:
template <>
class mycontainer <char>
{
...
};
Notice that we precede the class template name with an
empty template<> parameter list. This is to explicitly
declare it as a template specialization.

For example, let's suppose that we have a very


simple class called mycontainer that can have
the members as
1. one element of any type and
2. it has just one member function called increase,
which increases its value.
3. But we find that when it stores an element of type
char it would be more convenient to have a
completely different implementation with a function
member uppercase,
4. so we decide to declare a class template
specialization for type char only.

// template specialization
#include <iostream>

// class template:
template <class T>
class mycontainer {
T element;
public:
mycontainer (T arg) {
element=arg;
}
T increase () {
return ++element;
}
};

// class template specialization for char type will be as:


template <>
class mycontainer <char> {
char element;
public:
mycontainer (char arg) {
element=arg;
}
char uppercase () {
if ((element>='a')&&(element<='z'))
element+='A'-'a';
return element;
}
};

Carefully see the code used


template <>
This is to explicitly declare it as a template
specialization.
class mycontainer <char> {
...
};

Here <char> is the specialization parameter


after the class template name. This
specialization parameter itself identifies the type
for which we are going to declare a template
class specialization i.e. char.

Notice the differences between the generic class


template and the specialization:
template <class T> class mycontainer { ... };
template <> class mycontainer <char> { ... };

Here
first line is the generic template,
second one is the template specialization.
Remember
When we declare specializations for a template class,
we must also define all its members, even those exactly
equal to the generic template class, because there is no
"inheritance" of members from the generic template to
the specialization.

Class Template with non type parameter


As in case of function templates,the class templates can also use
nontype parameters in addition to the type parameter.Non type parameter
can be int ,char,pointers ,enum,strings etc
template<class T,int SIZE>
class stack
{
private: T array[SIZE];
int top;
public:------------------- };
When we create an object of the class template stack,we create it using
the statement,
stack <int,5> s1;
Here we specify the predetermined size of the stack along with the data
type int of values that can be entered into the stack.

61

Default values for class template


parameters
Default arguments can also be specified in the class
template parameter list.
Template<class T,int size=16>
Class stack{
----};

Friend declaration can also appear in the


class templates
template <class T>
class abc
{
friend void func();
};

63

Class template also support Inheritance.

A template type base class can be derived by a


normal class or a class template.
For exampletemplate<class T>
class base
{
};
template <class T>
class derived:public base <T>
{
};
64

Contents

Exception Introduction
Exception handling
Try, catch
Throw
Exception specification

Exception Handling - Introduction

The errors that occur at run time are known as


exceptions. They occur due to different situations such
as division by zero,acessing elements that is out of
bound of an array,unable to open an file,running out of
memory and many more.

An exception is a situation that would be unusual for the


program that is being processed.
As a programmer, you should anticipate any abnormal
behavior that could be caused by the user entering
wrong information that could otherwise lead to
unpredictable results.

An error result or an unpredictable behavior on


your program not caused by the operating
system but that occurs in your program is called
an exception.

The ability to deal with a programs eventual


abnormal behavior is called exception handling.

Whenever an exception occurs in a c++


program,the portion the program that detects the
exception can inform that exception has
occurred by throwing it.
On throwing an exception ,the program controls
immediately stops the step by step execution of
the code
and jump to the separate block of code known
as exception handler.The exception handler
catches the exception and process it without
troubling the user.
However ,if there is no exception handler
program terminates abnormally.

During the execution of a program, the computer


will face two types of situations: those it is
prepared to deal with and those it doesnt like.
Imagine you write a program that asks the user
to supply two numbers to perform a calculation.
This is a classic easy program. When it comes
up, the user is asked to simply type two
numbers; the program would use them to
perform a multiplication and display the result.
Here is such a program:

#include <iostream>
int main() {
double a, b, c; // Request two numbers from the user
cout << "Please provide two numbers\n"; cout << "First
Number: ";
cin >> a;
cout << "Second Number: ";
cin >> b;
// Multiply the numbers and display the result
c = a * b;
cout << "\n" << a << " * " << b << " = " << c << "\n\n";
return 0;
}

Imagine that a user, thanks to his infinite creativity or


because of just a mistake, decides to type the name of a
country or somebodys telephone number as one of the
requested values.
Since a program such as this one is not prepared to
multiply two strings or one number to a string (actually,
using operator overloading, you can tell the compiler
how to perform almost any type of operation on the
values of your program), it would not know what to do.
. As a programmer, if you can anticipate the type of error
that could occur in your program, you can catch the error
yourself and deal with it by telling the compiler what to
do when this type of error occurs

C++ provides mainly three keywords to handle an exception.

try ,catch,throw
1.

Trying the normal flow: (try block)


To deal with the expected behavior of a program, use the try
keyword as in the following syntax:
try {
normal code
that might generate an exception as well

We must place a portion of code under exception


inspection.
This is done by enclosing that portion of code in a try
block.

2. Catching the exception: (catch block)


During the flow of the program as part of the
try section, if an abnormal behavior occurs,
instead of letting the program crash or letting
the compiler send the error to the operating
system, you can transfer the flow of the
program to another section that can deal with
it.
When an exceptional circumstance arises
within that block, an exception is thrown that
transfers the control to the exception handler
i.e. the catch block here.

A complete syntax of such code could be


try {
// the program flow

}
catch (Argument) {
// Catch the exception

This section always follows the try section and


there must not be any code between the trys
closing bracket and the catch section.
The catch keyword is required and follows the
try section.

The catch behaves a little like a function.


It uses an argument that is passed by the
previous try section.
The argument can be a regular variable or a
class.
The behavior of the catch clause starts with an
opening curly bracket { and ends with a closing
curly bracket }.
The inside of the brackets is called the body of
the catch clause. Therefore, use the body of the
catch to deal with the error that was caused.

3. Throw an error: (throw statement)


An exception is thrown by using the
throw keyword from inside the try block.
A throw expression accepts one
parameter which is passed as an
argument to the exception handler i.e.
the catch block
throw argument;

We can also use a throw statement with


no argument as
throw;

// A simple Example - exceptions


#include <iostream>
int main () {
int x,y;
cout<<enter numerator) and denominator)=
cin>>x>>y;
try
{
if(y==0) //detects an exception
throw 10 ; //throw an exception
cout<<x/y =<<x/y;
}
catch (int i) //catches the exception
{
cout << "An exception occurred:division by zero
not allowed;
}
return 0; }

The purpose of the program is to display the result of division of two


numbers and check for division by 0 exception.
The program on execution ,first prompts the user to input numerator x
and denominator y both of type int.
In try block,we test the value of denominator y .If it is 0,an exception is
detected and thrown using the throw statement with an integer value
10.
The catch block defined in the program serves as a exception handler
for divide by 0 error.It catches the exception as the type of value thrown
matches with the parameter type of catch statement.
In catch block ,we display the appropriate message and gracefully exit
from the program.
If value of denominator is non zero then no exception occurs and
division is performed as desired which is then displayed

79

try {
.
if (condition)
throw;
.
These statements
are not executed if
.
throw is executed.
}
catch(...) {
catch statement1;
catch statement2;
..
}

When a throw statement


is encountered the control
automatically transfers to
the catch block

Catching multiple exceptions


The exceptions as we have seen so far
dealt with a single exception in a program.
Most of the time, a typical program will
throw different types of errors.
The C++ language allows you to include
multiple different catch blocks.
Each catch block can face a specific case
for error handling.

Catching multiple exceptions


Syntax for this could be as
try {
Code to Try
}
catch(Arg1) {
One Exception
}
catch(Arg2) {
Another Exception
}

The compiler would proceed in a top-down as follows:


1. Following the normal flow control of the program, the compiler
enters the try block.
2. If no exception occurs in the try block, the rest of the try block is
executed.
3. If an exception occurs in the try block, the try displays a throw that
specifies the type of error that happened.
a. The compiler gets out of the try block and examines the first
catch
b. If the first catch doesnt match the thrown error, the compiler
proceeds with the next catch. This continues until the compiler
finds a catch that matches the thrown error.
c. If one of the catches matches the thrown error, the body of that
catch block is executed and program executes further after the
catch block as a normal execution.

Default Handler catch()


If no catch matches the thrown error, you have (or the
compiler has) two
alternatives.
i. If there is no catch that matches the error (which
means that you didnt provide a matching catch), the
compiler hands the program flow to the operating
system (which calls the terminate() function).which in
turn call abort()and hence result in abnormal
termination of the program
ii.

Another alternative is to include a catch whose


argument is three periods:
catch()

The catch() catches all exceptions thrown


except for those for which separate catch blocks
are defined

If we use an ellipsis (...) as the parameter of


catch, that handler will catch any exception no
matter what the type of the throw exception is.
This can be used as a default handler that
catches all exceptions not caught by other
handlers if it is specified at last.

try {
// code here
}
catch (int param) {
cout << "int exception";
}
catch (char param) {
cout << "char exception";
}
catch (...) {
cout << "default exception";
}

In this case the last handler would catch any


exception thrown with any parameter that is
neither an int nor a char.

Exception specifications
C++ allows you to specify the list of exceptions that a
function can throw.This specifiction is known as
exception specification or a throw list .It ensures that
function will not throw other than listed exception in the
exception specification.
The exception specification can take the following form:
Datatype functionname(parameter list) throw (type list)
{
//function body
}

Program to demonstrate
exception specification
#include<iostream.h>
#include<conio.h>
void func_test(int val) throw(int,char)
{
if(val==0)
throw a; //throws char type
//exception
if(val==1)
throw 10; //throws int type exception
}

88

void main()
{
cout<<start of main;
try
{
func_test(1);
}
catch(int )
{
cout<<int type
exception catched;
}
catch(char)
{
cout<<char type
exception catched;
}

In this program ,we have defined exception specification


in which function (func_test() )can only throw char or int
type exceptions.If any other type of exception is thrown
such as double ,program will terminate abnormally.
If exception specification or throw list is empty ,then
function cannot throw any exception.
E.g if we modify the function fun_test() of the previoud
program as
void func_test(int val) throw () { }
then this function cannot throw any exception.

89

Q.No 1 Which of the following problem


causes an exception?
A. Missing semicolon in statement in
main().
B. problem in calling function.
C. A syntax error.
D. A run-time error.

Q.No 2 A default catch block catches


A. all thrown objects
B. no thrown objects
C. any thrown object that has not been
caught by an earlier catch block
D. all thrown objects that have been caught
by an earlier catch block

Q.No 3 Which of the following statement is


correct?
A.Class is an instance of object.
B.Object is an instance of a class
C.Class is an instance of data type.
D.Object is an instance of data type.

Q.No 4 Function Template handles


A. Different data types
B. Same data types
C. Interger data types
D. String data types

Q.No 6 The type to be used in an instantiation of a class


template follows ________

A.
B.
C.
D.

the template definition


the keyword class
the keyword template
the generic class name

Q.No 7 Two access specifiers in C++ are


A. public and private
B. void and free
C. formal and informal
D. public and string

Answers1 a
2c
3d
4a
5c
6d
7a

Thank You
Please forward your query
To :ssani@aiit.amity.edu
CC: manoj.amity@panafnet.com

Copyright @ Amity University

PAN African e-Network Project


PGDIT
Object Oriented Programming
Semester 2nd
Session - 7

Dr. Bhawna Minocha

Contents

Streams
Stream classes
Unformatted I/0 operations
Formatted I/O operations
File Handling
Open function mode
Opening a file using constructor
Closing a file
Example programs of reading and writing
string,character I/0,Copy one file to another.
Reading and writing objects
File poniters (seekp,seekg,tellg,tellp)
Preprocessor directives

What are Streams ??


A stream is a sequence of bytes.
It acts as a source from which the input data
can be obtained or as a destination to which
the output data can be sent.
Source stream is called Input Stream. And
destination stream is called Output Stream.
A stream is an abstraction that represents a
device on which input and output operations
are performed.

C++ Streams

A program extracts the bytes from an input stream


and inserts bytes into an output stream.

Streams
A stream in C++ is treated as an object of a particular
class.C++ has a number of predefined streams which
are automatically opens when the programs execution
starts.These
predefined
streams
include
cin,cout,cerr,clog which plays a central role in console
I/0 operations .These predefined streams perform the
following functions
cin(console input) The cin object represent the input
stream connected to the standard input device (usually
keyboard) from where a progam normally reads the
input.
cout(console output) The cout object represent the
output stream connected to the standard output device
(usually monitor) from where a progam normally reads
the input.

cerr The cerr object represent the output stream


connected to the standard output device to which a
program normally write error messages. The error
messages to be displayed using cerr are un-buffered
which means that output is immediately displayed on the
screen rather than being buffered as in case of cout.
clog-The clog object is similar to cerr for displaying error
messages except that its output is fully buffered.

C++ Stream Classes

ios
pointer

istream

streambuf

ostream
output

input

iostream

istream_withassign

iostream_withassign

ostream_withassign

From the diagram it is clear that at the top we have ios


base class.The classes istream and ostream
are
derived from base class ios and class iostream is further
derived from istream and ostream classes using multiple
inheritance.
The classes istream and ostream are derived virtually
from ios base class so that only one copy of the
members of ios class are inherited by the iostream
class.The extraction operator >> is a member of the
istream class and the insertion operator << is a
member of the ostream class.
The predefined cin object represent the standard input
stream(keyboard)is an object of istream_withassign
classwhich is derived from the istream class.Therefore
cin has the functionality of class istream.

The predefined cout object represent the standard output


stream(monitor)is an object of ostream_withassign class
which is derived from the ostream class.Therefore cout
has the functionality of class ostream.
These classes are declared in iostream.h header file.

The functions performed by these classes are listed


below:
ios class-It contains various member functions and
constant flags that are necessary to perform
formatting,error checking and status information
related to stream I/0.It also contains a pointer to buffer
object streambuf which contains the actual memory
buffer into which data is read or written and provides the
low level I/0 operations for handling this data.
istream class-It is used for providing formatted and
unformatted input operations.It includes input member
functions such as get(),getline(),read() and the
overloaded extraction operator >>.
ostream class It includes output member functions such
as put(),write() and the overloaded insertion operator
<<.

Unformatted I/O operationscin and cout are predefined objects that support inputting
and outputting of data of various types.To accomplish
this ,the operators << and >> are overloaded in the
istream and ostream classes respectively. In addition to
<< and >> operators ,numerous other member
functions can also be used for performing input and
output operations.
istream member functions-istream class consists of
get(ch),
get(),
get(str,Max),
get(str,MAX,delim),
getline(str,MAX,delim),
read(str,Max).

ostream member functions


ostream class consists of many member functions in
addition to the << (insertion)operator function.
include put(ch),write(str,MAX)

istream member function


get(ch)-The purpose of this function is to read a single
character from the associated stream and store it in the
character parameter ch.This function also fetch a white
space character including blank space ,tab and a new
line character.
Consider the statements of a program segment
char ch
cin.get(ch) on execution it will read a single chracter
variable ch from the standard input device(keyboard).

get()-This version of get contains no parameter .


char ch
ch=cin.get(); On execution,it reads a character and return
that value which is stored in a character variable ch.
get(str,MAX)-contains two parameters array of
characters(str) and maximum number of characters
(MAX).It is used to input multi word string.
The null character (\0) is automatically appended to the
character array str.
It reads character from the input stream into the array of
characters until either(MAX-1)character have been read
or a new line (\n) character has been encountered

#include<iostream.h>
#include <conio.h>
Outputint main()
{
Entera string :Amity University
const int MAX=80;
String is Amity University
char str[MAX];//array of character
cout<<\n enter a string
cin.get(str,MAX);
cout<<string is =<<str;
getch();
return 0;
}

get(str,MAX,delim)-contains three parameters


array of characters(str) and maximum number of
characters and delimiter character.
The delimiter refers to user specified termination
character which if encountered should terminate
the reading of characters.
The null character (\0) is automatically
appended to the character array str.
Purpose is to input multi line strings

#include<iostream.h>
#include <conio.h>
int main()
{
const int MAX=80;
char str[MAX];//array of character
cout<<\n enter a string
cin.get(str,MAX,*);
cout<<string is =<<str;
getch();
return 0;
}

OutputEnter a string:
Share Index is growing
Buy IPCI at current price
*

Explanation-The statement cin.get(str,MAX,*);


allows the user to input multiple lines until either
user enters the terminating character * or until
user exceeds the size of the array.It is
necessary to press the enter key after typing *
character

getline (str,MAX,delim)
The purpose of getline is similar to that of
get(str,MAX,delim) for inputting multiline string.
In getline if we skip the delimit then by default it
takes\n and therefore can input only a single
value.

read(str ,MAX) contains two parameters array


of characters(str) and maximum number of
characters (MAX).
The null character is not appended
automatically.

#include<iostream.h>
#include <conio.h>
int main()
Output:
{
const int MAX=11;
enter a string:Stock Index
char str[MAX];//array of character string is Stock Index
cout<<\n enter a string
cin.read(str,MAX);
int count=cin.gcount();
str[count]=\0;
cout<<string is =<<str;
getch();
return 0;
}

Explanation-The statement cin.read(str,max)


inputs a string str.As the null character is not
appended at the end of the string so we use
function gcount() to count the number of
character input by the user in the last input
operation and later use this value to append
null character\0 at the end of the string.Thus
the string can be displayed

ostream member function


put(ch)-The purpose is to write a single
character ch to the output device.
For example-char ch=X;
cout.put(ch);
On execution ,it will write the contents of the
character variable ch to the screen.

write(str,MAX)
The purpose of write function is to output the MAX number
of characters of the character array str.
The process of displaying using write function does not
stop even when the NULL character (\0) is
encountered.
Due to this property,if MAX is greater than the length of str
then it may display unwanted character beyond the
maximum length of string.

#include<iostream.h>
#include<conio.h>
#include<string.h>
int main()
{
char str[]=Streams;
int len1=strlen(str)
for(int i=1;i<=len1;i++)
{
cout.write(str,i);
cout<<\n;
}

for(i=len1-1;i>0;i--)
{
cout.write(str,i);
cout<<\n;
}
return 0; }
Output
S
St
Str
Stre
Strea
Stream
Streams
Stream
Strea
Stre
Str
St
s

Formatted I/O operationsC++ supports a number of features that could be


used for formatting the output.These features
include:
ios stream classs flags and member
functions
Manipulators
User defined manipulators

ios stream class functions and flags


Function

Task

width()

To specify the required field size for displaying an


output value

precision()

To specify the number of digits to be displayed after


the decimal point of a float value

fill()

To specify a character that is used to fill the unused


portion of a field

setf()

To specify format flags that can control the form of


output display (such as left-justification and rightjustification)
To clear the flags specified

unsetf()

cout.width(4);
cout<<124;
#include<iostream.h>
int main()
{
#
#
cout.fill(#);
cout.width(6);
cout<<204;
cout.width(4);
cout<<34;
return 0;
}

precision(p)#include<iostream.h>
int main()
6
.
{
cout.precision(3);
cout<<6.7291<<endl;
return 0;
}

Flags and bit fields for setf() functions


Format required

Flag(arg1)

Bit-field(arg2)

Left-justified output

ios::left

ios::adjustfield

Right-justified output

ios::right

ios::adjustfield

Padding after sign or


base Indicator (like
+##20)

ios::internal

ios::adjustfield

Scientific notation

ios::scientific

ios::floatfield

Fixed point notation

ios::fixed

ios::floatfield

Decimal base

ios::dec

ios::basefield

Octal base

ios::oct

ios::basefield

Hexadecimal base

ios::hex

ios::basefield

#include<iostream.h>
#include<conio.h>
void main()
{
cout.fill(*);
cout.setf(ios::left,ios::adjustfield);
cout.width(15);
cout<<Table 1<<\n;
}
output:
T

* * * * * * **

#include<iostream.h>
#include<conio.h>
void main()
{
cout.fill(*);
cout.precision(3);
cout.setf(ios::internal,ios::adjustfield);
cout.setf(ios::scientific,ios::floatfield);
cout.width(15);
cout<<-12.34567<<\n;
getch();
}
- * * * * * 1 . 2 3 5 e + 01

Flags that do not have bit fiields


Flag

Meaning

ios::showbase

Use base indicator on output

ios::showpos

Print + before positive numbers

ios::showpoint

Show trailing decimal point and zeroes

ios::uppercase Use uppercase letters for hex output


ios::skipus

Skip white space o input

ios::unitbuf

Flush all streams after insertion

ios::stdio

Flush stdout and stderr after insertion

Displaying Trailing zeros and plus


signIf we print the numbers 10.75,25.00
and 15.50 using a field width of say
eight positions with two digits
precision,then the output will be as
followsNote that Trailing zeros in second and
third items have been truncated.
1 0 .

7 5
2 5
1 5 . 5

cout.setf(ios::showpoint); //display
//trailing zeros.
cout.setf(ios::showpos); // show +sign
#include<iostream.h>
#include<conio.h>
void main()
{
cout.setf(ios::showpoint);
cout.setf(ios::showpos);
cout.precision(3);
cout.setf(ios::fixed,ios::floatfield);
cout.setf(ios::internal,ios::adjustfield);
cout.width(10);
cout<<275.5<<\n;
+
2 7 5 .
getch();
}

5 0 0

Manipulators and their meanings

The header file iomanip provides a set of functions called


manipulators which can be used to manipulate the output
formats.They provide the same features as that of the ios
member functions and flags
Manipulator

Meaning

Equivalent

Setw(int w)

Set the field width to wer to c

Width( )

Setprecision(int d)

Set the floating point


precision to d

Precision( )

Setfill(int c)

Set the fill chara c

Fill()

Setiosflags(long f)

Set the format flag f

Setf( )

Resetiosflags(long f)

Clear the flag specified by f

Unsetf( )

Endl

Insert new line and flush


stream

\n

Formatting with MANIPULATORS


#include<iostream.h>
#inlude<iomanip.h>
int main()
{
cout.setf(ios::showpoint);
cout<<setw(5)<<n
<<setw(15)<<Inverse_of_n
<<setw(15)<<Sum_of_terms\n\
n;
double term, sum=0;

for(int n=1; n<=5; 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;
}
return 0;
}

Output-

n
1
2
3
4
5

Inverse_of_n
1.0000e+000
5.0000e-001
3.3333e-001
2.5000e-001
2.0000e-001

Sum_of_terms
1.0000
1.5000
1.8333
2.0833
2.2833

User defined manipulators


The general form of creating is
ostream &manipulator(ostream & output)
{

(Code)
return output
}

The following function defines a manipulator


called unit that displays inches
Ostream & unit(ostream & output)
{
output<<inches;
return output;
}
The statement cout<<36<<unit;
will produce the following output
36 inches

File Handling
C++ provides the following classes to
perform output and input of characters
to/from files:
1. ofstream: Stream class to write on files
2. ifstream: Stream class to read from files
3. fstream: Stream class to both read and
write from/to files.

These classes are derived directly or indirectly from the


classes istream, and ostream.
We have already used objects whose types were these
classes:
cin is an object of class istream
cout is an object of class ostream
Therefore, we have already been using classes that are
related to our file streams.
And in fact, we can use our file streams the same way
we are already used to use cin and cout, with the only
difference that we have to associate these streams with
physical files.

Why file handling

Convenient way to deal large quantities of data.


Store data permanently (until file is deleted).
Avoid typing data into program multiple times.
Share data between programs.

We need to know:
how to "connect" file to program
how to tell the program to read data
how to tell the program to write data

ios

istream

streambuf

ostream

iostream

ifstream

fstream

ofstream
filebuf

fstreambase

ifstream , ofstream and fstream classes are derived from


fstreambase.
ifstream, ofstream and fstream are declared in fstream.h
Class fstream contains an object of class file buffer which is file
oriented buffer derived from more general stream buffer class.

A sample code
// basic file operations
#include <iostream.h>
#include <fstream.h>
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}

This code creates a file called example.txt


Inserts a sentence into it in the same way
we are used to do with cout,
But it is using the file stream myfile instead
of using the standard output stream i.e.
cout.

Step1 open a file


The first operation generally performed on an object of
one of these classes is to associate it to a real file. This
procedure is known as to open a file.
An open file is represented within a program by a stream
object (an instantiation of one of these classes, in the
previous example this was myfile) and
Any input or output operation performed on this stream
object will be applied to the physical file associated to it.

open function
In order to open a file with a stream object i.e. an object
of type ofstream we use its member function open():
open (filename, mode);
Where
filename - is a null-terminated character sequence of
type const char * (the same type that string literals have)
representing the name of the file to be opened,
mode - is an optional parameter with a combination of
the following flags:

Modes
ios::in

Open for input operations.

ios::out

Open for output operations.

ios::binary

Open in binary mode.

ios::ate

Set the initial position at the end of the


file.
If this flag is not set to any value, the
initial position is the beginning of the
file.

ios::app

All output operations are performed at the


end of the file, appending the content
to the current content of the file. This
flag can only be used in streams open
for output-only operations.

ios::trunc

If the file opened for output operations


already existed before, its previous
content is deleted and replaced by the
new one.

All these mode flags can be combined using the


bitwise operator OR (|).
For example, if we want to open the file
example.bin in binary mode to add data we
could do it by the following call to member
function open():
ofstream myfile;
myfile.open ("example.bin", ios::out |
ios::app | ios::binary);

For ifstream and ofstream classes, ios::in


and ios::out are automatically and
respectively assumed, even if a mode that
does not include them is passed as
second argument to the open() member
function.

Default open mode


If we do not specify any mode with the open
function, it assumes some default values
depending upon the type of stream object you
are creating.
Each one of the open() member functions of the
classes ofstream, ifstream and fstream has a
default mode that is used if the file is opened
without a second argument:

Class

default mode parameter

ofstream

ios::out

ifstream

ios::in

fstream

ios::in | ios::out

Using constructor to open a file


Since the first task that is performed on a file stream
object is generally to open a file, these three classes
include a constructor that automatically calls the open()
member function and has the exact same parameters as
this member function.
Therefore, we could also have declared the previous
myfile object and conducted the same opening operation
in our previous example by using the constructor only,
that will create the stream object for file and will open it
as well:

ofstream myfile ("example.bin",


ios::out | ios::app |
ios::binary);

Combining object construction and stream


opening in a single statement.
Both forms to open a file are valid and
equivalent.

Step 2.
Using the file stream object
After the file stream is opened successfully
with desired opening mode, we can use
the object to read/write data to the file
For example, if I need to open a file for
output operations and want o write some
data to file, we will write a code lines like

.
// create an object of ofstream type
ofstream myfile;
// open the stream for file example.txt.
// note no open mode is specified so
// default will be used i.e. ios::out here
// as it is an objetc of ofstream class
myfile.open ("example.txt");
// use the myfile object to write to file.
// note the use of << to write to file, in the same
// way as with cout.
myfile << "Writing this to a file.\n";

Step 3 close a file


When we are finished with our input and output
operations on a file we shall close it so that its resources
become available again for some other process/program
for further usage of the same file.
In order to do that we have to call the stream's member
function close().
This member function takes no parameters, and what it
does is
to flush the associated buffers and
close the file.

Syntax close()
The code will be like
myfile.close();
Where myfile is a stream object already opened with the
open member function.
Once this member function is called, the stream object
like myfile here can be used to open another file,
The file is available again to be opened by other
processes.

Example programs of
Character i/o
Writing/reading string.
Read/write object.

WRITING STRING:
#include<fstream.h>
void main()
{
ofstream out(test.txt) //creates file.
out.open(test.txt);
out<<Amity University;
out<<AIIT Noida;
out.close();
getch();
}

READING STRING:
void main()
{
const int MAX=80;
char buffer[MAX];
ifstream in(test.txt);
while(in) or
while(in eof() != 0)
{
in.getline(buffer.MAX);
cout<<buffer;
}

CHARACTER I/O
writing character by character.
#include<fstream.h>
#include<string.h>
{
char str[] = Amity University;
ofstream out(test.txt);
for(int j=0; j< strlen (str); j++)//for char. by char.
out.put(str[j])
//write it to file.
getch();
}

Reading character by character:


void main()
{
char ch;
ifstream in(test.txt);
while(in)
{
in.get(ch);
cout<<ch;
}
}

COPY ONE FILE TO ANOTHER


CREATES 2 ARRAY(SOURCE AND TARGET)
void main()
{
char source[100],dest[100];
char ch;
cout<<enter source file;
cin>>source;
cout<<destination file;
cin>>dest;
ifstream in(source,txt);
ofstream out(dest.txt );
while(in)
{
in.get(ch);
out.put(ch);
}
}

Which of the predefined stream objects are


automatically opened when program execution start.
solution: clog, cerr, cout, cin.
clog -> error stored in buffer.
cerr -> error message immediately shown on screen.
example:
#include<process.h>
void main()
{
ofstream out(abc.txt);
if(!out)
{
cerr<<file cannt open correctly;
exit(-1);
}

reading & writing object


TEXT FILE: Source code is a text, and when we write a
program then it is a text file.
when we save file, it is binary file because it is in 0s and
1s form.
In text file data stored in form of ASCII character.
example: source code file is text file.
In binary file data is stored in same way as it is stored in
the main memory for processing.
example: word processor store documents as binary files.

We can use save as option to save a document as a text file.


Binary files are used when we deal with raw data i.e that are
byte level.
To store and retrieve data from a binary file member function
read and write are used.
TEXT: 12345. Each digit is converted to ASCII character which
occupies 1 byte for each character.
Binary: 12345. Uses 2 byte for whole as it takes it as one
integer.
Advantage of binary file:

saves lot of space.


faster access to files.
security.

Program of reading and writing object:


class person
{
protected:
char name[40];
int age;
public:
void getdata()
{
cout<<enter name<<age;
cin>>name>>age;
}
};

void main()
{
person p1;
p1.getdata();
ofstream out(abc.txt);
out.write((char*)&p1,sizeof(p1));
getch();
}

// address of object
to be return.

It is necessary to cast the address pass to write function into


char* since write doesn't know about person.
Reading object from file:
class person
{
protected:
char name[20];
int age;
public:
void putdata()
{
cout<<name<<age;
cin>>name>>age;
} };

void main()
{
person p1;
ifstream in(abc.txt);
in.read((char*)&p1,sizeof(p1));
p1.putdata();
}

Reading & writing multiple objects:


class person
{
protected:
char name[20];
int age;
public:
void showdata()
{
cout<<name<<age;
} };
void main()
{
person p1;

fstream file;
file.open(abc.txt,ios::app | ios::in | ios::out);
do
{
cout<<persons data;
p1.getdata();
file.write((char*)&p1,sizeof(p1));
cout<<another person(y/n)?;
cin>>ch;
}
while(ch==y);
file.seekg(0); //cursor go to starting of file.
file.read((char*)&p1,sizeof(p1));

while(!file.eof())
or
while(file)
{
cout<<person;
p1.show();
file.read((char*)&p1,sizeof(p1));
}
}

get and put


stream pointers
All i/o streams objects have, at least, one internal stream
pointer.
ifstream, like istream, has a pointer known as the get
pointer that points to the element to be read in the next
input operation.
ofstream, like ostream, has a pointer known as the put
pointer that points to the location where the next element
has to be written.

Finally, fstream, inherits both, the get and the


put pointers, from iostream (which is itself
derived from both istream and ostream).
These internal stream pointers that point to the
reading or writing locations within a stream can
be manipulated using the following member
functions:
tellg() and tellp()
seekg() and seekp()

tellg()
Get position of the get pointer.
Returns the absolute position of the get pointer.
The get pointer determines the next location in
the input sequence to be read by the next input
operation.

tellp
Get position of put pointer
Returns the absolute position of the put
pointer.
The put pointer determines the location in
the output sequence where the next output
operation is going to take place.

seekg()
Set position of the get pointer
Sets the position of the get pointer.
The get pointer determines the next location
to be read in the source associated to the
stream.
istream& seekg ( streampos pos );
istream& seekg ( streamoff off, ios_base::seekdir dir );

seekp
ostream& seekp ( streampos pos );
ostream& seekp ( streamoff off, ios_base::seekdir dir );

Set position of put pointer


Sets the position of the put pointer.
The put pointer determines the location in the
output sequence where the next output
operation is going to take place.

Stream or FILE POINTERS


getpointer
-seekg()
-tellg()

putpointer
-seekp()
-tellp()

Used to move cursor to a specific record.


seekg() and tellg() allow to set and examine the get pointer.
seekp() and tellp() performs these function on put pointer.
It specifies the current get position and current put position.
ios::beg
beginning of file.
ios::cur
current position of file.
ios::end
end of file.

Beg
cur
End
seekg(4,ios::cur)
// it moves the get pointer to
4 position forward from the current position.i.e b
seekg(-3,ios::end) b
seekg(9,ios::beg) b
seekg(5)
t

To display the specific record out of many:


class person
{
protected:
char name[20];
int age;
public:
void showdata()
{
cout<<name<<age;
cin>>name>>age;
}
};

void main()
{
person p1;
ifstream in;
in.open(abc.txt);
in.seekg(0,ios::end);
//go to 0 byte from end.
int endpos = in.tellg();
int n = endpos/sizeof(p1);
cout<<there are<<n<<persons in file;
cout<<enter person number;
cin>>n;
int pos=(n-1)*sizeof(p1);
in.seekg(pos);
in.read((char*)&p1,sizeof(p1));
p1.showdata(); }

Preprocessor
A unique feature of c language is the preprocessor. A
program can use the tools provided by preprocessor to
make his program easy to read, modify, portable and
more efficient.
Preprocessor is a program that processes the code
before it passes through the compiler. It operates under
the control of preprocessor command lines and
directives.
Preprocessor directives are placed in the source
program before the main line before the source code
passes through the compiler it is examined by the
preprocessor for any preprocessor directives.
If there is any appropriate actions are taken then the
source program is handed over to the compiler.

Preprocessor directives
Preprocessor directives follow the special
syntax rules and begin with the symbol #

Notice that they do not require any


semicolon at the end like any other normal
statement

We would learn the following preprocessor directives


here
Macro expansion
File inclusion
Macro Expansion
#define UPPER 25 // macro definition
void main()
{
int I;
for (i=1;i<=UPPER;i++)
{ printf(\n%d,i);
}
During preprocessing,the preprocessor replaces every
occurrence of UPPER in the program with 25.

File inclusion - #include


The preprocessor directive #include can be used
to include any file in to your program. if the
functions or macro definitions are present in an
external file they can be included in your file
#include filename
In the directive the filename is the name of the
file containing the required definitions or
functions.

Alternatively this directive can take the


form as below without double quotation
marks.
#include< filename >

If used as above with filename within <>,


in this format the file will be searched in
only standard directories.

A set of commonly used preprocessor directives


#define

Defines a macro substitution

#undef

Undefines a macro

#include

Specifies a file to be included

#ifdef

Tests for macro definition

#endif

Specifies the end of #if

#ifndef

Tests whether the macro is not def

#if

Tests a compile time condition

#else

Specifies alternatives when # if test fails

Q.No 1 cout is a/an __________


.
A. Function
B. Operator
C. Object
D. macro

Q.No 2 Which of the following is the correct


class of the object cout?
A.
B.
C.
D.

iostream
istream
ostream
fstream

Q.No 3 Which of the following header file


includes definition of cin and cout?
A.istream.h
B.ostream.h
C.iomanip.h
D. iostream.h

Q.No 4 The return 0; statement in main


function indicates
A. The program did nothing; completed 0
tasks
B. The program worked as expected
without any errors during its execution
C. not to end the program yet. not to end
the program yet.
D. None of above

Q.No 5 Which of the following header file


does not exist?
A <iostream>
B <string>
C <sstring>
D <iomanip>

Q.No 6 A function that changes the state of


the cout object is called a(n) _____
A. member
B. adjuster
C. manipulator
D. operator

Answers1C
2C
3D
4B
5C
6C

Thank You
Please forward your query
To :bminocha@amity.edu
Cc: manoj.amity@panafnet.com

You might also like