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

Oops Using C++ Unit 1-4

Uploaded by

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

Oops Using C++ Unit 1-4

Uploaded by

srishti kukreti
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 187

O0Ps n C++

aim Of OoP i8to. bind oqe ther the data


The mainn
on them%0 hat
ond the function3 that operate
Code Con acce3s this data
mo other part of the

iexceptthi3 function

Ciass is er defin ed dato types which hoi dz


Own data member3 and member function8 ,which
Con be access ed and us ed by creatinq an Ins tane

ofthot class.

Object When a class is defined mo memor is allocated


but When t 18 instontiated Cie, Obj ect S ereaed)
memory allo coted.

Encapsulation In
0oP,Encapsulation iS defined as binding
together the dota an the functions tht manîpulateg ten

Abstraction Abstraction means display tng


- only ess ent iQ
intorm ation an d hidi ng h ne
detoils.
Abstraction uSing classeß
Abst91aetion usit Head er tile3
Cmath h poW))
Poly morphism Tn stmple Word3,we Can de ine Poly morphi
asthe ability Of a
message to be
display ed 1
more than one form
OperatoY Overloa dim
Funchon Overloa din
Tnt Sum C0, 20
,30)
int Sum (lo, 20))
mheritance The Capabi lity ofa ela ss to dert ve
Propertieg an characteri8tic3 rom anoTh er class
S Called nheritance
SubClass
Superclass
Re usabîlitu

Dyma mie
Binding dynamic bindin, h e Code to
be exe cu+ed An desponse Fuhctioncall 3
decide af un time

Conptructois A conStru ctorr iS a member function of


a class Which nitalizes object o f a elass n Crt|
Constuctor autonatically Calleà When the obect

create3
has Some ame ag l a s s Rtse .5.GHu

Constuctor don't have a etum pe

Default Constouctor No Porameter Possed)


Parometrized ConstTUcto
3 ConsTO uctbs
Copu
Destuctos in Ctt Derived cla 83 destructor wil
be invoked ftrst t h e n the base elasa destSuctoT
will be invoked,

AcceB8 Moditer. b l i c - Can be accessed b y any elass.


Private Can be accessed only i b y a f a n c t i o in-a

elass (?naccesfble outside the Clasa). A

rotected i3 aSo na ccessible ouTSide the


elass bu gub claCS ot

tha class
Can be acce ssed
y
Note Tf we do not S peci ty dny
Ccess
modifier
detauit he acce s3
1nside the Class then by
member
wiil be PTVGtE
modi fier he
Friend elass A tinend Coss can aceess PTvate
of other CloSS in Which
and protected mem bers
declared aS riend
riend alass B

Inhe ritancE
Class SubclasS 3 acess m ode bose class

Sinq e heritance
A

2. Multi Ple Gnhertance 3 Mulieve

Heera rchical fnheritance 5 Hbrid


A Combination ot oe
or more tyPe.

Polymorphism aOperator overloadinq


Compile time
y Function Oerloa dYr
Run ttme Poly
Funcion Oveidina O CcusB When a desive
elass haS a detinition
one Or more
membess bse ctas 4
Advantages of Data Abstraction
Avotd code dupli catton and ne. seusability
can chanqe nTeTnal implemertation otedss
ndepedently
Stoucture Vs Class o3t mportant difference
S Secusi y
A STTuctute not Secue ana Can not hide

3 membes functi on Ond Varlablee While lass

seuse and canhide t 3 P o s a mming 2

desiqrin detai3.

in C+* A cla9s declared. inside a


Local Claspes
function becomes local to hat un@tion and called|

loca lass
Al the methoð3 ot (ocal clasS must k ë detne2d

inside the ctoss only

Virtual function and


Runtime Poly morphism:
Virtual fun ction member Punction Which
A
iS declare à wthin a base a l o s s a n d red efined
derive20 elas3
(overriden) by
declared wHh V iotual Key word n
Functior are

base aos3

n Ct+
Exceptfon Handlinq
block of Code hat Can MTO WM
represet a
an exception
block Of Code that q e Executed
Catch eptesunt
error S hrow n
When
how Used On xceptib N
nere Speci aliCa
a blocK Cacn* )
+catches all type3 Ot erYOT

Tnline Fun etion

mine 3 aa reque 8 t Mot Commdn d .


funchion Mat 13 expanded ine When (t i3
colled. When he n line function called Whole
Code get Tnserted or Sokstitv ted athe pofn+ of înline
foncion Call

n ne
etunntype fun

Function Overloading a eature


Ctt Where
+wo or more onetions n have Same mame but
drfferent parameferz .

Void Pr+nt ( înt 1)


Cout e" Heres fn+ <<î e endl

Void print (flo7t i)


Cout " Here 8 foat" ce i
-

<c endl,

main
print(1o);
print (lo-i2)
pifferences b/ e ano Cr+

213dmC*T
CSupport3 Procedural proa Ctt iS Known as ny brid
tramquoge,9/dbeca vse 1t ort
both proceduraland object
oriented prog ramming
a. As Cdoes not SuPPort he C++ has Upport for poly mr
oofs Com cept has mn6 phis, encapsulation0 and
Support for polymorphism, 1nheita nce as t g an
encapsulath on and in heritance. oofs anquaqep tore

3 SUbset of CtT C t i s svperset of C

C Co tainS 32 keywordg Con tain 52


4 Ct+
KeyworcB|
Cpublic pavate, Protected
try tch, tnro w D
5. C 18 a functio driven lanquaqe C+* 13 an Objectdriven

languaoe.
6 Func+ion and operator over (oading C++ sUPport 3funtion
mot SPPort in C. Operator overlodding.
Tot Sopport exception daes SoPPort
7. does
hand linaq O CREEDtion hondin Usin
and atch
of dissimjlar elgmentg
StructTUre 18 a Collection

*
Static Members n

Static variable în a function When a variable

decloredd as Sttic Space or i+ getz3 allo cated for tne

ietime of the PTogrom (detaut fntialized


to o)
Even the tunction 3 Cailed multiple timEs he
Spacefor t 18 allocated once.

Static Variable in aclasS


Declored inside the class body
Also known a3 elass member Varidble .

They must be defined Outside he class

Static VOr iable doesn'+ belong any object bUt to


tne Whole Closs
here will be only a Copy of Static member varigbe
tortne whole clags

Ex elass
Accov
prtvate
balance;
Static TO

publie
Void setBalance Cimt b)
baonce =bj

l intialised outsi de doss


tloat Account Yo1 =
3.Sf;
Void main

Accountai
Dbjec+ con aso be decloredd aB 3tatic.
Statlc Account aL

Statie function in a lass


r
Static mem ber funcHong are alowed t o Occegs
only+he StatC daa members of Other etaHe
member tunc-tions.

ConshructorB
9'gm)+nl
ConstYUCtor8 On
special mem ber. yfun ctionprof me
Class. Tt i3 au tomatcolly nvo Ked when an object

iS created.

I has no Teturn
type
ConsS+ructor has Same Mame asClasS Hse
C++
TF we do ot spea fy en o mpiler generates
a default Comt rvctor tor

Constrvctor

Defoult Parometerized
CoPY
Classnamel) Cass-name (panameter2 9.CAsname (ong8t
Class-na me ob

updateC) S

UpdakelN*K, nt q) TUpdate(Constüpdate
YS9Y
a=p2.a;
rp b 20 b
enerates wo ConstUCHOr by Se
Compiler
1 Defau bnstructor
3.
Co Con strUCTOr

any of he onstructor
cratEd
by user,
defau + Constructor wil be CYeate by
then
Compi er.
Construction over loqding Can be done ust+

fonction overloqding

Delav+ (Compiler' 8) Constructor Can done Only


Copy
shallow CoPy

CPoint3 o Same
memory o ation)

ob) obj 2

Deep Copy Possble only Witm vser define d Construtoa


USer defined Copy constrUCtor we mare SoYe NF

pointess ot Copied object Points to mew memory lotion

Can we
make opy Consthructor priate ?
Yes
Why argument to Copy Constructor must be passed
a ° referene ?
Because we
pass vatue Men T Woul d ma de

to Constructor which becomes mon-termingti

PO

Deep CopP
Desructor

DesthUCtds a

delet es
member functlon Which destUCt 3 or
ans objectF
DesYuctos don+ ake any araument and don'+
hae ny retuYn type
only one destrUctor Poss ible
Des+TUCtor conno* DE
Soric
Actuall destrtor doezn't
destroy object i t
i3 me last
Func tion that invOked before object desry

ODjecF Kesource

Oe 3tructor US ed, So that before deletion of obj


We Can free space allocoted for thi8 resoUVce b/c
obi ets deleted then space allo cated for obj
l bee ree resovYee doegn't

Operatoor Overlo ading


+* have the ability topovide specal meanig
he operotor.

Class omple2X
'

omplex operatar + (Complex lei)


amplex reB 3
seg. C
eB b c2b

in main C)
C+c2
As + directly So W
CompleX no'3
Con+ add
Con define afunctton With ma me bot we

need write operator Keyword beore


So w e ' Use a operatoS r e this

Friend Ciass
A friend ela8s Can the Pri vate and
OcegS pro tected
members Other class i n Nhich + daclared 93
friend.
There an De riend elass a n d riend tunctr on

Ex ClaCs Box

private
dauble width
Public
friend YoidprintW idth (Box box)
Noid SetWidi( davble wia)

Vold Box SetWidh (Box double Wid)


Wdth Wid,
old PritWidHth Box
box)
Cout box width

mainC)
Box box
bx setWidti 4);
printWcth box)D
Tnher?tance
proce88 of in herhnq prope rties and behaviour
of existinq class into d ne lass.

Ciass Base cla ss elass der.closs

VisibiiryMode

EX class Car ClossSport3ar hipblie;j a r

of Tnneñtance
ypes
Q).
Single Tnheritance :

class B Public A

Inherl-ance :
b). Multilevej

public A
Class 8

3
class C poblic B
Tnhertance 3 b i AL
C). myltiple
ass AL Closs A2

eloss B publie Al, publie Az

d). HeirarehialTnher Itance

Clo ss B1:Public A

61-i
282
cloSS 82 Public A

9enic

Visibilty Mode :
Private
Protectd
A bose alossS Publle
- Sub Class
A

Private A
leotecka
-Kbliet
rinte> Publie
rotectes
vate
Sub CloBs
andNisibitiry Mode Public.
eloss

then Pdblie member., WN bee and protete


public n
will Protected.
visibility mode is Privatee hen both Protected
and poblicV member of A wi be Private membe S

1S a
Relationship always mplenm ented aB a
public n heri t nce

Constructor and Destructor n Thheritonce

First child elass ConstTU Ctor wil TUn during cretton


of object Of Ohi d el08S bot Soon

ereated Chi ld Class ConstruCtor YUn and twi al


CcnstTv et0s Of poret and 4AHes tne eeute
dass cONStSVGtps t wlll esIme + ConBtrctor
Oparent
aecuion,
ONd Poret
CostsUCtDT Cal

BC) AC)
ConstruCtos exer,

A d Const
While n ase e desesU Ctos,
exea
fHrt chi ld destrvctos
farent Con&
then arent 'des. exeCuted.

Complete pora

Comple+e d u |
this Pointer
Every object in CT has access to 113 own addre 83
mrouan an
imortat pointer aalled thi poimter

Friend function doezn + nave poimte, ble


friends are mot members of a ca33. Only member
funetlon have thi3 pointer

Class Box
private
9,b,h
Poblie
NoldY2I$et C Int 2:Ant b nt a)uite
hig> =

thisab b
this hn h

i t mgin C)
Box

beet (S ,\0, H);

Method Over Riding


(achleved at run Me)

S hee
vedei nition of base cksS
in
fonc+ ion
derived cla 33, with Same
return and same
parameter3
whíle method
NerloadingtnS achieved at Gompile ime.

Clo83 Cor
private
nt qearno
Publt
Yoiid
ge-(jnt aer
ear+t

Closs Spor13 a r Public Car

void Change qear n + qear


gear > 5D

enr+

main
S p o r t s Car

BC Cha nae qear(4),

Class will be Call ed.


uncton of spors ar
-

Change-qear ) fArat + Cheek if any fon


While Callino
in be s e alling Clo 38, o-th erwi
with Wo me
base o s s
Cha nge-ear for a excePT one car
Uselul e we Have
ehod of erCha mee
SWhich have uniqoe
Sjioma Virtval Function

A virtua function i3 a member tunction Whi ch iB


decla red base Class
With 'virtua Keyword
aa
Ond Tedeclared loverridden) na desived class
When refer to an 6bjec Ot derive d Cos8 Usinq
You
pointe b0se cla 83 y Can Calla virtuai tunctin
that execute derived cla B' B
object and

Version ot me fonction

They are used to achieve Ron time foly mor phism


Virtual Fonction Can not be Static and aiso Ccannot be trlend
tunction ot another closS

Compile-time Early binding) Run-+me Chate Binding)

e osS base

Sublic
vfrtval void print C)
"

Coutee This s bo8e print ec


Endl

Void Show
Coutcc Bose Show fon ee
endlG

clasS derived
publicsi 1i n
Noid printC)
CoUt <e:" deriived sint eend1
Void showc)

Cot e - derived3Showfon e dl; )


int main )
base bptr
derived der :T 9V
bptr 2 der.

Dp rintC) /Ron ime


bptr Show Compi le ime

ODtpUt derived Prin .' h Late ind iny

Base Show tun Early binding


6iyoT
As during Compi1er ime behaviovr Udqeá on
bptr
the ba8dzV o whicb So bptr repreEt
cloSs elong,
base clo 8
function mot virtual then + wiW allow bindíng

and twn bose etas wil)


Compile Hme prit
bindedd blC bpTT 9epreßent ba se elo ss
at YUn ime bptr Pois to the
But
o+ derlved So +wi bindfunchon
objecr clas
O derived Sun time

Workinq of Virtual Function Table


fonction then Compiler tself
T a closss
chtalnss virtual

doestwo mings
obj i8
(veTR)s ereated every ime
A Virtual pointer
that Class which Comains V iftual toncion
ereated

obect CYEate2 not, statie


respective OF
called VTABLE where each ceil-polt
array of Poiter
n b0 %e
vital funeion 8 Created,

deriNcd Ca sg
Class an d
durnng Eorny binding

VTABLEG for baBe clas


PTR
kate bigdino

VTABLE forr derives dlas

Pore Vivtual function


and 3 bsract Closs

inidyr
Some+íme3 mplementation Of all funcrion n not be proyit
n the base Class , Such aCoss is CAled abstaet class

drawO
Shape (Bct here
im plementatton
Cant be ony
et draw
e angie Square tun n base ttass

ApUTe virtual Fn ction n C+*


virtvat function for
WhichL We don'+ nave any mplementation,
we only declae

ABStroct Cla ss

public
orS Virt ual fun cHon
virtugl void Tun l) =0

A aloss is
abstra ct 14 + has at legs onc
.pUre virtual:fon etion
We cannaDt declare obect ofObs troct elo 83
Ex Test Wil eror
Show

2. We Can have Pointer or reference o - abstrac


closs

We an dccesS
he Omer fun ctions CKcept Virttaa
by object of i tS deived elass
we dont Override tme Purevirtua foneHon
in derived clasp hen it becomes a h s a d t
5. An abstract Class Con naNe ConstruCtorB
CRead 4rom GfG)

Templete in C +

temp late <clas X> t CneK Cipt 9 , X 6)


X-

Ca>b)
TErvrn aj
ei8e TerUT n b,

ín data tpe. So tha e Can


doe ust heP
tunction hat an be TUr
WaTte qenerIC
diterent data
yre
Pynamie Constro ctor
all o cotïon of memory done dynamicaliy
When
allocator new in Cnst ructor.
dynamic memory
USing
Class qeeks
Poblle
Vo id fon C)
P new Chor C6]
-

maln ()

geers
new aeeks)
OBJECT ORIENTED
PROGRAMMING

(with C++)

OOPS (Unit - 1) Dr. Gaurav Gupta 1


BOOKS TO REFER

 E. Balagurusamy,Object Oriented programming


with C++.
 Robert Lafore,Object Oriented programming in
C++.
 The Complete Reference (C++)

OOPS (Unit - 1) Dr. Gaurav Gupta 2


Procedure Oriented Programming
 Logically related statements are grouped
into functions(or procedures).
 such function performs some logical task.
 A function can call other such functions.
 functions may share some global data.
 Main drawback is global data sharing,
due to which adequate synchronization is
to be established among all functions
using it.

OOPS (Unit - 1) Dr. Gaurav Gupta 3


Object Oriented Programming
 The data and the function operating it is coupled to
to form a CLASS.
 Main features of such programming are
1. Encapsulation
(coupling data and functions together)
2. Inheritance
(Inheriting some class and add more functionality to new
class)
3. Polymorphism
(more than one class in inheritance branch may have same
named function)
OOPS (Unit - 1) Dr. Gaurav Gupta 4
Object oriented programming languages

1. ADA
2. C++
3. Java
4. C# (C sharp)
 Most of them also supports full syntax of
procedure oriented programming .
 Each of them supports object oriented
features to varied degree.

OOPS (Unit - 1) Dr. Gaurav Gupta 5


What is C++?
 An object oriented programming language.
 An extension of C (with added feature of
classes).Thus it is a superset of C.
 Follow bottom up programming approach.

 How C++ differs from ANSI C ?


1. It has a different set of identifiers than C( like
bool,export,using,false, true etc.)
2. In C++ main returns an “int” value always (cant has
return type VOID).
3. It doesn‟t put any limit on length of identifiers
whereas some versions of C does.

OOPS (Unit - 1) Dr. Gaurav Gupta 6


3. C++ doesn‟t automatically convert an “int”
value to an enumerated value.(which C
does)
e.g enum colour {red,green,yellow};
colour c; c=red;
c=3;// wrong in C++ ,correct in C
(in C++ it should be c=colour(3);
 In C++ ,Function taking no arguments should
be declared as (not doing so wont result in any error)
return_type Func_name(void).

OOPS (Unit - 1) Dr. Gaurav Gupta 7


Programming Features
1. Main returns an “Int”
2. Comments may be

 single line //

e.g //this is documentation


OR…..
 Multiple lines /*…….*/

e.g/* this is
documentation*/
3. Spaces and tabs can be inserted anywhere to
increase readability
e.g a=12*b-(c/2) is same as 12 * b –( c / 2)

OOPS (Unit - 1) Dr. Gaurav Gupta 8


4. cout identifier is used with operator “<<“to output
data to output devices.
e.g cout<<name;
<< is also used for bit wise left shift operations, thus
<< is overloaded to perform both as shift operator
and “put to “ operator.
5. cin identifier is used with operator “>>” to take
inputs from input devices.
E.g cin>>name;
>> is also overloaded operator to perform both as
right shift and “get from”operator.
cin and cout operators can be cascaded as
cin>>a>>b; OR cout<<“name is”<<name;

OOPS (Unit - 1) Dr. Gaurav Gupta 9


Types of Applications with C++
 Object oriented libraries can be developed
that can be used by several applications
later.
 Since C++ is easily expandable and
maintainable , any application that always
requires new additions can be well
developed with C++.
 C ++ standard library has two halves

1. Standard C library.
2. Class library(that supports object
oriented programming)

OOPS (Unit - 1) Dr. Gaurav Gupta 10


NameSpace
 This defines a scope for the identifiers that
are used in a program.
 For using the identifiers defined in the
namespace scope we must include the using
directive, like
Using namespace std;
 std is the namespace where C++ standards
class libraries are defined.
 This will bring all the identifiers defined in std
to the current global scope.
OOPS (Unit - 1) Dr. Gaurav Gupta 11
Structure of C++ program
 Any C++ program includes
1. Header files (are referred with the help of #include directive)
Syntax is
#include<iostream.h>( this file will be searched in space
assigned to include files)
OR
#include “iostream.h”( this file will be searched in current
working directory)
2. Class declaration
3. Member function definitions
3. Main function

OOPS (Unit - 1) Dr. Gaurav Gupta 12


These sections can be coded in different files and
then linked at the time of compilation.
Program is organised into 3 files
 The class declaration are placed in a header file.

 The definition of member functions go into


another file
 Finally main program that uses the class placed
in third file which includes other two files.
The approach is based on client-server model.
 Class definition including member function
constitute server that provides sevices to the
main program known as client.

OOPS (Unit - 1) Dr. Gaurav Gupta 13


Tokens
Smallest Individual units in a program. C++ has
following tokens :
 Keywords

 Identifiers

 Constant

 Operators

OOPS (Unit - 1) Dr. Gaurav Gupta 14


KEYWORDS in C++
 Are reserved identifiers in C++.
 They cannot be used as names(identifiers)
for the program variables , functions etc.
 Examples include

Double,new,else,if,break,continue,long,
int,float,for ,while,class,inline,struct,void etc.

OOPS (Unit - 1) Dr. Gaurav Gupta 15


IDENTIFIERS in C++
 Identifiers are user defined names for
variables,functions,labels etc.
 Rules to name a variable in C++ are
1. It can include alphabets ,digits ,
underscore(_).
2. It can not start with a number.
3. C++ is Case sensitive thus name, and
NAME are different identifiers.
4. Keywords cannot be used as variable
names.
OOPS (Unit - 1) Dr. Gaurav Gupta 16
CONSTANTS in C++
 Constants refer to fixed values that do
not change during the execution of a
program.
 Like C , C++ supports various literal
constants. They include integers ,
characters, floating point numbers and
strings.
1. 123
2. 12.34
3. “Abc”
4. „h‟
OOPS (Unit - 1) Dr. Gaurav Gupta 17
OPERATORS in C++
 Relational operators( represent
relationships between values)
Operator Action
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equals

OOPS (Unit - 1) Dr. Gaurav Gupta 18


 Logical operators (used to connect
relationships )

Operator Action
 && AND
 || OR
 ! NOT

OOPS (Unit - 1) Dr. Gaurav Gupta 19


 Bit wise operators( performs operations on
bits of char and int data types)
Operator Action
& AND
| OR
^ Exclusive OR
~ Complement
>> Shift Right
<< Shift Left

OOPS (Unit - 1) Dr. Gaurav Gupta 20


 Mathematical Operators (perform
mathematical operations )

 Addition(+)
 Subtraction(-)
 Multiplication(*)
 Division(/)
 Modulus(%)
 Unary minus(-)
 Unary Plus(+)

OOPS (Unit - 1) Dr. Gaurav Gupta 21


 Assignment Operator(=), for assigning
value to a variable.
 scope resolution operator (:: ) to define
scope of a variable or function.
 Conditional Operator(?)is a ternary
operator can replace if-then-else structure
Expr? Val1:Val2
Expr is evaluated ,if true value of
expression will be Val1 else Val2.

OOPS (Unit - 1) Dr. Gaurav Gupta 22


 Address of operator(&) returns the
memory address of the operand
int *p,a,b;
p=&a;
 Pointer operator(*) returns value at
address specified by the operand.
b=*p;
 Sizeof operator returns length (in bytes) of
the operand
int Len , a;
Len=sizeof(a);
(Len will be assigned 2(size of integer data
type))
OOPS (Unit - 1) Dr. Gaurav Gupta 23
DATA TYPES in C++
DATA TYPES

Built-in User-defined
Structure
Integer
Derived
Union
Character Array
Float Class
Pointer
Enumeration
Void Reference

OOPS (Unit - 1) Dr. Gaurav Gupta 24


Void Data Types
 Two uses of void are:
1 To specify the return type of function.
2 To indicate an empty list of arguments.
Eg: void func1(void);
 Another use of void is in declaration of
generic pointers. Eg: void *gp;
 A generic pointer can be assigned a pointer
value of any basic data type. Eg:
int *ip;
gp = ip;

OOPS (Unit - 1) Dr. Gaurav Gupta 25


Enumerated Data Type
 User Defined data type.
 Provides a way of attaching names to no.
 Enum keyword assigns the values 0,1,2 & so on. e.g
enum colour {red, green, yellow};
 We can explicitly assign the values. Eg :
enum colour {red, green=4, yellow=7};
 By using these tag names, we can declare new
variables. Eg: colour background;
 C++ doesn‟t automatically convert an “int” value to
an enumerated value.(which C does)
colour c; c=red;
c=3; // wrong in C++ ,correct in C
c=colour(3); // in C++ it should be
OOPS (Unit - 1) Dr. Gaurav Gupta 26
POINTER & REFERENCE DATA TYPES

1. Pointer: A pointer is a variable that


holds the memory address of other
variable. It is of different data types, e.g-
char pointer can store address of only
char variables, int pointer can store
address of int variables and so on.
2. Reference: A reference in the simplest
sense is an alias or alternate name for a
previously defined variable.

OOPS (Unit - 1) Dr. Gaurav Gupta 27


Declaration of variables in C++
 C++ permits declaration of variables
anywhere,before or at its first use.
 E.g
int main()
{
…………
For(int I=1;I<5;I++)
{…….}
double sum,number;
}

OOPS (Unit - 1) Dr. Gaurav Gupta 28


Dynamic initialization of variables
 In C++ variables can be initialized at run
time( without using constant expressions)
 E.g

int main()
{…..
int sum=32 ,number=4;
………
float average=sum/number;
}

OOPS (Unit - 1) Dr. Gaurav Gupta 29


Operators in C++
 :: scope resolution operator
 delete memory release operator
 endl line feed operator
 new memory allocation operator
 setw field width operator
 ::* Pointer to member declarator
 ->* Pointer to member operator
 .* Pointer to member operator

OOPS (Unit - 1) Dr. Gaurav Gupta 30


Manipulators
 The endl manipulator , causes a linefeed to be
inserted. It has the same effect as that of “\n” .
Ex: cout << « Infosys" << endl;
cout << "Training";
 The setw manipulator sets the minimum field width on
output. The syntax is: setw(x)
int main( )
{
int x1=12345, x2= 23456, x3=7892;
cout<<setw(8) <<”Infosys”<<setw(20)<<”Values”<< endl
<< setw(8) << “E1234567” << setw(20)<< x1 << end
<< setw(8) << “S1234567” << setw(20)<< x2 << end
<< setw(8) << “A1234567” << setw(20)<< x3 << end;
return 0 ;
OOPS (Unit - 1) Dr. Gaurav Gupta 31
}
Reference Variables
 A reference variable provides an alias (alternative
name) for a previously defined variables. Syntax :
Data-type & reference-name = variable name ;
 Ex : float total =100;
float & sum = total;
 Here & is not an address operator but float &
means reference to float.
(i) int x;
int n[10] ; int *p = &x ;
int & x = n[10] ; int & m = *p;
char & a =„\n‟ ; (ii) int & n = 50;
OOPS (Unit - 1) Dr. Gaurav Gupta 32
//Program to illustrate References
#include<iostream.h>
int main(void)
{
int var;
int & refvar=var;
//here a reference variable to var is declared
var=10; //var is given the value 10
cout<<var<<endl;
refvar=100; //reference variable of var is changed
cout<<var; //but var also gets changed
return 0;
}
OOPS (Unit - 1) Dr. Gaurav Gupta 33
Scope Resolution Operator
 The scope resolution operator (::) in C++ is used to
define the already declared member functions.
 Syntax : :: variable-name
#include <iostream>
using namespace std;
int n = 12; // A global variable
int main()
{ int n = 13; // A local variable
cout << ::n << endl; // Print the global variable: 12
cout << n << endl; // Print the local variable: 13
}

OOPS (Unit - 1) Dr. Gaurav Gupta 34


Memory Management Operators
 Two operators new & delete are used to allocate the
memory dynamically. Syntax:
 pointer-variable = new data-type;
 int *p = new int ;
float *q = new float;
*p = 25 ;
*q = 7.5 ;
 Can also initialize as
pointer-variable = new data-type(value);
 For arrays :
pointer-variable = new data-type[size];

OOPS (Unit - 1) Dr. Gaurav Gupta 35


 The fields must not be empty.
array_ptr = new int [4][6][6] ; // legal
array_ptr = new int [4][ ][8] ; //illegal
array_ptr = new int [ ][3][9] ; // illegal
 The delete operator is as:
delete pointer-variable ;
Ex: delete p;
delete q;
For array:
delete [size] pointer-variable;
Ex : [ ] a;

OOPS (Unit - 1) Dr. Gaurav Gupta 36


Types of expressions
 Constant Expression(all values are
constant)
for e.g 13+2 and 6+7*67
 Integral Expression (integral results)

For e.g m*2 and a+b*3-c(a,b,c are integers)


 Float Expression ( float results)

For e.g a+b/2 and 12.34+a


 Pointer Expression(producing address)

For e.g &m and *ptr

OOPS (Unit - 1) Dr. Gaurav Gupta 37


 Relational Expression(yielding
true/false)
For e.g a>b , (c==4)
 Logical expression (having &&,|| etc)
For e.g a>2 && b>=5
 Bit wise expressions (having bitwise
operators)
For e.g a<<3( shift 3 bit position to left)
b>>2(shift 2 bit positions to right)

OOPS (Unit - 1) Dr. Gaurav Gupta 38


Special assignment expressions
1. Chained Assignment
z=(y=12) or z=y=12
// same z=12 and y=12
2. Embedded assignment
x=(y=22)+12;
// y is assigned 22 first then x is assigned 34.
3. Compound Assignment(combination of
assignment operator with binary arithmetic
operator)
for e.g x+=12; // same as x=x+12;
Also called as short hand operator.

OOPS (Unit - 1) Dr. Gaurav Gupta 39


Implicit Conversions
 While evaluating an expression having
mixed data types “smaller” type is
converted to a “wider” type
ie if one operand is float and other is int for
a binary operator then int is being
widened to float type.
Short/char Int unsignedlong
intunsigned long
intfloatdoublelong double.

OOPS (Unit - 1) Dr. Gaurav Gupta 40


Type Casting
 Explicitly changing data type(either a
smaller into wider or vice versa)
 type-name (expression)
int a=23; float b=12.32; int(b);
 If type-name is not an identifier e.g char *
then
 (char*)var is used p = (int *)q;
OR
 typedef char* char_pt;
then char_pt(var) is used.
p = char_pt(q);
OOPS (Unit - 1) Dr. Gaurav Gupta 41
Control Structures in C++
 If-else
 Switch
Selection
 do-while

 while

 For Iteration/Loop
 Break

 Continue

 go to Jump
 Return

these structures are used to control the flow of


execution in a C++ program.

OOPS (Unit - 1) Dr. Gaurav Gupta 42


A C++ program
// FIRST PROGRAM
#include<iostream.h>
int main()
{
Float n1,n2,sum,average;
cout<<“enter two numbers”;
cin>>n1>>n2;
sum=n1+n2;
average=sum/2;
cout<<“sum is”<<sum<<“and average is “<<<average;
return o;

}
OOPS (Unit - 1) Dr. Gaurav Gupta 43
Questions

 1. Which is a valid identifier in C++?


a. abs.no
b. _front!
c. int_no12
d. 1_no123
e. int$no_is

ANS C
OOPS (Unit - 1) Dr. Gaurav Gupta 44
2. Which is true about C and C++?

a. C is a superset of C++
b. C is a subset of C++
c. Both have different spaces
d. Both are same
e. None.

ANS B

OOPS (Unit - 1) Dr. Gaurav Gupta 45


3. Type Casting in C++ is ….

1. To convert smaller data type into a wider


one.
2. To convert wider data type into smaller
one
3. same as explicit type conversion .
4. Never required in C++, as automatic
conversion take place in it.

ANS 1,2 and 3


OOPS (Unit - 1) Dr. Gaurav Gupta 46
4. Which will run well with C++?

1. Printf(“ my name is XYZ”);


2. Cout>>” Enter your name”;
3. Cin>>name>>Number;
4. Do { statements } while condition;

ANS 1, 3 and 4
OOPS (Unit - 1) Dr. Gaurav Gupta 47
5. Which syntax is not correct in C++?

a. For(a=1,b=3;a*b<100;a++);
b. Switch (char array)
{case “abc”: ……;break;}
c. for(;;){ statements…..}
d. For(;a<10;a++);
e. For (int a=1;a<13;);
f. All of the above
ANS b

OOPS (Unit - 1) Dr. Gaurav Gupta 48


Assignment -I
 Differences between switch and if-then
else structures.
 Meaning and usage of keywords…
static,const,extern
 Differences between break and continue
statements.
 How to use Exit() function? Where it is
defined? What can be its arguments?

OOPS (Unit - 1) Dr. Gaurav Gupta 49


Functions in C++

OOPS (Unit-1) Dr. Gaurav Gupta 1


Function Prototype
 A function declaration.
 All functions must be declared(prototyped)
(anywhere) before its use.
 Return_type function name (argument-list);
 Argument list has structure as
( data type1,datatype2,data type3)
 Names for arguments are not required while
declaring it (they don’t have to be matched with
names used for definition or call)

OOPS (Unit-1) Dr. Gaurav Gupta 2


 All library functions used in a program has
prototypes and definitions in header files
included.
 Compiler uses prototype to check number and
types of arguments used while calling that
function.

OOPS (Unit-1) Dr. Gaurav Gupta 3


Function Definition
 The general form of a function definition in C++ is
as follows:
return-type function-name( parameter-list )
{
local-definitions;
function-implementation;
}
 If the function returns a value then the type of
that value must be specified in return-type. For
the moment this could be int, float or char. If the
function does not return a value then the
function-type must be void.

OOPS (Unit-1) Dr. Gaurav Gupta 4


 Prototype is not required if function is defined
before its use.
 The function-name follows the same rules of
composition as identifiers.
 The parameter-list lists the formal parameters of
the function together with their types.
 The local-definitions are definitions of variables
that are used in the function-implementation.
These variables have no meaning outside the
function.
 The function-implementation consists of C++
executable statements that implement the effect
of the function.

OOPS (Unit-1) Dr. Gaurav Gupta 5


Passing arguments in functions
1. Call by value (copy of actual parameter is
acted upon)
2. Call by address(address of actual
parameter is acted upon)
Void swap1(int a,int b)
{
int temp=a;
A=b;
b=temp;
}
OOPS (Unit-1) Dr. Gaurav Gupta 6
• Void swap2(int* a, int* b)  Void swap3(int &a, int b)
{ {
int temp; int temp;
temp=*a; temp=a;
*a=*b; a=b;
*b=temp; b=temp;
} }

OOPS (Unit-1) Dr. Gaurav Gupta 7


 int main()
{
int m=2;n=1;
swap1(m,n);
cout<<m<<n;
swap2(&m,&n);
cout<<m<<n;
swap3(m,n);
cout<<m<<n;
}

OOPS (Unit-1) Dr. Gaurav Gupta 8


What is an inline function?
 Functions defined with “inline” directive
 at each call to such function , its function
body is inserted at that point in compiled
code.
 If function body is small and called at
several places then it should be made
inline as there is no overhead in CALL and
RETURN statements .
 Functions defined inside a class are by
default INLINE.

OOPS (Unit-1) Dr. Gaurav Gupta 9


using inline function….
#include<iostream.h>
inline float prod(float a,float b)
{ return(a*b); }
inline double div(double a,double b)
{ Return(a/b);}
int main()
{
float a=12.654,b=3.45;
cout<<prod(a,b)<<endl;
cout<<div(a,b)<<endl;
return 0;
}
OOPS (Unit-1) Dr. Gaurav Gupta 10
 Inline keyword sends only a request(not a
command) to the compiler, the compiler may
ignore the request and treat the function as
normal one if function definition is too long or
complicated.
 Situations where inline expansion may not
work:
1 For functions returning values , if a loop , a
switch, or a goto exist.
2 For functions not returning values, if a return
statement exists.
3 If functions contains static variables.
4 If inline functions are recursive.

OOPS (Unit-1) Dr. Gaurav Gupta 11


Default arguments
 The argument whose default value is mentioned
at function declaration can be skipped from
actual parameter list at the time of function call.
e.g ret-type function-name(type1,type2 n=6)
 If some value is passed to default argument then
default value is replaced by that value.
 Are useful where one or more parameter remain
same for each call.

OOPS (Unit-1) Dr. Gaurav Gupta 12


#include<iostream.h>
int main(void)
{ char name[12];
int no;
cout <<"enter name and no";
cin >>name>>no;
void display (int , char name[12]="default");
display(no,name);
display(no); }
void display (int n,char name[12])
{ cout<<"name is“<<name;
cout<<endl<<"no is"<<n<<endl;
}
OOPS (Unit-1) Dr. Gaurav Gupta 13
 Output of the program will be
enter name and no aarti 23
name is aarti
no is23

name is default
no is23

OOPS (Unit-1) Dr. Gaurav Gupta 14


Function Overloading

OOPS (Unit-1) Dr. Gaurav Gupta


What is Function overloading?

A number of functions having same name


but performing different tasks.
Every function has differs from others in
return type or argument list.
At function call ,function definition with
corresponding arguments is invoked.
Argument lists may differ in either type of
arguments or number of arguments.

OOPS (Unit-1) Dr. Gaurav Gupta


Example:
 // Declaration
int add(int a, int b); // 1
int add(int a, int b, int c); //2
double add( double x, double y); //3
double add (int p , double q); //4
double add (double p, int q ); //5
 //Function calls
cout<< add(5,10); // uses 1
cout<< add(15,10.0); // uses 4
cout<< add(12.5,7.5); // uses 3
cout<< add(5,10,15); // uses 2
cout<< add(9.75,5); // uses 5
OOPS (Unit-1) Dr. Gaurav Gupta
If compiler is unable to find an exact match
then it tries to use promotions to the actual
arguments and again match new argument
list with function definitions.
char --int
float--double
If after promotions more than one match is
found then it gives error for ambiguity.
long square (long n);
double square (double x);
Function call : square(10); // so Error
OOPS (Unit-1) Dr. Gaurav Gupta
#include<iostream.h>
#include<conio.h>
double volume (float l, float w, float h)
{
return (l*w*h);
}
/*double volume (float l, float w, double h)
{
return (l*w*h);
} */( WILL GIVE AN ERROR)

OOPS (Unit-1) Dr. Gaurav Gupta


double volume (float r, float h)
{
double vol=3.14*r*r*h;
return vol;
}
int main(void)
{
clrscr();
cout<<endl<<"volume of a cube is
"<<volume(2.6,12,21.25);
cout<<endl<<"volume of a cylinder
"<<volume(2,2.8);
return 0;
}
OOPS (Unit-1) Dr. Gaurav Gupta
OUTPUT

volume of a cube is 662.999976


volume of a cylinder 35.167999

OOPS (Unit-1) Dr. Gaurav Gupta


Assignment II
A ) Write a c++ program to overload average
function to compute average of three and
four numbers respectively.
B) Write a C++ program to overload a
function for computing area of a rectangle
and a circle .
C) Write any C++ program to use
overloaded constructor for a class with
one constructor having default arguments.

OOPS (Unit-1) Dr. Gaurav Gupta


OBJECT ORIENTED
PROGRAMMING
(with C++)

Unit-3
Generic Function

OOPS (Unit-3) Dr. Gaurav Gupta 1


Unit-III
Inheritance, Class hierarchy, derivation – public,
private & protected; aggregation, composition vs
classification hierarchies
polymorphism, categorization of polymorphic
techniques, method polymorphism, polymorphism by
parameter, operator overloading, parametric
polymorphism,
generic function – template function, function
name overloading, overriding inheritance methods,
run time polymorphism.

Dr. Gaurav Gupta


Associate Professor (IT Deptt.) 2
Templates
 Templates are the foundation of generic programming,
which involves writing code in a way that is independent
of any particular type.
 Templates allows function and classes to operate with
generic types.
 There are 2 type of templates:
 Function templates – A function template is
a “generic” function that can work with different data
types. Like macros, It enables software reuse. But
unlike macros, fn templates help eliminate many type
of errors through scrutiny of full c++ type checking.
 Class templates - Allows type-specific versions of
generic classes. Just like function templates, we can
also define class templates.
OOPS (Unit - 3) Dr. Gaurav Gupta 3
Associate Professor (IT Deptt.)
Templates
 Template Parameter - A template parameter is a special
kind of parameter that can be used to pass a type as
argument: just like regular function parameter which is
used to pass values to a function, template parameter
allows to pass values and also types to a function.
 Template Instantiation – When the compiler generates
a class, function or static data members from a template,
it is referred to as template instantiation.
 A function generated from a function template is called a
generated function.

OOPS (Unit - 3) Dr. Gaurav Gupta 4


Associate Professor (IT Deptt.)
Function Templates
Function generated from function template is called
template function.
Syntax:
template <class T> returnType FnName(Parameter List)
//Template function
{
:
}

Templates function with 2 arguments of same/different


type depending on argument passed e.g.
template <class T, class U> T getMin(T a, U b)
{
return (a>b?a:b);
}
Dr. Gaurav Gupta
OOPS (Unit - 3) Associate Professor (IT Deptt.) 5
Function Templates
Example:
#include <iostream.h>
template<class x> void swap(x &a, x& b) main()
{ {
x temp; int i=10,j=20;
temp=a; double x=10.1,y=21.3;
a=b; char a=„x‟, b=„z‟;
b=temp; swap(i,j);
} swap(x,y);
swap(a,b);
cout<<i<<j;
cout<<a<<b;
cout<<x<<y;
}

OOPS (Unit - 3) Dr. Gaurav Gupta 6


Associate Professor (IT Deptt.)
Function Templates
 A function template can be overloaded as well as
overrided.
 Example of function Template overloading:
#include<iostream.h> template <class t> void Max(t a, t b, t c)
template <class t> void Max(t a, t b) {
{ if(a>b && a>c)
if(a>b) cout<<a;
cout<<a; else if(b>a && b>c)
cout<<b;
else
else
cout<<b; cout<<c;
} }
main()
{
Max(1,2);
Max(3,2,1);
}
Dr. Gaurav Gupta 7
OOPS (Unit - 3) Associate Professor (IT Deptt.)
Function Templates
 If a template is invoked with a user defined type, and
if that template uses functions or operators (e.g.
==,+,<= etc.) with objects of that class type, then those
functions and operators must be overloaded for the
user-defined type. Forgetting to overload such
operators causes compilation error.

Dr. Gaurav Gupta 8


OOPS (Unit - 3) Associate Professor (IT Deptt.)
Example
Program to define the function template for calculating the
square of given numbers with different data types.
template <class T> T square(T number)
{ return number * number; }
int main()
{
// Get an integer and compute its square
int iValue;
cout << "Enter an integer value: ";
cin >> iValue;
// compiler creates int square(int) at call to square with an int argument
cout << "The square is " << square(iValue); //square<int>(iValue);
// Get a double and compute its square
cout << "\nEnter a double value: ";
double dValue;
cin >> dValue;
// compiler creates double square(double)on call to square with double arg
cout << "The square is " << square(dValue); // //square<double>(dValue);
return 0;
} Dr. Gaurav Gupta
OOPS (Unit - 3) Associate Professor (IT Deptt.) 9
Class Templates
• Class created from a class template is called template class
• Creating a class from class template is called Instantiation
• Syntax:
template <class t> class className
{
:
}
For objects:
className <Type> objectName(Arguments);
e.g.
className <int> obj1(10);
className <float> obj2;

Dr. Gaurav Gupta 10


OOPS (Unit - 3) Associate Professor (IT Deptt.)
Class Templates
• Non-Type Parameters & Default Type
Non-Type Parameter
template <class T, int Size> Default type
class Array template <class T= int> class Array
{ {
T a[size]; T a[5];
: :
}; };

For Object: For Object:


Array<int,10> obj1; Array<> obj; //Instantiation
//Instantiation
Array<float, 5> obj2;

Dr. Gaurav Gupta 11


OOPS (Unit - 3) Associate Professor (IT Deptt.)
Class Templates
• Member function templates - Syntax:
template <class T> retType className<T>::fnName(Arguments)
{
:
}
e.g.
template<class T>
T Point<T> :: operator *(Point & P)
{
:
}

Dr. Gaurav Gupta 12


OOPS (Unit - 3) Associate Professor (IT Deptt.)
Example
Program to find the bigger of two entered numbers using
class template.
template <class T> class pair
{
T a; T b; void main()
public: {
pair() cout<<"\nEnter 2 Integer numbers:";
{ pair<int> obj1;
cin>>a>>b; cout<<"Greatest Integer is”
} <<obj1.get_max();
T get_max(); Cout<<“Enter 2 Float Numbers:\n";
}; pair<float> obj2;
Template<class T> cout<<"Greatest Float is”
T pair<T>::get_max() <<obj2.get_max();
{ }
T ret;
ret=a>b?a:b;
return ret;
}
Dr. Gaurav Gupta
OOPS (Unit - 3) Associate Professor (IT Deptt.) 13
Templates & Inheritance
A class template can be derived from a template/non-
template class
Example
template <class T> class Base
{
protected:
T var;
public:
Base(T val): var(val) {}
T Get() { return var; }
};
template <class T> class Derived : public Base<T>
{
public:
Derived(T valu): Base<T>(valu) { }
T fun() { return var; }
};
Dr. Gaurav Gupta
OOPS (Unit - 3) Associate Professor (IT Deptt.) 14
Function Templates & Static Variable
Each instantiation of function template has its own copy of
local static variables.
Example
template <class T> void fun(const T &x)
{
static int i=10;
cout<< ++i; Output:
} 11
main() 12
{ 11
fun<int> (1); //prints 11
fun<int> (2); //prints 12
fun<double> (1.1); //prints 11
}

Dr. Gaurav Gupta


OOPS (Unit - 3) Associate Professor (IT Deptt.) 15
Class Templates & Static Variable
Each instantiation of class template has its own copy of
member static variables.
Example
template <class T> class Test main()
{
{
Test<int> a; //Value of count for
private: Test<int> is 1 now
T val; Test<int> b; //Value of count for
public: Test<int> is 2 now
static int count; Test<double> c; //Value of count for
Test<double> is 1 now
Test() cout<<Test<int>::count; //prints 2
{
count++; cout<<Test<double>::count;//prints 1
}
}
};
Template<class T> int Test<T>::count=0;
Dr. Gaurav Gupta
OOPS (Unit - 3) Associate Professor (IT Deptt.) 16
End of Unit-3

Dr. Gaurav Gupta 17


OBJECT ORIENTED
PROGRAMMING
(with C++)

Unit-4
Exception Handling

Dr. Gaurav Gupta 1


Unit-IV
Standard C++ classes, using multiple inheritance,
persistant objects, streams and files, namespaces,
exception handling, generic classes, standard
template library: Library organization and containers,
standard containers, algorithm and Function objects,
iterators and allocators, strings, streams,
manipulators, user defined manipulators, vectors,
valarray, slice, generalized numeric algorithm.

Dr. Gaurav Gupta


Associate Professor (IT Deptt.) 2
Exception
 An exception is a problem that arises during the
execution of a program. A C++ exception is a response to
an exceptional circumstance that arises while a program
is running, such as an attempt to divide by zero.
 Exceptions provide a way to transfer control from one
part of a program to another.
 Note that an exceptional circumstance is not necessarily
an error.

Dr. Gaurav Gupta


OOPS (Unit - 4) Associate Professor (IT Deptt.) 3
Exception Handling
 Exception handling is a mechanism that separates code
that detects and handles exceptional circumstances from
the rest of your program.
 Exception handling mechanism consists of following
parts:
 Find the problem (Hit the exception)
 Inform about its occurrence (Throw the exception)
 Receive error information (Catch the exception)
 Take proper action (Handle the exception)

Dr. Gaurav Gupta


OOPS (Unit - 4) Associate Professor (IT Deptt.) 4
Exception Handling
C++ consists of 3 keywords for handling the exception:
 try: Try block consists of the code that may generate
exception. Exception are thrown from inside the try
block.
 throw: Throw keyword is used to throw an exception
encountered inside try block. After the exception is
thrown, the control is transferred to catch block.
 catch: Catch block catches the exception thrown by
throw statement from try block. Then, exception are
handled inside catch block.

Dr. Gaurav Gupta


OOPS (Unit - 4) Associate Professor (IT Deptt.) 5
Exception Handling
Syntax: Example:
try int main ()
{ {
statements; try
... ... ... {
throw 20;
throw exception; }
} catch (int e)
catch (type argument) {
cout << "An exception
{ occurred with value " << e;
statements; }
... ... ... return 0;
}
}

Dr. Gaurav Gupta


OOPS (Unit - 4) Associate Professor (IT Deptt.) 6
Exception Handling
Example:
int main()
{
int x = -1;
cout << "Before try \n";
try {
Output:
cout << "Inside try \n";
if (x < 0) Before try
{ Inside try
throw x; Exception Caught
cout << "After throw (Never executed) \n"; After catch (Will be executed)
}
}
catch (int x ) {
cout << "Exception Caught \n";
}
cout << "After catch (Will be executed) \n";
return 0;
}
Dr. Gaurav Gupta
OOPS (Unit - 4) Associate Professor (IT Deptt.) 7
Multiple Catch Exception
Multiple catch exception statements are used when a user
wants to handle different exceptions differently. For this, a
user must include catch statements with different
declaration.
Syntax:
try {
body of try block }
catch (type1 argument1)
{ statements; ... ... ... }
catch (type2 argument2)
{ statements; ... ... ... }
catch (typeN argumentN)
{ statements; ... ... ... }
Dr. Gaurav Gupta
OOPS (Unit - 4) Associate Professor (IT Deptt.) 8
Catch All Exceptions
Sometimes, it may not be possible to design a separate catch
block for each kind of exception. In such cases, we can use
a single catch statement with ellipsis (...) that catches all
kinds of exceptions which are not caught by other
handlers.
Syntax:
catch (...)
{
statements;
... ... ...
}

Dr. Gaurav Gupta


OOPS (Unit - 4) Associate Professor (IT Deptt.) 9
Example
Program to divide two numbers using try catch block.
int main() catch (int e)
{ {
int a,b; cout << "Exception: Division by zero";
cout << "Enter 2 numbers: "; }
cin >> a >> b; catch (char st)
try {
{ cout << "Exception: Division is less than 1";
if (b != 0) }
catch(...)
{
{
float div = (float)a/b; cout << "Exception: Unknown";
if (div < 0) throw 'e'; }
//’e’ is not implicitly converted to int return 0;
cout << "a/b = " << div; }
}
else
throw b;
} Dr. Gaurav Gupta
OOPS (Unit - 4) Associate Professor (IT Deptt.) 10
Nested try-catch blocks
int main()
{
try {
try {
throw 20;
Output:
} Handle Partially Handle remaining
catch (int n) {
cout << "Handle Partially ";
throw; //Re-throwing an exception
}
}
catch (int n) {
cout << "Handle remaining ";
}
return 0;
}
Dr. Gaurav Gupta
OOPS (Unit - 4) Associate Professor (IT Deptt.) 11
Throwing exception from a function
Example: catch (int i)
void xTest(int test)
{
{
cout<<“Caught exception : ”;
cout<<“Inside xTest: ”<<test;
cout<<i;
if(test)
}
throw test;
cout<<“Main End”;
}
}
main()
{
cout<<“Main Start”; Output:
try{ Main Start
cout<<“Inside try block”; Inside try block
xTest(0); Inside xTest: 0
xTest(1); Inside xTest: 1
xTest(2); Caught Exception : 1
} Main End

Dr. Gaurav Gupta


OOPS (Unit - 4) Associate Professor (IT Deptt.) 12
Exception Specification
To specify the set of exceptions that might be thrown as part
of the function declaration e.g.

returnType functionName(Arg_list) throw(type_list)


{
:
}
This specifies functionName may throw only exceptions of
type_list and exceptions derived from these types but no others.

To throw character as well as integer from xTest() use:

void xTest(int test) throw (int, char)

To throw no type exception from xTest() use:

Void xTest(int test) throw()


Dr. Gaurav Gupta
OOPS (Unit - 4) Associate Professor (IT Deptt.) 13
Re- Throwing an exception
Example: main()
void f(int a) {
{ try{
try f(0);
{ }
if(a==0) catch(int)
throw a; {
else cout<<“Caught Exception”;
cout<<“Good”; }
} }
catch(int)
{
Output:
cout<<“Rethrowing”;
Rethrowing
throw;
Caught Exception
}
}
Dr. Gaurav Gupta
OOPS (Unit - 4) Associate Professor (IT Deptt.) 14
Exception & Classes
When an exception is thrown, all objects created inside the
enclosing try block are destructed before the control is
transferred to catch block.

class Test {
public:
Test() { cout << "Constructor of Test \n"; }
~Test() { cout << "Destructor of Test \n"; }
}; Output:
Constructor of Test
int main() { Destructor of Test
try { Caught 10
Test t1;
throw 10;
} catch(int i) {
cout << "Caught " << i << endl;
}
}

Dr. Gaurav Gupta


OOPS (Unit - 4) Associate Professor (IT Deptt.) 15
Exception & Classes
 If both base and derived classes are caught as exceptions then
catch block of derived class must appear before the base class. If
we put base class first then the derived class catch block will
never be reached. For example, following C++ code
prints “Caught Base Exception”
class Base {}; catch(Base b)
class Derived: public Base {}; {
int main() cout<<"Caught Base Exception";
{ }
Derived d; catch(Derived d)
try {
//This catch block is NEVER executed
{
cout<<"Caught Derived Exception";
throw d; }
} return 0;
}

Dr. Gaurav Gupta


OOPS (Unit - 4) Associate Professor (IT Deptt.) 16
Exception & Classes
 In the above C++ code, if we change the order of catch
statements then both catch statements become reachable.
Following is the modified program and it prints “Caught
Derived Exception”

class Base {};


class Derived: public Base {}; catch(Derived d)
{
int main()
cout<<"Caught Derived Exception";
{ }
Derived d; catch(Base b)
try { {
throw d; cout<<"Caught Base Exception";
} }
return 0;
}

Dr. Gaurav Gupta


OOPS (Unit - 4) Associate Professor (IT Deptt.) 17
To be continued…

Dr. Gaurav Gupta 18


OBJECT ORIENTED
PROGRAMMING
(with C++)

Unit-4
Standard Library, Streams & File

Dr. Gaurav Gupta


Associate Professor (IT Deptt.) 1
Unit-IV
Standard C++ classes, using multiple inheritance,
persistant objects, streams and files, namespaces,
exception handling, generic classes, standard template
library: Library organization and containers, standard
containers, algorithm and Function objects, iterators
and allocators, strings, streams, manipulators, user
defined manipulators, vectors, valarray, slice,
generalized numeric algorithm.

Dr. Gaurav Gupta


Associate Professor (IT Deptt.) 2
Standard Library
A standard library is something that every implementer
must supply so that every programmer can rely on it.
The C++ standard library:
 Provides support for language features such as memory
management and run time type information
 Supplies information about implementation-defined
aspects of the language such as the largest float value
 Supplies functions that can not be implemented
optimally in the language itself for every system such as
sqrt()
 Supplies facilities that a programmer can rely on for
portability such as lists, sort functions & I/o streams
 Provides common foundation for other libraries
Dr. Gaurav Gupta 3
Associate Professor (IT Deptt.)
Standard Library
The facilities of the standard library are defined in the std
namespace and presented as a set of headers.
using namespace std;
Standard library is a collection of classes and functions
which are written in the core language. Header files in the
c++ standard library do not end with ‘.h’ extension e.g.
#include <iostream>
using namespace std;

Dr. Gaurav Gupta 4


Associate Professor (IT Deptt.)
Stream I/O Library Header Files
 A stream is a sequence of bytes.
 A stream acts as an interface between program & i/p, o/p
device.
 A stream is nothing but a flow of data.
 iostream -- contains basic information required for all
stream I/O operations
 iomanip -- contains information for performing formatted
I/O with parameterized stream manipulators
 fstream -- contains information for performing file I/O
operations
 strstream -- contains information for performing in-
memory I/O operations (i.e., into or from strings in
memory)

Dr. Gaurav Gupta 5


Associate Professor (IT Deptt.)
Stream Classes for I/O & File Operations

 ios is the base class.


 istream and ostream inherit from ios
 ifstream inherits from istream (and ios)
 ofstream inherits from ostream (and ios)
 iostream inherits from istream and ostream (& ios)
 fstream inherits from ifstream, iostream, and ofstream
Dr. Gaurav Gupta 6
Associate Professor (IT Deptt.)
C++ Stream I/O -- Stream Manipulators
 Manipulators are special functions that can be included in
the I/O statements to alter the format parameters of a
stream.
 Stream manipulators are defined in <iomanip>
 These manipulators provide capabilities for
 setting field widths,
 setting precision,
 setting and unsetting format flags,
 flushing streams,
 inserting a "newline" and flushing output stream,
 skipping whitespace in input stream

Dr. Gaurav Gupta 7


Associate Professor (IT Deptt.)
C++ Stream I/O -- Stream Manipulators
setprecision (int precision)
 To set floating point precision i.e. number of significant
digits to be printed e.g.
cout << setprecision (2) << 1.2345;
Output: 1.23 // two significant digits

setw (int width)


 To set the field width (can be used on input or output,
but only applies to next insertion or extraction) e.g.
cout << setw (10) <<12345;
Output: _ _ _ _ _ 1 2 3 4 5 //5 blanks+5 digits

Dr. Gaurav Gupta 8


Associate Professor (IT Deptt.)
C++ Stream I/O -- Stream Manipulators
setfill (char fillChar)
 To set the fill character.
e.g.
cout << setfill(‘*’) << setw(10)<<12345;
Output: * * * * * 1 2 3 4 5 //5 stars + 5 digits

endl
 To insert new line and flush stream
cout<<endl;

Dr. Gaurav Gupta 9


Associate Professor (IT Deptt.)
C++ Stream I/O - Stream Manipulators
 Various ios format flags specify the kinds of formatting
to be performed during stream I/O.

 There are member functions (and/or stream


manipulators) which control flag settings.

 There are various flags for trailing zeros and decimal


points, justification, number base, floating point
representation, and so on.

Dr. Gaurav Gupta 10


Associate Professor (IT Deptt.)
C++ Stream I/O -- Stream Manipulators
setiosflags(long f)
 Sets the format flag e.g.

cout<<setiosflags(ios::scientific)<<1.0000;
Output: 1.0000e+000

resetiosflags(long f)
 Clears the flag specified by setiosflag e.g.

cout<<resetiosflags(ios::scientific)<<1.0000;
Output: 1.0000

Dr. Gaurav Gupta 11


Associate Professor (IT Deptt.)
I/O Stream Member Functions
.setf ( )
 Allows the setting of an I/O stream format flag.

 e.g.

// To show the + sign in front of positive numbers


cout.setf (ios::showpos) ;

// To output the number in hexadecimal


cout.setf (ios::hex, ios::basefield) ;

Dr. Gaurav Gupta 12


Associate Professor (IT Deptt.)
I/O Stream Member Functions
.precision ( ) ;
 Select output precision, i.e., number of significant digits
to be printed.
 e.g.
cout.precision (2) ; // two significant digits

.width ( ) ;
 Specify field width. (Can be used on input or output, but
only applies to next insertion or extraction).
 e.g.
cout.width (4) ; // field is four positions wide

Dr. Gaurav Gupta 13


Associate Professor (IT Deptt.)
I/O Stream Member Functions
.eof ( ) ;
 Tests for end-of-file condition.
 e.g.
cin.eof ( ) ; // true if eof encountered

.fail ( ) ;
 Tests if a stream operation has failed.
 e.g.
cin.fail ( ) ; // true if a format error occurred
! cin; // same as above; true if format error

Dr. Gaurav Gupta 14


Associate Professor (IT Deptt.)
I/O Stream Member Functions
.clear ( ) ;
 Normally used to restore a stream's state to "good" so
that I/O may proceed or resume on that stream.

 e.g.
cin.clear ( ) ; // allow I/O to resume on a "bad"
// stream, in this case "cin",
// on which error had previously
// occurred

Dr. Gaurav Gupta


Associate Professor (IT Deptt.)
Using Manipulators & Member Functions
#include <iostream> // No “.h” (standard header)
#include <iomanip> // No “.h” (standard header)
using namespace std; // To avoid “std::”
int main ( )
{
int a, b, c = 8, d = 4 ;
float k ;
char name[30] ;
cout << "Enter your name" << endl ;
cin.getline (name, 30) ;
cout << "Enter two integers and a float " << endl ;
cin >> a >> b >> k ;

Dr. Gaurav Gupta 16


Associate Professor (IT Deptt.)
Using Manipulators & Member Functions
// Now, let's output the values that were read in
cout << "\nThank you, " << name << ", you entered"
<< endl << a << ", " << b << ", and " ;
cout.width (4) ;
cout.precision (2) ;
cout << k << endl ;
// Control the field and precision another way
cout <<"\nThank you, " << name << ", you entered"
<< endl << a << ", " << b << ", and " << setw (c)
<< setprecision (d) << k << endl ;
}
Dr. Gaurav Gupta 17
Associate Professor (IT Deptt.)
Example Program Output
Enter your name
Dr. Gaurav
Enter two integers and a float
12 24 67.85

Thank you, Dr. Gaurav, you entered


12, 24, and •68

Thank you, Dr. Gaurav, you entered


12, 24, and •67.85

Dr. Gaurav Gupta 18


Associate Professor (IT Deptt.)
Creating own manipulator
Syntax:
ostream & manipulator_name(ostream &out)
{
:
return out;
}
How to use it:
ostream &unit(ostream &out)
{
out<<inches;
return out;
}
Example:
cout<<36<<unit;  36 inches

Dr. Gaurav Gupta 19


Associate Professor (IT Deptt.)
Own manipulator with multiple operations
Example:
ostream &currency(ostream & output)
{
output<<“Rs”;
return output;
}
ostream &show(ostream &output) Output:
{ Rs***+503.20
output.setf(ios::showpos);
output.setf(ios::showpoint);
output.fill(‘*’);
output.precision(2);
output.setiosflags(ios::fixed)<<setw(10);
return output;
}
main()
{
cout<<currency<<show<<503.2;
}
Dr. Gaurav Gupta
Associate Professor (IT Deptt.) 20
Files & Streams
 A file is a collection of related data stored in a particular
area on the disk.
 C++ views each file as a sequence of bytes.
 Each file ends with an end-of-file marker.
 When a file is opened, an object is created and a stream
is associated with the object.
 To perform file processing in C++, the header files
<iostream.h> and <fstream.h> must be included.
 <fstream.h> includes <ifstream> and <ofstream>

Dr. Gaurav Gupta 21


Associate Professor (IT Deptt.)
How to open a file?
A file can be opened in 2 ways:
 Using Constructor: Used when only one file is in the
stream. Syntax:
FileStreamClass objectName(“fileName”, open_Mode)
e.g. ofstream outFile(“Try.dat”,ios::out);
OR
 Using member function – open(): Used to manage
multiple files using one stream. Syntax:
FileStreamClass objectName;
objectName.open (“fileName”, open_Mode)
e.g.
ofstream outFile;
outFile.open(“clients.dat”, ios:out)
Dr. Gaurav Gupta 22
Associate Professor (IT Deptt.)
File Open Modes
 ios:: app - (append) write all output to the end of file
 ios:: ate - data can be written anywhere in the file
 ios:: binary - read/write data in binary format
 ios:: in - (input) open a file for input i.e. for read only
 ios:: out - (output) open a file for output i.e. for write
only
 ios:: trunc -(truncate) discard the file’s content if it
exists
 ios:: nocreate - if the file does NOT exists, the open
operation fails
 ios:noreplace - if the file exists, the open operation
fails
Dr. Gaurav Gupta 23
Associate Professor (IT Deptt.)
How to close a file in C++?
The file is closed implicitly when a destructor for the
corresponding object is called
OR
by using member function close:
ofstream outFile;
outFile.close();

Dr. Gaurav Gupta 24


Associate Professor (IT Deptt.)
Sequential file (Using Constructor)
#include <iostream.h>
#include <fstream.h>
ifstream inFile(“File”);
int main()
inFile>>name;
{
inFile>>year;
// ofstream constructor opens file
cout<<name;
ofstream outFile( “File”);
cout<<year;
char name[30]=“Gaurav”;
}
int year=2018;
outFile<<name<<“\n”;
outFile<<year<<“\n”;
outFile.close();

Dr. Gaurav Gupta 25


Associate Professor (IT Deptt.)
Sequential file (Using open())
#include <iostream.h>
while(inFile) //(inFile.eof()!=0)
#include <fstream.h>
{
int main()
inFile.getline(str,100);
{
cout<<str;
char str[100];
}
ofstream outFile;
inFile.close();
outFile.open(“Country”);
inFile.open(“States”);
outFile<<“India\n”;
while(inFile) //eof()=0 on
outFile<<“Nepal\n”;
reaching end of file condition
outFile.close();
{
outFile.open(“States”);
inFile.getline(str,100);
outFile<<“Delhi”;
cout<<str;
outFile<<“Kathmandu”;
}
outFile.close();
inFile.close();
ifstream inFile;
}
inFile.open(“Country”);
Dr. Gaurav Gupta 26
Associate Professor (IT Deptt.)
Reading and printing a sequential file
// Reading and printing a sequential file
#include <iostream.h>
#include <fstream.h>
#include <iomanip.h>
#include <stdlib.h>
void outputLine( int, const char *, double );
int main()
{
// ifstream constructor opens the file
ifstream inFile( "clients.dat", ios::in );
if ( !inFile ) {
cerr << "File could not be opened\n";
exit( 1 );
}
Dr. Gaurav Gupta 27
Associate Professor (IT Deptt.)
int account;
char name[ 30 ];
double balance;
cout << setiosflags( ios::left ) << setw( 10 ) << "Account“ << setw( 13 ) <<
"Name" << "Balance\n";

while ( inFile >> account >> name >> balance )


outputLine( account, name, balance );

return 0; // ifstream destructor closes the file


}

void outputLine( int acct, const char *name, double bal )


{
cout << setiosflags( ios::left ) << setw( 10 ) << acct << setw( 13 ) << name <<
setw( 7 ) << setprecision( 2 ) << resetiosflags( ios::left )
<< setiosflags( ios::fixed | ios::showpoint )
<< bal << '\n';
}
Dr. Gaurav Gupta 28
Associate Professor (IT Deptt.)
File position pointer
 <istream> and <ostream> classes provide member functions
for repositioning the file pointer (the byte number of the next
byte in the file to be read or to be written.)
 These member functions are:
seekg (seek get) for istream class – Moves get (i/p)
pointer to a specified location
Syntax: seekg(offset, refPosition);
Where offset is no. of bytes, file pointer is to be moved from
refPosition.
refPosition:
 ios::beg start of file
 ios::currCurrent position of pointer
 ios::end  End of file
seekp (seek put) for ostream class – Moves put pointer to a
specified location.
seekp(offset, refPosition);
Dr. Gaurav Gupta 29
Associate Professor (IT Deptt.)
Examples of moving a file pointer
 inFile.seekg(0) - repositions the file get pointer to the
beginning of the file
 inFile.seekg(n, ios::beg) - repositions the file get pointer to
the n-th byte of the file
 inFile.seekg(m, ios::end) -repositions the file get pointer to
the m-th byte from the end of file
 inFile.seekg(0, ios::end) - repositions the file get pointer to
the end of the file
 The same operations can be performed with <ostream>
member function - seekp.

Dr. Gaurav Gupta 30


Associate Professor (IT Deptt.)
Member functions tellg() and tellp()
 Member functions tellg and tellp are provided to return
the current locations of the get and put pointers,
respectively.
long location = inFile.tellg();
 To move the pointer relative to the current location use:
ios::cur
 inFile.seekg(n, ios::cur) - moves the file get pointer n
bytes forward from current position of pointer.

Dr. Gaurav Gupta 31


Associate Professor (IT Deptt.)
Sequential file-I/O operations (put() & get())
int main()
{
char str[100];
cin>>str;
int len=strlen(str);
fstream file;
file.open(“Try”,ios::in|ios::out);
for(int i=0;i<len;i++)
file.put(str[i]);
file.seekg(0); //Go to start
char ch;
while(file)
{
file.get(ch);
cout<<ch;
}
}
Dr. Gaurav Gupta 32
Associate Professor (IT Deptt.)
Sequential file - write() & read()
Used to handle data in binary form. Syntax:
• inFile.read((char*)&var,sizeof(var));
• outFile.write((char*)&var,sizeof(var));
main()
{
float arr[4]={1.2,2.3,3.4,4.5,5.6};
ofstream outfile;
outfile.open(“Try”);
outfile.write((char*)&arr,sizeof(arr));
outfile.close();
arr={0,0,0,0};
ifstream infile;
infile.open(“Try”);
infile.read((char*)&arr,sizeof(arr));
for(i=0;i<4;i++)
cout<<arr[i];
infile.close();
} Dr. Gaurav Gupta 33
Associate Professor (IT Deptt.)
Sequential file – Reading & Writing Class Object
Data members are written to disk file not the member function
class ABC file.open(“Try.DAT”, ios::in|ios::out);
{ cout<<“Enter Data: ”;
char name[50]; for(int i=0;i<5;i++) {
int roll; obj[i].GetData();
public: file.write((char*)&obj[i],sizeof(obj[i]));
void GetData() { }
cin>>name>>roll; } file.seekg(0);
void Display() { cout<<“Output : ”;
cout<<name<<roll; for(int i=0;i<5;i++) {
}}; file.read((char*)&obj[i],sizeof(obj[i]));
obj[i].Display();
main() }
{ file.close();
ABC obj[5]; }
fstream file;
Dr. Gaurav Gupta 34
Associate Professor (IT Deptt.)
Updating a sequential file
 Data that is formatted and written to a sequential file
cannot be modified easily without the risk of
destroying other data in the file.
 If we want to modify a record of data, the new data may
be longer than the old one and it could overwrite parts of
the record following it.

Dr. Gaurav Gupta 35


Associate Professor (IT Deptt.)
Problems with sequential files
 Sequential files are inappropriate for so-called “instant
access” applications in which a particular record of
information must be located immediately.
 These applications include banking systems, point-of-
sale systems, airline reservation systems, (or any data-
base system.)

Dr. Gaurav Gupta 36


Associate Professor (IT Deptt.)
Random access files
 Instant access is possible with random access files.

 Individual records of a random access file can be


accessed directly (and quickly) without searching many
other records.

Dr. Gaurav Gupta 37


Associate Professor (IT Deptt.)
<ostream> function write
 The <ostream> member function write outputs a fixed
number of bytes beginning at a specific location in
memory to the specific stream.
 When the stream is associated with a file, the data is
written beginning at the location in the file specified by
the “put” file pointer.
 The write function expects a first argument of type const
char *, the address of the object is converted to a const
char *. The second argument of write is an integer of type
size_t specifying the number of bytes to written. Thus the
sizeof( object).

Dr. Gaurav Gupta 38


Associate Professor (IT Deptt.)
<istream> function read

The <istream> function inputs a specified (by


sizeof(object)) number of bytes from the current position
of the specified stream into an object.

Dr. Gaurav Gupta 39


Associate Professor (IT Deptt.)
Operations on random access file
#include <iostream.h> inoutfile.seekg(0,ios::beg);
#include <iomanip.h> while(inoutfile.read((char*)&obj,
#include <fstream.h> sizeof(obj))) {
classs ABC obj.Display();
{ }
char name[20]; inoutfile.clear();
int roll;
public: //Adding Data
void GetData(); obj.GetData();
void Display(); inoutfile.write((char*)&obj,sizeof(obj));
};
main() //Display the appended file
{ inoutfile.seekg(0);
ABC obj; while(inoutfile.read((char*)&obj,sizeof(
fstream inoutfile; obj)) {
inoutfile.open(“Try.DAT”, ios::ate| obj.Display();
ios::in|ios::out|ios::binary); }

Dr. Gaurav Gupta 40


Associate Professor (IT Deptt.)
Operations on random access file
//Find no. of objects in the file inoutfile.seekp(location);
int last=inoutfile.tellg(); //current cout<<“Enter value for object : ”;
position of get pointer which obj.GetData();
will be last position
int n=last/sizeof(obj); //no. of inoutfile.write((char*)&obj,sizeof(obj));
objects //Display updated file
inoutfile.seekg(0);
//Modify details while(inoutfile.read((char*)&obj,sizeof(
cout<<“Enter object no. to be obj)) {
updated : ”; obj.Display();
int objNo; }
int location=(objNo-1) * inoutfile.close();
sizeof(obj); }
if(inoutfile.eof())
inoutfile.clear(); //To turnoff
eof flag

Dr. Gaurav Gupta 41


Associate Professor (IT Deptt.)
To be continued…

Dr. Gaurav Gupta 42


OBJECT ORIENTED
PROGRAMMING
(with C++)

Unit-4
Standard Template Library

Dr. Gaurav Gupta


Associate Professor (IT Deptt.) 1
Unit-IV
Standard C++ classes, using multiple inheritance,
persistant objects, streams and files, namespaces,
exception handling, generic classes, standard
template library: Library organization and
containers, standard containers, algorithm and
Function objects, iterators and allocators, strings,
streams, manipulators, user defined manipulators,
vectors, valarray, slice, generalized numeric
algorithm.

Dr. Gaurav Gupta


Associate Professor (IT Deptt.) 2
Standard Template Library(STL)
STL is a powerful set of C++ template classes to provide
general-purpose classes and functions with templates that
implement many popular and commonly used algorithms
and data structures like vectors, lists, queues, and stacks.
 STL provides a collection of classes to make C++
programming more efficient
 Algorithms, Containers, and Iterators
 Function objects, Allocators, and Adapters

Function Objects

Iterators
Containers Containers

Dr. Gaurav Gupta 3


Associate Professor (IT Deptt.)
Components of STL
 Containers - Generic class templates for storing
collection of data. Containers are used to manage
collections of objects of a certain kind. There are several
different types of containers like deque, list, vector, etc.
 Algorithms - Generic function templates for operating
on containers. Algorithms act on containers. They provide
the means by which you will perform initialization,
sorting, searching, and transforming of the contents of
containers.
 Iterators - Generalized ‘smart’ pointers that facilitate use
of containers. They provide an interface that is needed for
STL algorithms to operate on STL containers.
Dr. Gaurav Gupta 4
Associate Professor (IT Deptt.)
Containers
Three types of containers
- Sequence containers:
- linear data structures such as vectors and linked lists
 vector (dynamic table)
 dequeue (double ende queue, using dynamic table)
 list (double linked one)
 (arrays and strings not STL containers, but operable by STL
algorithms)
- Associative containers:
- non-linear containers such as hash tables
 set (using binary tree)
 multiset
 map, multimap
- Container adapters:
- constrained sequence containers such as stacks and
queues
Dr. Gaurav Gupta 5
Associate Professor (IT Deptt.)
Iterators
• Iterators are pointers to elements of first-class containers
 Type const_iterator defines an iterator to a container
element that cannot be modified
 Type iterator defines an iterator to a container element
that can be modified
 Used as arguments to algorithms
 Containers provide several iterators
 Begin, End, Reverse Begin, Reverse End
 5 categories – each has specific operations
 Input, Output, Forward, Bidirectional, Random

Dr. Gaurav Gupta 6


Associate Professor (IT Deptt.)
Algorithms
 Operate on containers using iterator interface
 generic, but not as fast as containers’ methods
 slow on some combinations of algorithm/container
 may operate on various containers at the same time
 4 categories
 Non-modifying
For each, Find, Count, Equal, Search, etc.
 Mutating
Copy, Generate, Reverse, Remove, Swap, etc.
 Sorting Related
Sort, Stable sort, Binary search, Merge, etc.
 Numeric
Accumulate, Inner product, Partial sum, Adjacent difference

Dr. Gaurav Gupta 7


Associate Professor (IT Deptt.)
Function Object as Algorithm Argument
 Used by some algorithms
 Applied to each element in input by For each
 Used to create new elements by Generate
 Predicates - Function Objects that return bool
 Unary and Binary predicates used to test equality
 Find If uses unary, Sort uses binary
 function objects are
 easily optimizable by compiler
 may have class member variables,internal state” passed by
the constructor argument
 we may have many function objects of the same class

Dr. Gaurav Gupta 8


Associate Professor (IT Deptt.)
Vector container
Provides an alternative to the built in array. A vector is self
grown. Use It instead of the built in array!
 Vector – similar to an array
 Vectors allow access to its elements by using an index in the
range from 0 to n-1 where n is the size of the vector
 Vector vs array
 Vector has operations that allow the collection to grow and
contract dynamically at the rear of the sequence
Syntax:
vector<of type>
Example :
vector<int> - vector of integers.
vector<string> - vector of strings.
vector<Shape> - vector of Shape objects where
Shape is a user defined class.
Dr. Gaurav Gupta 9
Associate Professor (IT Deptt.)
Vector container
Example :
#include <iostream> for(i = 0; i < 5; i++) {
#include <vector> cout << "value of vec [" << i << "] = " <<
using namespace std; vec[i] << endl;
int main() } // use iterator to access the values
{ // create a vector to store vector<int>::iterator v = vec.begin();
int vector<int> vec; while( v != vec.end())
int i; // display the original size of vec {
cout << "vector size = " << vec.size() << cout << "value of v = " << *v << endl;
endl; // push 5 values into the vector v++;
for(i = 0; i < 5; i++) { }
vec.push_back(i); } / return 0; }
/ display extended size of vec
cout << "extended vector size = " <<
vec.size() << endl; // access 5 values
from the vector

Dr. Gaurav Gupta 10


Associate Professor (IT Deptt.)
Strings
 In C, char * was used to represent a string.
 The C++ standard library provides a common
implementation of a string class abstraction named string.
 To use the string type simply include its header file.
#include <string>
string str = “some text”;
or
string str(“some text”);
other ways:
string s1(7,„a‟);
string s2 = s1;
Dr. Gaurav Gupta
Associate Professor (IT Deptt.)
String Operations
String Length: The length of string is returned by its
size() operation.
#include <string>
string str = “something”;
cout << “The size of “<< str << “is “ << str.size() <<
“characters.” << endl;

String concatenation: Concatenating one string to


another is done by the ‘+’ operator.
string str1 = “Here ”;
string str2 = “comes the sun”;
string concat_str = str1 + str2;

Dr. Gaurav Gupta


Associate Professor (IT Deptt.)
Valarray slice
A valarray slice is defined by a starting index, a size, and
a stride.
 The starting index (start) is the index of the first
element in the selection.
 The size (size) is the number of elements in the
selection.
 The stride (stride) is the span that separates the
elements selected.
Therefore, a slice with a stride higher than 1 does not
select contiguous elements in the valarray;
 For example, slice(3,4,5) selects the elements 3, 8, 13 and
18.

Dr. Gaurav Gupta


Associate Professor (IT Deptt.)
Valarray slice
Example:
#include <iostream> // std::cout
#include <cstddef> // std::size_t
#include <valarray> // std::valarray, std::slice
using namespace std;
int main () {
valarray<int> foo (12);
for (int i=0; i<12; ++i)
foo[i]=i;
valarray<int> bar = foo[slice(2,3,4)];
cout << "slice(2,3,4):"; Output:
for (size_t n=0; n<bar.size(); n++) slice(2,3,4): 2 6 10
cout << ' ' << bar[n]<<‘\n’;
return 0;
}
Dr. Gaurav Gupta
Associate Professor (IT Deptt.)
Generalized Numeric Algorithm
Some of the Numeric algorithms in STL are:
 iota Method: assigns all the successive elements in range
[first, last] as an incremented value of the element itself.
Syntax is:
 iota(iterator first, iterator last, int value ).
 accumulate Method: performs operation op on all the
element in the range [first, last] and stores the result into
the container result. Syntax is:
 accumulate(iterator first, iterator last, object_type result,
binaryoperator op)
 partial_sum Method: assigns every element in the range
starting from iterator result of the operation op on the
successive range in [first, last]. Syntax is:
 partial_sum(iterator first, iterator last, iterator result,
binary_operation op)
Dr. Gaurav Gupta
Associate Professor (IT Deptt.)
iota method

#include<iostream>
#include<numeric>
#include<vector>
using namespace std;
int main()
{
vector<int> v(10); /* now vector v is : 0,0,0,0,0,0,0,0,0,0 */
iota(v.begin(), v.end(), 10 ); /* now the vector v is
10,11,12,13,14,15,16,17,18,19 */
}

Dr. Gaurav Gupta


Associate Professor (IT Deptt.)
Accumulate method
#include<iostream>
#include<numeric>
#include<vector> accumulate(v.begin(), v.end(), result) ;
using namespace std; /* as no operator is specified,
accumulate add all the elements
int myoperator(int a, int b )
between v.begin() and v.end() and store
{ the sum in result */
return a*b; /* now result = 45 */
}
int main() { accumulate(v.begin(), v.end(), result,
vector<int> v; myoperator) ;
for(int i = 0 ; i < 10; i++) { /* applies myoperator on all the
v.push_back(i); elements in the range v.begin() and
} v.end() and store them in result */
/* now vector v is : /* now result = 9! */
}
0,1,2,3,4,5,6,7,8,9 */
int result;
Dr. Gaurav Gupta
Associate Professor (IT Deptt.)
partial_sum method
#include<iostream>
#include<numeric>
#include<vector>
using namespace std;
int myoperator(int a, int b) {
return a*b;
}
int main() {
int a[] = {1,2,3,4,5};
vector<int> v (a,a+5);
vector<int> v2; /* vector v is 1,2,3,4,5 */
v2.resize(v.size());
partial_sum(v.begin(), v.end(), v2.begin());
/* now v2 is : 1,3,6,10,15 */
/* sum of the successive range in v.begin() and v.end() */
partial_sum(v.begin(), v.end(), v2.begin(), myoperator);
/* now v2 is : 1,2,6,24,120 */
}
Dr. Gaurav Gupta
Associate Professor (IT Deptt.)
End of Unit-IV…
Syllabus Finished…

Dr. Gaurav Gupta 19

You might also like