You are on page 1of 108

1

OBJECT ORIENTED PROGRAMMING USING C++


1.1 The Evolution of C++:
Computer languages have come a long way since the 1940s. Back then, scientists
punched instructions in to mammoth, room-sied computer systems. !hese instructions were
long series o" eroes and ones. !hese machine language instructions are called the frst
generation o" computer languages.
!he 19#0s saw the emergence o" the second generation computer languages-
assembly language-easier to write than machine language $ut still e%tremely complicated "or
a lay person. &owever, the computer could still understand only machine language.
!here"ore, the assem$ler so"tware was developed to translate the code written in assem$ly
language into machine language.
'n 19(), *artin +ichard developed a language called B,C- "or writing operating
systems. .n operating system is a set o" programs that manages the resources o" a computer
and its interactions with users.
!he era o" the third generation o" computer languages had arrived. 'n 19)0s /en
!hompson modi0ed B,C- to create a new language called B. working "or Bell -a$oratories,
!hompson teamed up with 1ennis +itchie and wrote an early version o" the 2ni% operating
system "or a 13C ,1,-) computer.
1ennis +itchie was working on a pro4ect to "urther develop the 2ni% operating system.
&e wanted a low-language, like the assem$ly language, the could control hardware e5ciently.
.t the same time, he wanted the language to provide the "eatures o" a high level language,
that is, it should $e a$le to run on di6erent types o" hardware. B had per"ormance draw$acks,
so in 19)7, he rewrote B and called in C.
!here"ore, C is categoried as $oth a second and third generation language. !hompson
and +itchie rewrote the 2ni% operating system in C. 'n the years that "ollowed, C was widely
accepted and used over di6erent hardware plat"orms. 'n 1989, the American National
Standards Institute(.9:';, along with the 'nternational :tandards <rganiation =':<;, approved
a machine independent and standard version o" C.
'n the early 1980s , B!"ne St"ou#t"u$ working "or Bell -a$s developed the C>>
language. 'n his own words , ? C>> was designed primal so that my "riends an ' would not
have to program in assem$ly, C, or various modern high-level languages. 'ts main purpose
was to make writing "ood programs easier and more pleasant "or the individual programmer@.
=B4arne :troustup The C++ Programming Language !hird 3dition. +eading, *.A .ddition
Besley ,u$lishing Company 199);. C>> was originally known as CC with classes as two
languages contri$uted to its design. C which provided low-level "eatures, and simula!" which
provided the class concept.
!he C>> language is a superset o" C. -ike the C language, C>> is compact and can $e
used "or system programming. 't can use e%isting C so"tware libraries# =-i$raries are
collections o" programs that you can reuse in your program.; C>> has o$4ect-oriented
programming =<<,; capa$ilities similar to an earlier computer language called :imula(). C>
> is called a hy$rid language $ecause it can $e used $oth as a procedural language like C and
as an o$4ect-oriented language like :imula(), other o$4ect-oriented languages include
Smalltal$ and Ada#
'n 1990s, the .9:'D':< committee $egan working on a standard version o" the C>>
language. By Eune 1998,the committee had approved the Final 1ra"t 'nternational :tandard "or
C>>. 't was released in the "orm o" a document. 't e%tended the language to include
e%ceptions, templates, and the Standard Template Library = :!-;.
2
Soft%!"e Evolution:
!he so"tware evolution has had distinct phases or ?layers@ o" growth. !hese layers were
$uilt up one $y one over the last 0ve decades as shown in 0gure. 3ach layer representing an
improvement over the previous one.
1, 0
Machine language
Assembly language
Procedure-oriented
Object oriented programming
Fig. -ayers o" computer so"tware
Object-Oriented Programming =<<,; is an approach program organiation and
development that attri$utes to eliminate some o" pit"alls o" conventional programming
methods $y incorporating the $est o" structured programming "eatures with several power"ul
new concepts.
1.& P"o'e(u"e ) O"iente( P"o*"!++in*:
!he high level languages such as C<B<-, F<+!+.9 and C are commonly known as
procedure-oriented programming ,POP-. 'n the procedure-oriented approach, the
pro$lem is viewed as a seGuence o" things and a num$er "unctions are written to accomplish
these tasks. !he primary "ocus is on "unctions.
P"o'e(u"!l P"o*"!++in* Mo(elA 3ach pro$lem is divided into smaller pro$lems and solved
using speci0ed modules that act on data.
*ain ,rogram
Function -1 Function -7 Function -H
Function -4 Function -#
Function -( Function -) Function -8
Fig I :tructure o" procedural-oriented programs
3
'n a multi-"unction program, many important data items are
placed as $y all the "unctions. 3ach "unction may have its own
local data. Fig "unctions in a procedure-oriented program.
global so that they may $e
accessed shows the
relationship o" data and
Jlo$al data Jlo$al data
Function-1 Function-7 Function-H
-ocal data -ocal data -ocal data
Fig- +elationship o" data and "unctions in procedural programming
Jlo$al data are more vulnera$le to an inadvertent change $y a "unction. 'n a large
program it is very di5cult to identi"y what data is used $y which "unction.
.nother serious draw$ack with the procedural approach is that it does not model real
world pro$lems very well. !his is $ecause "unctions are action-oriented and do not really
corresponding to the elements o" the pro$lem.
:ome characteristics e%hi$ited $y procedure-oriented programming areA
1.. O/e't0O"iente( P"o*"!++in* P!"!(i*+:
!he ma4or motivating "actor in the invention o" o$4ect-oriented approach is to remove
some o" the Kaws encountered in the procedural approach. <<, treats data as a critical
element in the program development and does not allow it to Kow "reely around the system. 't
ties data more closely to the "unctions that operate on it, and protects it "rom accidental
modi0cation "rom outside "unctions.
<<, allows decomposition o" a pro$lem into a num$er o" entities called objects and
then $uilds data and "unctions around these o$4ects. !he organiation o" data and "unctions in
o$4ect-oriented program is shown in 0gure.
1ata
<$4ect .
1ata
<$4ect
B
Functions Functions
Functions
<$4ect
C
1ata
Figure - <rganiation o" data and "unctions in
E+$h!#i# i# on (oin* thin*# ,!l*o"ith+#-.
1!"*e $"o*"!+# !"e (ivi(e( into #+!lle" $"o*"!+# 2no%n
!# fun'tion#. Mo#t of the fun'tion# #h!"e *lo/!l (!t!.
D!t! +ove o$enl3 !"oun( the #3#te+ f"o+ fun'tion
to fun'tion. 4un'tion# t"!n#fo"+ (!t! f"o+ one
fo"+ to !nothe".
E+$lo3# top-down !$$"o!'h in $"o*"!+ (e#i*n.
<<,

!he data o" an o$4ect can $e accessed only $y the "unctions associated with the o$4ect.
&owever, "unctions o" one o$4ect can access the "unctions o" other o$4ects.
:ome o" the striking "eatures o" o$4ect-oriented programming areA
5O/e't0o"iente( $"o*"!++in* !# an approach that provides a way of modularizing
programs by creating partitioned memory area for both data and functions that
can be used as template for creating copies of such modules on demand. *emory
partitions are independentL the o$4ects can $e used in a variety o" di6erent programs without
modi0cations.
O/e't o"iente( $"o*"!++in* +o(el: 't perceived the entire so"tware system as a
collections o" o$4ects which contain attri$utes and $ehaviors.
BASICS CONCEPTS O4 OBJECT )ORIENTED PROGRAMMING
So+
e
of the 'on'e$t# u#e( e6ten#ivel3 in o/e't0o"iente(
$"o*"!++in*. !hese includeA
<$4ects
Classes
1ata a$straction and encapsulation
'nheritance
,olymorphism
1ynamic $inding
*essage passing
O/e't:

O/e't i# ! t"i!n*le of entit3 th!t +!3 /e e6hi/itin* #o+e %ell0(e7ne(


/eh!vio". ,O"- O/e't i# !n in#t!n'e of Cl!## ,o"- Eve"3thin* i# !n o/e't
<$4ects are the $asic run-time entities in an o$4ect-oriented system. !hey may
represent a person, a place, a $ank account, a ta$le o" data or any item the program has to
handle. !hey may $e represents user-de0ned data such as vectors, time and lists.
Bhen a program e%ecuted, the o$4ect interact $y sending messages to one another.
3ach o$4ect contain data, and code to manipulate the data. Fig shows two notations that are
popularly used in o$4ect-oriented analysis and design.
Object ! "#$%&'# "#$%&'#
%A#A
#otal
'ame
%ate-o(-)irth
A*erage
Mar+s
F$',#-O'"
%isplay
Fig I !wo ways o" representing an o$4ect
Cl!##e#:

Cl!## i# ! #et of !tt"i/ute# !n( /eh!vio" #h!"e( /3 #i+il!" o/e't# ,o"- in


#i+$le %!3 'olle'tion of o/e't# of #i+il!" t3$e i# '!lle( ! Cl!##.
E+$h!#i# i# on (!t! "!the" th!n
$"o'e(u"e P"o*"!+# !"e (ivi(e( into %h!t
!"e 2no%n !# o/e't
D!t! #t"u'tu"e# !"e (e#i*ne( #u'h th!t the3 'h!"!'te"i8e the o/e't.
4un'tion# th!t o$e"!te on the (!t! of on o/e't !"e tie( to*ethe" in
the (!t! #t"u'tu"e. D!t! i# hi((en !n( '!nnot /e !''e##e( /3
e6te"n!l fun'tion#.
Ne% (!t! !n( fun'tion# '!n /e e!#il3 !((e(
%heneve" ne'e##!"3. 4ollo%# bottom-up !$$"o!'h in
$"o*"!+ (e#i*n.
!he entire set o" data and code o" an o$4ect can $e made a user-de0ned data type with
the help o" a class. O/e't# !"e v!"i!/le of the t3$e class. <nce a class has $een de0ned,
we can create any num$er o" o$4ects $elonging to that class.
.
'" f"uit has $een de0ned as a 'l!##, then the statement.
f"uit appleL
will create an o$4ect !$$le $elonging to the class f"uit.
D!t!

A/#t"!'tion !n( En'!$#ul!tion:


.$straction re"ers to the act o" representing essential "eatures without including the
$ackground details or e%planations. Classes use the concept o" a$straction and are
de0ned as a list o" a$stract attributes such as sie, weight and cost, and %unctions to
operate on these attri$utes.
:ince the classes use the concept o" data a$straction, they are known as Abstract
Data Types =.1!;.
!he attri$utes are sometimes called data members $ecause they hold in"ormation. !he
"unctions that operate on these data are sometimes called methods or member
functions.
En'!$#ul!tion: The %"!$$in* u$ of (!t! !n( fun'tion into ! #in*le unit ,'!lle(
'l!##- i# 2no%n !# encapsulation. The (!t! i# not !''e##i/le to the out#i(e %o"l(9
!n( onl3 tho#e fun'tion# %hi'h !"e
%"!$$e( in the 'l!## '!n !''e## it.
!his instruction o" the data "rom direct access $y the program is called data hiding or information
hiding.
A/#t"!'tion fo'u#e# on the e##enti!l 'h!"!'te"i#ti'# of o/e't#
Inhe"it!n'e:

nheritance i# the $"o'e## /3 %hi'h o/e't of one 'l!## !':ui"e the $"o$e"tie#
of o/e't# of
't supports the concept o" hierarchical classifcation. For e%ample, the $ird Cro$in is a
part o" the class CKying $ird which is again a part o" the class C$ird. !he principle
$ehind this sort o" division is that
each derived class shares common characteristics with the class "rom which it is derived as
illustrated in
0g.
!nothe"'l!##.C"e!te ! ne% 'l!## (e"ive( f"o+ the ol( 'l!##.
Bird
.ttri$ute
Features
-ay eggs
Flying Bird 9on-Flying
Bird
.ttri$ute
MMMM .ttri$ute
MMMM MMMM
+o$in :wallow ,enguin /iwi
.ttri$ute .ttri$ute .ttri$ute .ttri$ute
MMMM MMMM MMMM MMMM
MMMM MMMM MMMM MMMM
Fig- property inheritance
'n <<,, the concept o" inheritance provides the idea o" reusability. !his means that we
can add additional "eatures to an e%isting class without modi"ying it.
!his is possi$le $y deriving new class "rom the e%isting one. !he new class will have the
com$ined "eatures o" $oth the class.
/
Pol3+o"$hi#+:

Polymorphism i# !nothe" i+$o"t!nt OOP 'on'e$t. Pol3+o"$hi#+9 ! G"ee2


te"+9 +e!n# the !/ilit3 to t!2e +o"e th!n one fo"+. An o$e"!tion +!3 e6hi/it
(i;e"ent /eh!vio"# in (i;e"ent
!he $ehavior depends upon the types o" data used in the operation.
For e%ample, consider the operation o" addition. For two num$ers, the operation will
generate a sum. '" the operands are string, then the operation would produce a third
string $y concatenation.
!his process o" making an operator to e%hi$it di6erent $ehaviors in di6erent instances
is known as operator overloading.
2sing a single "unction name to per"orm di6erent types o" tasks is known as function overloading!
in#t!n'e#.

Figure illustrates that a single "unction name can $e used to handle di6erent num$er
and di6erent types o" arguments.
:hape
1raw
Circle o$4ect Bo% o$4ect !riangle o$4ect
1raw =circle; 1raw =$o%; 1raw =triangle;
Fig. I ,olymorphism
,olymorphism plays an important role in allowing o$4ect having di6erent internal
structures to share the same e%ternal inter"ace. !his means that a general class o" operation
may accessed in the same manner even though speci0c actions associated with each
operation may di6er. ,olymorphism is e%tensively used in implementing inheritance.
Binding re"ers to the linking o" a procedure call to the code to $e e%ecuted in response
to the call.
Dynamic "inding ,!l#o 2no%n !# l!te /in(in*- +e!n# th!t the 'o(e !##o'i!te(
%ith ! *iven $"o'e(u"e '!ll i# not 2no%n until the ti+e of the '!ll !t "un0ti+e.
It i# !##o'i!te( %ith $ol3+o"$hi#+ !n( inhe"it!n'e.
. "unction call associated with a polymorphic re"erence depends on the dynamic type o" that
re"erence.
D3n!+i'Bin(in*:
Consider the procedure ?draw@ in a$ove 0gure $y inheritanceL every o$4ect will have
this procedure. 'ts algorithms are, however, uniGue to each o$4ect and so the draw procedure
will $e rede0ned in each class that de0nes the o$4ect.
.n o$4ect-oriented program consists o" a set o" o$4ects that communicate with each
other. !he process o" programming in an o$4ect-oriented language, there"ore, involves
the "ollowing $asic stepsA
i. Creating classes that de0ne o$4ects and their $ehavior.
ii. Creating o$4ects "rom class de0nitions, and
iii. 3sta$lishing communication among o$4ects.
A +e##!*e fo" !n o/e't i# ! "e:ue#t fo" e6e'ution of ! $"o'e(u"e9 !n( the"efo"e %ill
invo2e ! fun'tion ,$"o'e(u"e- in the "e'eivin* o/e't th!t *ene"!te# the (e#i"e(
"e#ult.
Me##!*eP!##in*:

0
&essage passing involves speci"ying the name o" the o$4ect, the name o" the "unction
=message; and
the in"ormation to $e sent. 3%ampleA
3mployee.salary
=name;L
<$4ect in"ormation
*essage
<$4ects have a li"e cycle. !hey can $e created and destroyed. Communication with an
o$4ect is "easi$le as long as it is alive.
Bene7t# of OOP#:
<<, o6ers several $ene0ts to $oth the program designer and user.
Th"ou*h inhe"it!n'e9 %e '!n eli+in!te "e(un(!nt 'o(e !n( e6ten( the u#e
of e6i#tin* 'l!##e#.
The $"in'i$le of (!t! hi(in* hel$# the $"o*"!++e" to /uil( #e'u"e
$"o*"!+# th!t '!nnot /e
inv!(e( /3 'o(e on othe" $!"t# of the $"o*"!+.
It i# $o##i/le to h!ve +ulti$le in#t!n'e# of on o/e't to 'o0e6i#t %ithout
!n3 inte"fe"en'e.
It i# $o##i/le to +!$ o/e't# in the $"o/le+ (o+!in to tho#e o/e't# in the
$"o*"!+.
It i# e!#3 to $!"tition the %o"2 in ! $"oe't /!#e( on o/e't#.
O/e't0o"iente( #3#te+# '!n /e e!#il3 u$*"!(e( f"o+ #+!ll to l!"*e
#3#te+#.
Me##!*e $!##in* te'hni:ue# fo" 'o++uni'!tion /et%een o/e't# +!2e#
the inte"f!'e
(e#'"i$tion# %ith e6te"n!l #3#te+# +u'h
#i+$le". Soft%!"e 'o+$le6it3 '!n /e
e!#il3 +!n!*e(.
A$$li'!tion# of OOP:
.pplications o" <<, are $eginning to gain importance in many areas. !he most popular
application o" o$4ect-oriented programming, up to now, has $een in the area o" user inter"ace
design such as windows.
<in(o%# !"e (evelo$e( u#in* OOP te'hni:ue#. OOP i# #i+$lif3in* the 'o+$le6
$"o/le+.
!he
other areas "or application o" <<, includesA
Re!l0ti+e #3#te+#
Si+ul!tion !n( +o(elin*
O/e't0o"iente( (!t!/!#e#
=3$e"te6t9 h3$e"+e(i! !n( e6$e"te6t
AI !n( e6$e"t #3#te+#
Neu"!l net%o"2# !n( $!"!llel
$"o*"!++in*
De'i#ion #u$$o"t !n( o>'e !uto+!tion
#3#te+#
CIM?CAM?CAD #3#te+#.
O/e't0O"iente( 1!n*u!*e#:
<$4ect-oriented programming is not the right o" any particular language. -ike
structured programming, <<, concepts can $e implemented using languages such as C and
,ascal. . language that is specially designed to support the <<, concepts makes it easier to
implement them.
!he languages should support several o" the <<, concepts to claim that they are
o$4ect-oriented.
1epending upon the "eatures they support, they can $e classi0ed into the "ollowing two
categoriesA
<$4ect-$ased programming -anguages

<$4ect-oriented programming -anguages.


Object-based programming i# the #t3le of $"o*"!++in* th!t $"i+!"il3
#u$$o"t# en'!$#ul!tion
!n( o/e't i(entit3. M!o" fe!tu"e# th!t !"e "e:ui"e( fo" o/e't0/!#e $"o*"!++in* !"e:
1ata encapsulation
1ata hiding and access mechanisms
.utomatic initialiation and clear-up o" o$4ects
<perator overloading
1
-anguages that support programming with o$4ects are said to $e o$4ect-$ased
programming languages. !hey do not support inheritance and dynamic $inding. .da is a
typical o$4ect-$ased programming

language.
Object-oriented programming in'o"$o"!te# !ll of o/e't0/!#e( $"o*"!++in*
fe!tu"e# !lon* %ith t%o !((ition!l fe!tu"e#9 n!+el39 inhe"it!n'e !n( (3n!+i'
/in(in*. It@# #i+$l3
<$4ect-$ased "eatures > inheritance > dynamic $inding.
-anguages that support these "eatures include C>> , :malltalk and o$4ect ,ascal and
4ava. !here are a large num$er o" o$4ect-$ased and o$4ect-oriented programming languages.
C++ STREAMS
. stream is a seGuence o" $ytes. !he source stream that provides data to the program
is called the input stream and the destination stream that receives output "rom the program is
called the output stream. . program e%tracts the $ytes "rom and input stream and inserts
$ytes into an output stream.
'nput :tream
'nput
3%traction
"rom
1evice
input stream
,rogram
<utput :tream
'nsertion into <utput
1evice
output
stream
Fig. 1ata :treams
C++ STREAM C1ASSES
!he C>> 'D< system contains a hierarchy o" classes that are used to de0ne various streams to
deal with $oth the console and disk 0les. !hese classes are called stream classes.
io#
$ointe"
i#t"e!
+
#t"e!+/u
f o#t"e!+
*et, - $ut, -
tell*,
- tell$, -
"e!(,
- %"ite, -
ove"lo!(AA ove"lo!(BB
in$u
t out$ut
io#t"e!+
i#t"e!+C%ith
!##i*n
io#t"e!+C%ith
!##i*n
o#t"e!+C%ith
!##i*n
Fig. :tream classes "or console 'D< operations
Cl!## n!+e Content#
ios A Contains $asic "acilities that are used $y all other input and output classes
istream A 1eclares input "unctions. 'nherits the properties o" io#
ostream A 1eclares output "unctions. 'nherits the properties o" io#
iostream A
Contains all the input and output "unctions. 'nherits ios, istream and
ostream classes.
stream$
u" A ,rovides an inter"ace to physical devices through $u6ers.
2
UN4ORMATTED I?O OPERATIONS:
!he "ollowing "unctions are used to implement the un"ormatted console 'D< operations.
!hey are the mem$er "unctions o" the istream and ostream classes. :o, we should use the cin
and cout o$4ects with
the
"unctions.
In$ut fun'tion# ,i#t"e!+ 'l!##-
Out$ut fun'tion# ,o#t"e!+
'l!##-
overload operator NN, overload operator OO,
get= ;
, put= ;,
getline= ; write= ;
Ove"lo!( o$e"!to"AA : 2sed to get input "rom the key$oard.
S3nt!6 :
'in AA v!"1 AA v!"& AA D
AA v!"nE
E6!+$le : 'in AA 6 AA 3 AA 8E
*et, - : !his "unction is used to get input "rom the key$oard. Be can use this "unction in two
ways.
1. *et,'h!"- &. *et,voi(-
S3nt!6 :
'in.*et,v!"Cn!+
e-E S3nt!6 :
v!"Cn!+e F
'in.*et, -E
E6!+$le : 'h!" 'E E6!+$le : 'h!" 'E
'in.*et,'-E ' F 'in.*et, -E
*etline, - : !his "unction is used to get a line o" te%t as
input.
S3nt!6 : 'in.*etline,v!"Cn!+e9 #i8e-E
E6!+$le : 'h!" n!+eG1HIE
'in.*etline,n!+e
9 1H-E
Ove"lo!( o$e"!to" BB: !his "unction is used to display the output on P12.
S3nt!6 :
'out BB v!"1BB v!"&BB D
BB v!"nE
E6!+$le :
'outBB 6BB 3BBJTh!n2
3ouJE
$ut, - : !his "unction is used to display a single character as output on P12.
S3nt!6 :
'out.$ut,v!"Cn!
+e-E
E6!+$le : 'h!" ' F K8@E
'out.$ut,'-E
%"ite, - : !his "unction is used to display a line o" te%t as output on the screen.
S3nt!6 :
'out.%"ite,v!"Cn!+e9
#i8e-E
E6!+$le :
'h!" n!+eG1HI F 5Th!n2
LouJE
'out.%"ite,n!+e9 1H-E
4ORMATTED CONSO1E I?O OPERATIONS
Formatted console 'D< operations are used to "ormat the output o" a program. !hese
"unctions are the mem$er "unctions o" io# class. :o, we should use the 'out o$4ect "or using
these "unctions.
i. width= ;
ii. prescision= ;
iii. 0ll= ;
iv. set"= ;
v. unset"= ;
%i(th, -: 2sed to speci"y the reGuired 0eld sie "or displaying an output value.
S3nt!6 : 'out.%i(th,#i8e-E
& M
E6!+$le : int ! F &ME
'out.%i(th,N-E
'outBB!E
$"e'i#ion, - : 2sed to speci"y the num$er o" digits to $e displayed a"ter the decimal point o"
a Koat value.
S3nt!6 : 'out.$"e'i#ion, #i8e-E
N M & & . 1 &
E6!+$le : int ! F NM&&.1&.NMOE
'out.$"e'i#ion,&-E
'outBB!E
10
7ll, - : 2sed to speci"y a character that is used to 0ll the unused portion o" a 0eld.
S3nt!6 : 'out.7ll, !"* -E
P P Q M H
E6!+$le : int ! F QMHE
'out.%i(th,M-E
'out.7ll,KP@-E
'outBB!E
#etf, - : 2sed to speci"y "ormat Kags that can control the "orm o" output display =such as
le"t-4usti0cation and right-4usti0cation;
Format reGuired Flag =arg1; Bit-0eld =arg7;
-e"t-4usti0ed output iosAAle"t iosAAad4ust0eld
+ight-4usti0ed output iosAAright iosAAad4ust0eld
,adding a"ter sign or
$ase iosAAinternal iosAAad4ust0eld
:cienti0c notation iosAAscienti0c iosAAKoat0eld
Fi%ed point notation iosAA0%ed iosAAKoat0eld
1ecimal $ase iosAAdoc iosAA$ase0eld
<ctal $ase iosAAoct iosAA$ase0eld
&e%adecimal $ase iosAAhe% iosAA$ase0eld
S3nt!6 : 'out.#etf, !"*19 !"*& -E
P R G C + +
E6!+$le : 'h!" !GQI F 5PRGC++JE
'out.#etf,io#::left9
io#::!(u#t7el(-E
'out.%i(th,1H-E
'outBB!E
un#etf, - : !his "unction is used unset the Kags and $it 0eld groups using set"= ; "unction.
4l!*# th!t (o not h!ve /it 7el(# :
!he set"= ; "unction can $e used with the "ollowing Kags as a single arguments to achieve
the reGuired output.
Flag *eaning
iosAAshow$ase
2se $ase indicator on
output
iosAAshowpos
,rint > $e"ore positive
num$ers
iosAAshowpoint
:how trailing decimal point and
eroes
iosAAuppercase
2se uppercase letters "or he%
output
iosAAskipus :kip white space on input
iosAAunit$u"
iosAAFlush all streams a"ter
insertion
iosAAstdio
iosAAFlush stdout and stderr a"ter
insertion
E6!+$le : 'out.#etf,io#::#ho%$oint-E
Out$u
t
'out.#etf,io#::#ho%$o#-E + & Q M . M H H
'out.$"e'i#ion
,.-E
'out.#etf,io#::76e(9
io#::Ro!t7el(-E
'out.#etf,io#::inte"n!l9
io#::!(u#t7el(-E
'out.%i(th,1H-E
'out BB &QM.M BB 5SnJE
M!ni$ul!to"# !n( U#e" De7ne( M!ni$ul!to"#:
*anipulators are used to "ormat the output. C>> has provided some prede0ned and user
de0ned manipulators. !here are num$er o" prede0ned manipulators present in the header 0le
Ciomanip.h. !wo or more manipulators can $e used as a chain in one statement as shown
$elowA
cout OO manip1 OO manip7 OO manipH
OO itemL cout OO manip1 OO item1 OO
manip7 OO item7L
11
*anipulators and their meanings
#et
%
,-
+!ni$ul!to":
0
!akes integer type o" varia$le as its parameter. !he parameter speci0es the width o"
the column.
E6!+$le: 1. coutOO 17HOOendlL Out$ut:
7. coutOO setw =H; OO 10L 17H
10
,- +!ni$ul!to":
C>> displays values o" Koat and dou$le type with si% digits $y de"ault a"ter decimal point. By
using the setprecision =; manipulator we can pass num$er o" digits we want to display
a"ter
#et$"e'i#ion

decimal point.
E6!+$le: 1. coutOOsetprecision=H;L Out$ut:
7. coutOO sGrt =H; OO endlL
1.)H7 =the value o" T. i#
1.Q.&HMHUHQMOUV;
#et7ll ,-
+!ni$ul!to":
!he main task o" set0ll =; manipulator is to 0ll the e%tra spaces le"t in the output
o" setw=;
manipulator with characters.
E6!+$le: 1.
coutOOset0ll=CQ
; Out$ut:
7.
coutOOsetw =#;
OO 10L QQQ10QQ7#)
H.
coutOOsetw =#;
OO
7#)OOendl
L
,- +!ni$ul!to":
!here are two important parameter setiosKags =; takes. !hey are iosAAshowpos and iosAAshowpoint.
Bhen iosAAshowpos is passed as parameter to setiosKags =; than a positive sign is pre0%ed to
the
#etio#R!*#

output.
E6!+$leA 1. coutOOsetiosKags=iosAAshowpos; OO 70L Out$ut: >70
Bhen iosAAshowpoint is passed as a parameter than it "ollows the setprecision parameter
=;.
E6!+$leA 1. coutOO setprecision=H;L
Out$u
t:
7. coutOO1.) OOendlL 1.)
H.
coutOOsetiosKags
=iosAAshowpoint; 1.)00
4. coutOO1.)OOendlL
"e#etio#R!*# ,- +!ni$ul!to":
!his manipulator cancels the setiosKags parameter. !his manipulator resets again to
setiosKags =; manipulator.
E6!+$le: 1. coutOO setprecision =H;OO1.)OOsetiosKags=iosAAshowpoint;OO1.)OOendlL
7. coutOOresetiosKags=iosAAshowpoint;OO1.)OOendlL
Out$ut: 1.)
1.)0
0
1.)
12
U#e
" (e7ne( +!ni$ul!to"#:
!he manipulators de0ned $y the users are called as user de0ned
manipulators.
:ynta% A o#t"e!+ W +!ni$ul!to",o#t"e!+ W out$ut-
X
??#t!te+en
t#?? "etu"n
out$utE
Y
Calling the user de0ned manipulators A
'out BB n!+e of the +!ni$ul!to" BB li#t to $"intE
3%ampleA o#t"e!+ W unit ,o#t"e!+ W out$ut-
X
out$ut BB 5in'he#JE
"etu"n out$utE
Y
CallingA 'out BB .O BB unitE
<utputA .O in'he#.
Example Program using setw and endl manipulators
3include4iostream5
3include4iomanip5 66 (or set7
int main89
:
int basic ; 2.0, allo7ance;2., total;10.<
cout44set7810944=)asic=44set7810944basic44endl<
cout44set7810944=Allo7ance=44set7810944allo7ance44endl<
cout44set7810944=#otal=44set7810944total44endl<
return 0<
>
Output o( this program is gi*en belo7?
)asic 2.0
Allo7ance 2.
#otal 10.
13
INTRODUCTION TO C++
C>> is an o$4ect-oriented programming language. 'nitially named CC with classes, C>>
was developed $y B4arne :troustrup at .!R ! Bell -a$oratories in *urray &ill, 9ew Eersey,
2:., in the early eighties. 'n 198H, the name=?C with classes@; was changed to C>>. !he idea
o" C>> comes "rom the C increment operator >>, there$y suggesting that C>> is an
incremented version o" C.
C>> is a superset o" C. !he three most important "acilities that C>> adds on to C are
classes, inheritance, "unction overloading, and operator overloading. !hese "eatures ena$le us
to create a$stract data types, inherit properties "rom e%isting data types and support
polymorphism, thus making C>> a truly o$4ect- oriented language.
!he addition o" new "eatures has trans"ormed C "rom a language that to one that
provides $ottom-up, o$4ect-oriented design.
A$$li'!tion# of C++:
C>> is a versatile language "or handling very large programs. 't is suita$le "or virtually
any programming task including development o" editors, compilers, data$ases,
communication systems and any comple% real-li"e application systems.
:ince C>> allows us to create hierarchy-related o$4ects, we can $uild special o$4ect
oriented li$raries
which can $e used later $y many programmers.
Bhile C>> is a$le to map the real-world pro$lem properly, the C part o" C>> gives the
language the a$ility to get close to the machine-level details.
C>> programs are easily maintaina$le and e%panda$le. Bhen a new "eature needs to
$e implemented, it is very easy to add to the e%isting structure o" an o$4ect.
Si+$le C++ P"o*"!+:
S includeOiostreamN DD include header 0le
int main=;
T
coutOO@ C>> is $etter than C.Un@L DD C>> statement
return 0L
V DD end o" e%ample
P"o*"!+ 4e!tu"e#:
-ike C, the C>> program is a collection o" "unctions. !he a$ove e%ample contains only
one "unction, +!in,-. 3%ecution $egin at main=;. 3very C>> program must have a +!in,-.
C>> is a "ree-"orm language, the C>> statements terminate with semicolons.
Co++ent#:
C>> introduces a new comment sym$ol DD =dou$le slash;. . comment may start
anywhere in the line, and whatever "ollows till the end o" the line is ignored. !here is no
closing sym$ol.
!he dou$le slash comment is $asically a single line comment. *ulti line comments can
$e written "ollowsA
/ this is an e%ample 0le
/ C>> program to illustrate
/ some o" its "eature
!he C comment sym$ol DQ, QD are still valid are more suita$le "or multi line comments.
!he "ollowing command is allowed.
DQ this is an e%ample o"
C>> program to illustrates
:ome o" its "eatures
QD
1
!he output statement 'out BB 5C++ i# /ette" th!n C.JE
causes the string in Guotation marks to $e displayed on the screen. !his statement introduces
two new C>> "eatures, 'out and BB. !he identi0er cout=pronounced as CC out; is a
prede0ned o$4ect that represents the standard output stream in C>>.
!he operator OO is called the insertion or put to operator. 't inserts =or sends; the
content o" the varia$le on its to the rights o" the o$4ect on its le"t =0gure;.
,out 44 @,AA=
<$4ect insertion operator varia$le
FigureA <utput using insertion operator
!he operator OO is the $it-wise le"t-shi"t operator and it can still $e used "or this purpose. !his
is an e%ample o" how one operator can $e used "or di6erent purposes, depending on the
conte%t. !his concept is known as operator overloading.
!he statement 'in AA nu+/e"1E
In$ut o$e"!to":
Out$ut O$e"!to":
!he operator NN is known as e#traction or get from operator. 't e%tracts =or takes; the
value "orm the key$oard and assign it to the varia$le on its right=0gure;.
<$4ect 3%traction <perator Paria$le
,in 55 .?.
/ey$oard
Figure. 'nput using 3%traction operator
C!#'!(in* of I?O o$e"!to"#:
!he statement 'out BBJSu+ F 5BB#u+BBJSnJE
0rst send the strings ?:umW@ to cout and then sends the value o" sum. Finally, it sends the
new line character so that the ne%t output will $e in the new line. !he multiple use o" OO in
one statement is called cascading.
The io#t"e!+ 7le:
!he "ollowing Sinclude directive in the program
Z in'lu(e Bio#t"e!+A
!his directive causes the preprocessor to add the contents o" the iostream 0le to the
program. 't contains declarations "or the identi0er 'out and the operator BB. :ome old
versions o" C>> use a header 0le called iostream.h. !he header 0le iostream should $e
included at the $eginning o" all programs that use inputDoutput statements.
1.
Retu"n t3$e of +!in,-:
'n C>> main=; returns an integer type value to the operating system. !here"ore, every
main=; in C>> should end with a return=0; statementL otherwise a warning or error might
occur. :ince +!in,- returns a integer type value, return type "or main=; is e%plicitly speci0ed
as int. the de"ault return type "or all "unctions in C>> is int.
int main=;
T
MM
MM
return 0L
V
St"u'tu"e of C++ $"o*"!+:
. typical C>> program would contain "our sections as shown in 0gure. !hese sections
may $e placed in separate code 0les and then compiled independently or 4ointly.
In'lu(e 7le#
Cl!## (e'l!"!tion
Cl!## fun'tion# (e7nition#
M!in fun'tion $"o*"!+
Fig. :tructure o" C>> program
TO[ENS
!he smallest individual units in a program are known as to$ens# C>> has the "ollowing
tokensA

/eywords

'denti0ers

Constants

:trings
<perators.
. C>> program is written using these tokens, white spaces and synta% o" the language.
[e3%o"(#:
!he keywords implement speci0c C>> language "eatures. !hey are e%plicitly reserved
identi0ers and cannot $e used as names "or the program varia$les or other user-de0ned
program elements.
:ome /eywords areA
auto $reak case catch char class const
continue de"ault delete do dou$le else
enu
m
e%tern Koat "or "riend goto i" inline
int long new operator private protected
pu$li
c
register return short signed sieo" static
struc
t
switch template this throw try typede" union
unsigned virtual void volatile while
I(enti7e"#:
denti%ers re"er to the names o" varia$les, "unctions, arrays, classes, etc. created $y
programmer.
!he "ollowing rules are common to $oth C and C>>.

<nly alpha$et characters, digits and underscores are permitted.

!he name cannot start with a digit.

2ppercase and lowercase letters are distinct.
. declared keyword cannot $e used as a varia$le name.
1/
\!"i!/le#:
Paria$les are locations in the memory that can hold values. Be"ore assigning any value to a
varia$le, it must $e declared. !o use the varia$le number storing an integer value, the
varia$le number must $e declared and it should $e o" the type int as "ollowsA
int num$erE
Con#t!nt#:
&onstants re"er to 0%ed values that do not change during the e%ecution o" a
program. -ike C, C>> support several kinds o" literal constants. !hey include integers,
characters, Koating point num$ers and string.
3%ampleA 17H DD decimal integer 17.H4
DD Koating point
integer
<H) DD octal integer <X7
DD he%adecimal
integer
?C>>@ DD string constant C. DD character constant
B!#i' D!t! T3$e#:
1ata types in C>> can $e classi0ed under various categories as shown in Fig.
C>> 1ata !ypes
2ser-de0ned type Built-in type 1erived type
structure array
union "unction
class pointer
enumeration re"erence
'nteger !ype Poid Floating type
int char Koat dou$le
Figure- &ierarchy o" C>> data types
Bith the e%ception o" void, the $asic data types may have several modi0ers preceding
them to serve the needs o" various situations. !he modi0ers signed, unsigned, long, and short
may $e applied to character and integer $asic data types. &owever, the modi0er long may
also $e applied to dou$le.
Si8e !n( R!n*e of C++ B!#i' D!t! t3$e#
T3$e B3te# R!n*e U#e
Char 1 -178 to >17) 2sed to store single character
unsigned char 1 0 to 7## 2sed to store unsigned =positive only;
single character
signed char 1 -178 to >17) 2sed to store signed =$oth positive and
negative; single character
'nt 7
-H7,)(8 to > H7,)() =-7
1#
to
7
1#
-1; 2sed to store integer =whole num$ers;
values
unsigned int 7 0 to (#,#H# 2sed to store unsigned integer =positive
whole num$ers; values
signed int 7
-H7,)(8 to > H7,)() =-7
1#
to
7
1#
-1; 2sed to store signed integer =whole
num$ers $oth positive and negative;
values
10
short int 7
-H7,)(8 to > H7,)() =-7
1#
to
7
1#
-1;
2sed to store short integer =whole
num$ers;
values
unsigned short
int 7 0 to (#,#H# 2sed to store unsigned short integer
=positive whole num$ers; values
signed short int 7
-H7,)(8 to > H7,)() =-7
1#
to
7
1#
-1;
2sed to store signed short integer
=whole
num$ers $oth positive and negative;
values
long int 4
-7,14),48H,(48 to
>7,14),48H,(4)
2sed to store long integer =whole
num$ers;
values
signed long int 4
-7,14),48H,(48 to
>7,14),48H,(4) 2sed to store unsigned long integer
=positive whole num$ers; values
unsigned long int 4 0 to 4,794,9(),79#
2sed to store signed long integer
=whole
num$ers $oth positive and negative;
values
Float 4 H.43-H8 to H.43>H8
2sed to store num$ers with decimal
point
with single precision.
1ou$le 8 1.)3-H08 to 1.)3>H08 2sed to store num$ers with decimal
point
with dou$le precision.
long dou$le 10 H.43-49H7 to 1.13>49H7
2sed to store num$ers with decimal
point
with more than dou$le precision.
\oi(:
!he normal use o" void is
=1;!o speci"y the return type o" a "unction when it is not returning any value and
=7;!o indicate an empty argument list to a "unction.
3%ampleA
U#e"]De7ne( D!t! T3$e#:
St"u'tu"e# !n( Cl!##e#:

1. struct !o store #t"u'tu"e


7. union !o store union
C>> also permits us to de0ne another user-de0ned data type known as 'l!## which
can $e used, 4ust like any other $asic data type, to declare varia$les. !he class varia$les are
known as o/e't#.
Enu+e"!te( D!t! T3$e:
.n enumerated data type is another user-de0ned type which provides a way "or
attaching names to num$ers, there$y increasing comprehensi$ility o" the code. !he enu+
keyword automatically enumerates a list o" words $y assigning them values 0,1,7 and so on.
!he synta% o" an enu+ statement is similar to that o" the #t"u't statement.
3%A enum
shape T circle, sGuare,
triangle VL
enum
color T red, green, $lue,
yellow VL
By de"ault, the enumerators are assigned integer values starting with 0 "or the 0rst
enumerator, 1 "or the second, and so on.
For e%ample,
voi( fun't1,voi(-E
enum colorTred, $lueW4,
greenW8VL enum
colorTredW#, $lue, greenVL
are valid de0nitions. 'n 0rst case, "e( is 0 $y de"ault. 'n the second case, /lue is ( and *"een
is ).
De"ive( D!t! T3$e#:
A""!3#:
.n array is a group o" like-typed varia$les that are re"erred to $y a common name. !he
compiler will allow declaring the array sie as the e%act length o" the string constant.
3% A char stringYHZW @%y@L is valid in C.
't assumes that the programmer to leave out the null character U0 in the
de0nition. But in C>>, the sie should $e one larger than the num$er o"
characters in the string.
char stringY4ZW @%y@L
11
4un'tion#:
't is a su$program to reduce the sie o" the program and to use di6erent places in a
program "or more than one time.
Pointe"#:
,ointers are declared and initialied as in C. For e%ample
int QaL it is an int pointer.
a W R%L it is an address o" % assigned to a.
C>> adds the concept o" constant pointer and pointer
to a constant# char Qconst ptW@so"t@L it is an
constant pointer.
S3+/oli' Con#t!nt#:
!her
e
are two ways o" creating sym$olic constants in C>
>.
2sing the Guali0er 'on#t.
1e0ning a set o" integer constants using enu+
keyword.
.ny value declared as 'on#t cannot $e modi0ed $y the program in any way. 't allows us to
create typed constants instead o" having to use Sde0ne to create constants that have no type
in"ormation. .s with lon* and #ho"t9 we can use the 'on#t modi0er alone, it de"aults to int.
For e%ample,
!o declare 'on#t aW10L =it means const int
aW10;. .nother method o" naming integer constants is as
"ollowsA
enumT%,y,VL
!his de0nes %,y and as integer constants with values 0,1,7 respectively. !his is eGuivalent to
const %W0L const yW1L const W7L
Be can also assign values to %,y and
e%plicitly.
enumT%W100,yW700,WH00VL
T3$e Co+$!ti/ilit3:
C>> de0nes int9 #ho"t int9 lon* int as three di6erent types. !hey must $e cast when
their values are assigned to one another. :imilarly, un#i*ne( 'h!"9 'h!"9 and #i*ne( 'h!"
are considered as di6erent types.
To use the #i8eof9 #i8eof,K6@-E it will $e eGuals to #i8eof,'h!"- and print the sie o"
character type
data
De'l!"!tion of \!"i!/le#:
'n C, all varia$les must $e declared they are used in e%ecuta$le statements. C>>
allows the declaration o" a varia$le any where in the scope. !his means that a varia$le can $e
declared right at the place o" its 0rst use.
3%ampleL
int main=;
T
Koat %L DDdeclaration
Koat sum W 0L
"or=int iW1LiO#Li>>; DDdeclaration
T
cinNN%L
sumWsum>%L
V
Koat averageL DDdeclaration
averageWsumDiL
coutOOaverageL
return 0L
V
12
D3n!+i' Initi!li8!tion \!"i!/le#:
C>>, permits initialiation o" the varia$le at run time. this is re"erred to as dynamic
initialization.
3%ampleA No"+!l (e'l!"!tion D3n!+i' De'l!"!tion
MM. MM
MM. MM
int nL int nWstrlen=string;L
nWstrlen=string;L MM
Koat areaL MM.
areaWH.141#9QradQradL
Koat
areaWH.141#9QradQradL
1ynamic initialiation is e%tensively used in o$4ect-oriented programming. Be can create
e%actly the type o" o$4ect needed, using in"ormation that is known only at the run time.
Refe"en'e \!"i!/le#:
C>> introduces a new kind o" varia$le known as the reference variable. . re"erence
varia$le provides an alias (alternati'e name( "or a previously de0ned varia$le. For e%ample, i"
we make the varia$le #u+ a re"erence to the varia$le tot!l, then #u+ and tot!l can $e used
interchangea$ly to represent that varia$le.
!he re"erence varia$le created as "ollowsA
(!t!0t3$e W "efe"en'e0n!+eFv!"i!/le0n!+eE
C>> assigns additional meaning to the sym$ol W. &ere, W is not an address operator. !he
notation Ro!t W
means re"erence to Ro!t.
3%ample,
int nY10ZL
int R % W nY10ZL DD % is alias "or nY10Z
char R a WUnL
DD initialie re"erence to a
literal
the varia$le 6 is an alternative to the array element nG1HI. !he varia$le ! is initialied to the
newline constant.
!he "ollowing re"erence are also allowed
i. int %L ii. int RnW#0L int QpWR%L
int RmWQpL
the 0rst set o" declarations causes + to re"er to 6 which is pointed to $y the pointer p and the
statement in ii. Creates an int o$4ect with value #0 and name n.
. ma4or application o" re"erence varia$les is in passing arguments to "unctions. Consider the
"ollowingA
voi( "=int R
%;
T
% W%>10L
V
int main=;
T
int
mW10L
"=m;L
------
------
V
DD uses re"erence int m W 10
m
DD % is incrementedL so also
m
one
location 10
two names
call
DD "unction call "=m;
%
int R % W
mL
when the "unction is call f,+- is e%ecuted, the "ollowing
initialiation occursA int W6 F +E
such "unction calls are known as call by reference! :ince the varia$le 6 and + are aliases,
when the "unction increments 6, + is also incremented. !he value o" m $ecomes 70 a"ter the
"unction is e%ecuted.
20
O$e"!to"#:
C>> has a rich set o" operators. .ll operators in C are valid in C>> also.
a? Assignment Operators b? Arithmetic Operators
c? Belational Operators d? Cogical Operators
d? )it 7ise Operators e? -ncrement6%ecrement operators
(? "hortcut Operators g? ,onditional Operators
h? "pecial operators
A##i*n+ent o$e"!to"#:
!he assignment operator is used to store the constants, varia$les, and result o" an
e%pression and return value o" a "unction "rom right side into varia$le placed in le"t side.
<perator A F 3% A ! F OE ! F /E ! F /+'E
A"ith+eti' o$e"!to"#:
!he arithmetic operators per"orm the $asic arithmetic operations such as addition,
su$traction,
multiplication, division and modulus.
!he operators
are A +9 ) 9 P9 ?9 ^
3% A 6F!+/9 6F!0/9 6F!P/9
6F!?/9 6F!^/
Un!"3 o$e"!to"#:
!he operators that work with only one operand are called as unary operators. !he
operators used in
C>> language are A +9 )9 ++9 ) )9 _.
In'"e+ent?De'"e+ent o$e"!to"#:
!he 'ncrement operators ++ increase the value o" operand $y one.
!he 1ecrement operators 00 decrease the value o" operand $y one.
3% A i++9 ++i9 i009 00i.
Sho"t'ut !##i*n+ent o$e"!to"#:
Bhen same varia$le is used in $oth le"t and right side o" an arithmetic e%pression, we
can use the
shortcut assignment operators .
!he operators are A +F9 ) F9 PF9 ?F9 ^F 3% A ! +F /9 ! )F/9 !PF/9 !?F/9 !
^F/
Si8eof !n( Co++! o$e"!to"#:
!he #i8eof operator returns the memory sie occupied $y an operand in terms o" $ytes.
3% A ! F #i8eof,int-L
!he 'o++! operator =9; ad4oins several
e%pressions. 3% A 6 F ,3 F .9 3 + 1-E
Con(ition!l o$e"!to"#:
!he `: are conditional operators. !hey do the 4o$ done $y i"..else control structure.
:ynta% A e6$"e##ion1 ` e6$"e##ion& :
e6$"e##ion.E
3% A /i* F ,!A/- ` ! :
/E
Rel!tion!l o$e"!to"#:
!he operators that do relationship tests with the operands are called relational
operators.
!he relational operators areA
E6 : if,! B /-
B =less than;
BF =less than or eGual to;
E6 :
if,! BF /-
A =greater than; E6 : if,! A /-
AF =greater than or eGual
to;
E6 :
if,! AF /-
FF =is eGual to;
E6 :
if,! FF /-
_F =not eGual to;
E6 : if,! _
F /-
1o*i'!l o$e"!to"#:
-ogical operators are used when more than one relationship should $e considered in
evaluation.
't gives either !rue value or False
value.
.91
operator A WW AND
E6: if,,!A/- WW
,!A'-- !ruth ta$le "or .91, <+A
<+ operator A aa

OR E6: if,,!A/- aa ,!A/--
A B AWWB A aa B
A _ NOT E6: if,_,!A/--
9<!
operator H H H H
H 1 H 1
!ruth ta$le o" 9<! A
A _ A
1 H H 1
H 1
1 1 1 1
1 H
21
Bit0%i#e o$e"!to"#
!he $it wise logical operators work with those decimal num$ers in its $inary "orm. !he
$it wise <+, $it wise .91, $it wise X<+, $it wise OO, and $it wise NN are $inary operators.
!he $it wise 1s complement is a unary operator.
Bit %i#e OR
,a- : 3% A 0101 a
101
0
W
1111
Bit %i#e
AND,W-: 3% A 0101W 0101
W
0101
Bit %i#e bOR
,c-: 3%A 0101 c
101
0
W
1111
Bit %i#e Co+$le+ent,d- :'" a $it is 1, then the operator converts it into H
and vice versa. 3% A d1010 W 0101.
Bit %i#e 1eft #hift ,BB- : 't is used to shi"t the $its to the le"t.
3%A % W # BB 7L 0000 0101 W 0001
0100 Bit %i#e Ri*ht #hift ,AA- : 't is used to shi"t the $its to
the right.
3%A % W # AA 7L 0000 0101 W 0000 0001
ne% o$e"!to"#. The3 !"e :
< 0000

in#e"tion o$e"!to" ,o" out$ut o$e"!to"- AA


0000

e6t"!'tion o$e"!to" ,o" in$ut o$e"!to"- :: 0000 S'o$e


"e#olution o$e"!to"
$ointe"0to0+e+/e" (e'l!"!to"
$ointe"0to0+e+/e" o$e"!to"
$ointe"0to0+e+/e" o$e"!to"
+e+o"3 "ele!#e o$e"!to"
line fee( o$e"!to"
+e+o"3 !llo'!tion o$e"!to"
7el( %i(th o$e"!to"C++int"o(u'e##o+e::P00000AP0000.P0000(elete0000en(l0000ne%0000#et%0000
S'o$e Re#olution O$e"!to" ,::-
C>> is a $lock structured language. Blocks and scopes can $e used in constructing programs.
!he same varia$le name can $e used to have di6erent meanings in di6erent $locks. !he
scope o" the varia$le e%tends "rom the point o" its declaration till the end o" the $lock
containing the declaration. . varia$le declared inside the $lock is said to $e local to that
$lock.
3%ample 1A 3%ample 7A
----- -----
----- -----
T T
int % W10L int % W 10L
----- -----
----- -----
V T
----- int % W 1L
----- ----- Block 7
Block
1
T -----
int % W1L V
----- -----
----- -----
V V
!he two declarations o" % re"ers to two di6erent memory locations containing di6erent values.
!he statement second $lock cannot re"er to the varia$le % declared in the 0rst $lock, and vice-
versa.
Block7 is contained in Block1. 9ote that a declaration in an inner $lock hides a
declaration o" the same varia$le in an outer $lock and there"ore, each declaration o" 6 causes
it to re"er to a di6erent data o$4ect.
'n C, the glo$al version o" a varia$le cannot $e accessed "rom within the inner $lock.
C>> resolves this pro$lem $y introducing a new operator :: called the scope resolution
operator.
22
!his can $e used to uncover a hidden varia$le. 't take the "ollowing "orm
:: v!"i!/le0n!+e
!his operator allows access to the glo$al version o" varia$le. AAcount means the glo$al
version o" the varia$le count.
3%ample1A
Sinclude OiostreamN coutOO@ we are in inner $lock Un@L
int
+W10L DDglo$al m coutOO@k W@OO/OO@Un@L
int main=; coutOO@m W@OOmOO@Un@L
T coutOO@AAm W@OOAAmOO@Un@L
int
+W70L DD m redeclared, local to main V
T
int k W mL
coutOO@Un we are in outer $lockUn@;L
coutOO@mW@OOmOO@Un@VL
int + W H0L DDm declared again
coutOO@AAmW@OOAAmOO@Un@VL
DD local to inner $lock
return 0L
V
<utputA
Be are in inner
$lock k W 70
m W H0
::+ F 1H
Be are in outer $lock
m W 70
::+ W 10
Me+/e" De"efe"en'in* O$e"!to"#:
AAQ

----- !o declare a pointer to a mem$er o" a class
Q
----- !o access a mem$er using o$4ect name and a pointer to that the
mem$er
-
to access a mem$er using a pointer to the o$4ect and a pointer to
that mem$er
Me+o"3 M!n!*e+ent O$e"!to"#:
Be use dynamic allocation techniGues when it is not known in advance how much o"
memory space is needed. .lthough C>> support these "unctions, it also de0nes two unary
operators ne% and (elete that per"orm the task o" allocating and "reeing the memory in a
$etter and easier work. !hese operators manipulate memory on "ree storeL they are also
known as free store operators.
.n o$4ect can $e created $y using ne%, and destroyed $y using (elete. !he ne%
operator can $e used to create o$4ects o" any type. 't take the "ollowing general "orm
pointer-varia$le W ne% data-typeL
&ere, pointer-variable is a pointer o" type data-type. !he ne% operator allocates su5cient
memory to hold a data o$4ect o" data-type and returns the address o" the o$4ect. !he
pointer-variable holds the address o" the memory space allocated. !he declaration o"
pointer and their assignments as "ollows.
int P$ Fne% intE
Ro!t P: F ne%
Ro!tE
Bhen a data o$4ect is no longer needed, it is destroyed to release the memory space reuse.
!he general "orm o" its use is
(elete pointer-varai$leL
the pointer-variable is the pointer that points to a data o$4ect created with ne%. 3%ample
(elete
$E
(elete
:E
!he ne% operator o6ers the "ollowing advantagesA
1.'t automatically computes the sie o" the data o$4ect. Be need not use the operator #i8eof.
7.'t automatically returns the correct pointer type, so that there is no need to use a type cast.
H.'t is possi$le to initialie the o$4ect while creating the memory space.
4.-ike any other operator, ne% and (elete can $e overloaded.
23
M!ni$ul!to"#:
*anipulators are operators that are used to "ormat the data display. !he most
commonly used manipulators are en(l and #et%.
!he en(l manipulator, when used in an output statement, causes a line"eed to $e
inserted. 't has the same e6ect as using the newline character ?Un@. "or e%ample, the
statement
<utput
MM..
7 # 9 ) MM.. m W
coutOO@mW@OOmOOendlL
coutOO@nW@OOnOOendlL n W 1 4
coutOO@pW@OOpOOendlL p W
1 ) #
MM.
!hree lines o" output, one "or each
varia$le. the
values o" the
varia$le as 7#9),14 and
1)#
respectively. !he output will appear as shown $elow.
&ere, the num$ers are right-justi%ed. !his "orm o" output is possi$le only i" we can
speci"y common 0eld width "or all the num$ers and "orce them to $e printed right-4usti0ed.
!he #et manipulator does this 4o$. 't is used as "ollows.
coutOOsetw=#;OOsumOOendlL
!he manipulator #et%,M- speci0es a 0eld width # "or printing the value o" the varia$le
sum. !his value is right-4usti0ed within the 0eld s shown $elow.
H 4 #
!he program illustrate the use o" en(l and #et%.
E6!+$le
SincludeOiostreamN
SincludeOiomanipN DD "or setw
int main=;
T
int $asic W 9#0, allowanceW9#, totalW104#L
coutOOsetw=10;OO@Basic@OOsetw=10;OO$asicOOendl
L
coutOOsetw=10;OO@.llowance@OOsetw=10;OOallowan
ceOOendlL
coutOOsetw=10;OO@!otal@OOsetw=10;OOtotalOOendlL
return 0L
V
<utput o" this program is given $elow.
Basic 9#0
.llowance 9#
!otal 104#
T3$e C!#t O$e"!to"#:
C>> permits e%plicit type conversion o" varia$les or e%pression using the type cast
operator.
,t3$e0n!+e-
e6$"e##ion ??C not!tion
t3$e0n!+e
,e6$"e##ion- ??C++ not!tion
3%amplesA
!ve"!*e F #u+?
,Ro!t- ?? C not!tion
!ve"!*eF#u+?Ro!t,i
-E ?? C++ not!tion
For e%ample,
pWintQ=G;L is illegal. 'n :uch cases, we must use C type notation.
pW=intQ;GL alterativley, we can use typede" to create an identi0er o" the reGuired type
and use it in the "unctional notation.
typede" int Q
int[pt
pWint[pt=G;
2
E6$"e##ion# !n( thei" t3$e#:
.n e%pression is a com$ination o" operators, constants and varia$les arranged as per the
rules o" the language. 3%pressions consist o" one or more operands, and ero or more
operators to produce a value.

3%pressions may $e o" the "ollowing seven typesA


Constant e%pression
'ntegral e%pression
Float e%pression
,ointer e%pression
+elational e%pression
-ogical e%pression
Bitwise e%pression
.n e%pression may also use com$inations o" the a$ove e%pressions. :uch e%pressions are
known as compound e%pressions
Con#t!nt E6$"e##ion:
Constant e%pression consists o" only constant values.
3%amplesA 1# 70 > # D 7.0
Inte*"!l E6$"e##ion#:
'ntegral e%pressions are those which produce integer results a"ter implementing all the
automatic and e%plicit type conversions. 3%amplesA
m
m Q n -
# m Q
%
# > int=7.0;
where + and n are integer varia$les.
4lo!t E6$"e##ion#:
Float e%pressions are those which, a"ter all conversions, produce Koating point
results. 3%amplesA % > y
% Q y D 10
# > Koat=10;
10.)#
where 6 and 3 are Koating-point varia$les.
Pointe" E6$"e##ion#:
,ointer e%pressions produce address values.
e%amplesA Rm
ptr
ptr>
1
?%y
@
where + is a varia$le and $t" is a pointer.
Rel!tion!l E6$"e##ion#:
+elational e%pressions yield results o" type /ool which takes a value t"ue or
f!l#e. 3%amplesA % OW y
a > $ WW c
> d m > n
N 100
when arithmetic e%pressions are used on either side o" a relational operator, they will $e
evaluated 0rst and then results compared. +elational e%pressions are also known as "oolean
'#pressions.
1o*i'!l E6$"e##ion#:
-ogical e%pression com$ine two or more relational e%pressions and produces /ool type
results. 3%amplesA a N $ RR % WW 10L
% WW 10 \\ y WW #
2.
Bit%i#e E6$"e##ion#:
Bitwise e%pressions are used to manipulate data at $it level. !hey are $asically used "or
testing or shi"ting $its. 3%amplesA
%OOH DDshi"t three $it position to le"t
yNN1 DDshi"t one $it position to right
shi"t operators are o"ten used "or multiplication and division $y powers o" two.
S$e'i!l A##i*n+ent E6$"e##ion#
Ch!ine( A##i*n+ent
% W = y W 10 ;L or % W y W 10L
First 10 assigned to y and then to %.
. chained assignment cannot $e used to initialie varia$les at the time o" declaration.
E+/e((e( A##i*n+ent
% W =y W #0; > 10.
=yW#0; is an assignment e%pression known as em$edded assignment. &ere, the value
#0 is assigned to y and then the result #0 > 10 W (0 is assigned to %.
Co+$oun( A##i*n+ent
C>> supports compound assignment operator which is a com$ination o" the assignment
operator with a $inary arithmetic operators.
3%ampleA % W % > 10 may $e written as 6 +F 1HL
!he operator >W is known as compound assignment operator or short-hand assignment
operator.
!he general "orm is A v!"i!/le o$ F v!"i!/le &E
OPERATOR PRECEDENCE
.ssociativity de0nes in the case that there are several operators o" the same priority level-
which one must $e evaluated 0rst, the rightmost one or the le"tmost one.
2/
CONTRO1 STRUCTURES:
Control :tructure
:election :eGuence -oop
i"-else switch do-while while, "or
!wo way
$ranch
*ulti way
$ranch 3%it-control
3ntry-
control
b
The if #t!te+ent : !he if statement is implemented in two "ormsA
:imple if statement
ifDel#e statement
a;!he if structure tests a condition and trans"ers the control accordingly.
S3nt!6 : if,e6$"e##ion-
X #t!te+ent# Y
3%ample A i"=aN$;
print"=?. is $ig@;L
print"=?B is $ig@;L
$; ifDel#e structure works according to the true R "alse value generated $y the e%pression.
:ynta% A if,'on(ition-
X #t!te+ent# Y
el#e
X #t!te+ent# Y
3%ample A if,+!"2# AF NH-
$"intf,5P!##J-E
el#e
$"intf,54!ilJ-E
c; Ne#te( if #t"u'tu"e:
'" any if or el#e $lock contains another if9 ifDel#e9 el#eDif l!((e" then it can
$e called as
Ne#te( ifDel#e.
20
fo",iFHE iB1HE
i++- 'outBBiE
!he while structure is called as entry controlled loop. !he condition is tested 0rst. '" the
condition satis0es, the loop $lock is e%ecuted, otherwise the program e%ecution continues
a"ter the while structure. :ynta% A 3%ample A
(oD%hile loo$ #t"u'tu"e:
Y Y
i F 1E
%hile,i B
1H-
X 'outBBiBBJSnJE
i++E
initi!li8!tionE
%hile,'on(ition
- X #t!te+ent#E
in'"e+ent?(e'"e+entE
%hile loo$ #t"u'tu"e:
:ynta% A
if,e6
$- 3%ample A if,+!"2 AF OH-
X X
if,e6$- if,+!"2 AF QM-
X #t!te+e
nt# Y $"intf,5=onou"#J-E
el#e el#e
X #t!te+e
nt# Y $"intf,5I 'l!##J-E
Y Y
el#e el#e
X if,e6$- X if,+!"2 AF NH-
X #t!te+e
nt# Y
$"intf,5II
Cl!##J-E
el#e el#e
X #t!te+e
nt# Y $"intf,54!ilJ-E
Y Y
S%it'h #t"u'tu"e:
#%it'h is called *ulti-directional control structure. !his structure is used when
decision-making is
depending upon more than two values.
:ynta% A #%it'h,e6$- 3%ample A #%it'h,n-
X X
'!#e 1 : '!#e 1 :
!'tion1E $"intf,5ONEJ-E
/"e!2E
'!#e & : '!#e & :
!'tion&E $"intf,5T<OJ-E
/"e!2E
'!#e .: '!#e . :
!'tion.E $"intf,5T=REEJ-E
(ef!ult : /"e!2E
!'tionNE (ef!ult :
$"intf,5Th!n2 3ouJ-E
Y /"e!2E
Y
!he doMwhile structure is called as e%it controlled loop. !he $lock is e%ecuted 0rst and
the condition is tested ne%t. '" the condition satis0es, the $lock is e%ecuted again, otherwise
the program
e%ecution continues a"ter the doMwhile structure.
:ynta% A initi!li8!tionE 3%ample A
i F
1E
(o (o
X #t!te+ent#E X
'outBBiBBJS
nJE
in'"e+ent?(e'"e+entE i++E
Y %hile,'on(ition-E Y%hile,i B 1H-E
fo" loo$ #t"u'tu"e:
"or statement is used to e%ecute a statement or a group o" statements repeated "or a
known num$er o" times.
:ynta% A fo",initi!li8!tionE 'on(itionE in'"?(e'"- 3% A
X
#t!te+ent#E
Y
21
Othe" fo"+# of fo" loo$ :
't is possi$le to omit any one o" the sections in "or construct. 'n case, i" we omit, a semi colon
must $e present.
3%amples A a. fo", E iB1H E i++ - $. fo", E iB1H E - c. fo", E E E-
Be can use more than one initial value, condition and counter inside a "or loop $y using
comma operator. d. fo",i F19 F1E iBM9 B.E i++9 ++-
ARRALS
.n array is a group o" related data items that share a common name. .n array reserves
continuous memory location to place the values consecutively. !he types are A
1.<ne-dimensional array.
7.!wo-dimensional array.
H.*ulti-dimensional array.
Rule# fo" #u/#'"i$te( v!"i!/le# :
a. !he su$script is always an integer
$. !he su$script value cannot $e negative
c. !he su$script must $e given within sGuare $rackets.
d. '" there is more than one su$script, they should $e given within separate sGuare
$rackets. 9o
other delimiters are used.
One0(i+en#ion!l !""!3 :
.n array having only one su$script is a one-dimensional array.
1eclaration
'nitialiatio
n 3%ample
T%o0(i+en#ion!l !""!3 :
.n array having two su$scripts is a two-dimensional array.
1eclaration
A
t3$e !""!3Cn!+eG#i8e1IG#i8e&IE
A t3$e !""!3Cn!+eG#i8eIE
A t3$e !""!3Cn!+eG#i8eI F
X v!lue# YE A int !G1HIE
int !G1HI F
X 19&9.9N YE
'nitialiation
A
t3$e
!""!3Cn!+eG#i8e1IG#i8e&I F
X v!lue# YE
3%ample A int !G1HIG1HIE
int !G1HIG1HI F X 19&9.9N YE
Multi0(i+en#ion!l !""!3:
.n array having more than two su$scripts is a multi-dimensional array.
1eclaration
A
t3$e !""!3Cn!+eG#i8e1IG#i8e&IDG#i8eNIE
'nitialiation
A
t3$e
!""!3Cn!+eG#i8e1IG#i8e&ID
G#i8eNIFX v!lue#YE
3%ample A int !G&IG&IG&IE
int !G&IG&IG&I F X 19&9.9N9M9O9Q9U YE
Pointe" :
. pointer is a varia$le that contain the address o" any varia$le. 't point to varia$le o" the data type "or
which it has $een declared. 't is declared with the CQ preceding it.
!he unary operator W gives the ?address o" a varia$le@.
!he indirectionDdere"erence operator P gives the ?content o" an o$4ect pointed to $y a
pointer@.
\!"i!/le \!lue A(("e##
]uantity 102 #000
p
.000
#048
!he value o" the varia$le p is the address o" the varia$le Guantity. .ccess the value o" Guantity
$y using the value o" p. the varia$le p Cpoints to the varia$le Guantity thus p gets the names
pointer.
E6. int P$E
$FW:u!nti
t3E
assign the address #000 =location o" Guantity; to varia$le p. the R operator remem$ered
?address o" ?.
22
4UNCTIONS
A fun'tion i# #!i( to /e ! #et of in#t"u'tion# th!t '!n $e"fo"+ ! #$e'i7' t!#2.
't will $e reduce the sie o" the program $y calling and using them at di6erent places in the
program. !he advantages areA Re0u#!/ilit39 +o(ul!"it39 ove"!ll $"o*"!++in*
#i+$li'it3. Functions are classi0ed into li$rary "unctions and user-de0ned "unctions.
1i/"!"3 4un'tion#: !he "unctions that are already availa$le in the C>> li$rary are called
-i$rary "unctions. :ome important categories o" li$rary "unctions are A 'nputD<utput "unctions
=iostream.h;, *athematical "unctions =*ath.h;, :tring handling "unctions =:tring.h;, Console
inputDoutput "unctions =conio.h; and *anipulator "unctions =iomanip.h;.
U#e"0De7ne( 4un'tion#: . "unction de0ned $y the user is called as user-de0ned "unction.
!he advantage o" user-de0ned "unction is that the comple%ity o" a program is reduced and the
errors can $e traced easily.
The M!in 4un'tion:
'n C>>, the +!in,- returns a value o" type int to the operating system. C>>,
there"ore, e%plicitly de0nes +!in,- as matching one o" the "ollowing prototypesA
int +!in, -E
int +!in, int !"*-E
!he "unction that have a return value should use the "etu"n statement "or termination.
!he +!in, - "unction in C>>, there"ore, de0ned as "ollowsA
int main= ;
T ---------
---------
return 0L
V
!he return type o" "unction is int $y de"ault, the keyword int in the main= ; header is
optional. *ost C>> compilers will generate an error or warning i" there is no "etu"n
statement.
The $"otot3$e (e#'"i/e# the fun'tion inte"f!'e to the 'o+$ile" /3 *ivin* (et!il#
#u'h !# the
nu+/e" !n( t3$e of !"*u+ent# !n( the t3$e of "etu"n v!lue#. <hen ! fun'tion i# '!lle(9 the 'o+$ile" u#e#
the te+$l!te to en#u"e th!t $"o$e" !"*u+ent# !"e
4un'tionP"otot3$in*,o"(e'l!"!tion-:

$!##e(9 !n( the "etu"n v!lue i# t"e!te( 'o""e'tl3.
Function prototype is a declaration statement in the calling program and is o" the "ollowing
"ormA
t3$e fun'tion0n!+e , !"*u+ent0li#t -E
!he argument-list contains the types and names o" arguments that must $e passed to
the "unction.
E6!+$le
: int '!l,int9 int9 Ro!t-E
Ro!t #u+,int !9 Ro!t /9 Ro!t '-E
4un'tion De7nition:
4un'tion (e7nition (e7ne# the o$e"!tion# of ! fun'tion %hi'h i# !l"e!(3 (e'l!"e(.
Bhen the "unction de0nition comes $e"ore the main=; "unction, we need not declare it.
E6!+$le: Koat #u+=int a, Koat $, Koat c;
T
Koat vWa>$>cL
----------
V
4un'tion '!ll : !he process o" calling a "unction "or e%ecution is known as "unction call. .ny
user de0ned "unction can call any other "unction. !here are two types o" "unction callA C!ll /3
v!lue and C!ll /3 Refe"en'e.
30
!he "unction #u+, - can $e invoked in a program as
"ollowsA Ro!t !((v!l F #u+,/19%19h1-E
??fun'tion '!ll
!he varia$le /1,%1 and h1 are known as the !'tu!l $!"!+ete"# =!"*u+ent#; which
speci"y the dimensions o" !((v!l. !heir types should match with the types declared in the
prototype. !he calling statement should not include type names in the argument list.
Di;e"ent t3$e# of 4un'tion#
1. Function %ith $!"!+ete"# =arguments;
and
7. Function %ith $!"!+ete"# =arguments;
and
%ithout "etu"n v!lue#. %ith ! "etu"n v!lue.
Sinclude Oiostream.hN Sinclude Oiostream.hN
Sinclude Oconio.hN Sinclude Oconio.hN
void main= ; void main= ;
T T
int aW10, $W10L int aW10, $W10L
void add=int,int;L int add=int,int;L
clrscr=;L clrscr=;L
add=a,$;L cout OO add=a,$;L
getch=;L getch=;L
V V
void add=int %, int y; int add=int %, int y;
T T
coutOO %>yL return=%>y;L
V V
7. Function %ithout $!"!+ete" =argument;
and
7. Function %ithout $!"!+ete" =argument;
and
%ith ! "etu"n v!lue. %ithout ! "etu"n v!lue.
Sinclude Oiostream.hN Sinclude Oiostream.hN
Sinclude Oconio.hN Sinclude Oconio.hN
void main= ; void main= ;
T T
int add=;L void add=;L
clrscr=;L clrscr=;L
cout OO add=;L add=;L
getch=;L getch=;L
V V
int add=; void add=;
T T
int %W10, yW10L int %W10, yW10L
return=%>y;L cout OO =%>y;L
V V
P!"!+ete" P!##in* in 4un'tion#
C!ll B3 \!lue :
Bhen a "unction is called $y #u$$l3in* v!lue# !# $!"!+ete"# =arguments;, it is
called C!ll B3 \!lue. !he values placed in the !'tu!l $!"!+ete"# !"e 'o$ie( into the
fo"+!l $!"!+ete"#. :o any 'h!n*e# +!(e to the fo"+!l $!"!+ete"# (o not !;e't the
!'tu!l $!"!+ete"#.
C!ll B3 Refe"en'e:
Bhen we pass $!"!+ete"# ,!"*u+ent#- /3 "efe"en'e, the fo"+!l $!"!+ete"# in
the called "unction /e'o+e !li!#e# to the !'tu!l $!"!+ete"# in the calling "unction. :o any
'h!n*e +!(e in the fo"+!l $!"!+ete"# !;e't the o"i*in!l v!lue.
31
Retu"n B3 Refe"en'e:
. "unction can also return a re"erence.
int W ma%=int R%, int Ry;
T i"=%Ny;
return %L
else
return yL
V
:ince the return type o" +!6, -is int W, the "unction returns re"erence to 6 and 3 =and
not the value;. !hen "unction call such as +!6,!9/- will yield a re"erence to either ! or /
depending on their values. !his means that this "unction call can appear on the -e"t-hand side
o" an assignment statement. !hat is, the statement
+!6,!9/- F 01E
is legal and assigns -1 to ! i" it is larger, otherwise -1 to /.
Inline 4un'tion:
<ne o" the o$4ectives o" using "unctions in a program is to save some memory space,
which $ecomes apprecia$le when a "unction is likely to $e called many times. 3very time a
"unction is called, it takes a lot o" e%tra time is e%ecuting a series o" instructions "or tasks such
as 4umping to the "unctions, saving registers, pushing arguments into stack, and returning to
the calling "unction.
To eli+in!te the 'o#t of '!ll# to #+!ll fun'tion#9 C++ $"o$o#e# ! ne% fe!tu"e
'!lle( inline function. Inline fun'tion i# ! fun'tion th!t i# e6$!n(e( in line %hen it
i# invo2e(.
S3nt!6: Inline "unction-header
T
"unction $ody
V
E6!+$le: inline dou$le cu$e=dou$le a;
T
return=aQaQa;L
V
't will $e reduce the memory sie and processing time will $e very "ast more than the normal
"unctions.
:ome o" the situations where inline e%pansion may not work areA
1. For "unctions returning values, i" a loop, a #%it'h, or a *oto e%ists.
7. For "unctions not returning values, i" a return statement e%ists.
H. '" "unctions contain #t!ti' varia$les.
4. '" inline "unctions are recursive.
Def!ult A"*u+ent#:
C>> allows us call a "unction without speci"ying all its arguments. 'n such cases, the
"unction assigns a default value to the parameter which does not have a matching argument
in the "unction call. 1e"ault values are speci0ed when the "unction is declared. !he compiler
looks at the prototype to see how many arguments a "unction uses and alerts the program "or
possi$le de"ault valuesA
Ro!t !+ount, Ro!t $"in'i$!l9 int $e"io(9 Ro!t "!teFH.1M-E
the a$ove prototype declare a de"ault value o" 0.1# to the argument "!te. :u$seGuent
"unction call like
v!lue !+ount,MHHH9Q-E ?? one !"*u+ent +i##in*
passes the value o" #000 to $"in'i$!l and ) to $e"io( and then let the "unction use de"ault
value o" 0.1# "or rate. !he call
v!lue !+ount, MHHH9M9H.1&-E
passes the value o" 0.17 to "!te.
32
<ne important point to note is that only the trailing argument can have de"ault values. Be
must add de"ault "rom right to left. Be cannot provide a de"ault value to a particular
argument in the middle o" argument list.
int mul =int i9 int FM9 int
2F1H;L DD legal
int mul =int iFM9 int FM;L DD illegal
int mul =int iFH9 int 9 int
2F1H;L DD illegal
int mul =int iF&9 int FM9 int
2F1H;L DD legal
'on#t A"*u+ent#:
'n C>>, an argument to a "unction can $e delivered as const as
shown $elow. int strlen='on#t char Qp;L
int length='on#t string Rs;L
!he Guali0er 'on#t tells the compiler that the "unction should not modi"y the
argument. !he compiler will generate an error when this condition is violated. !his
type o" declaration is signi0cant only when we pass arguments $y re"erence or
pointers.
4un'tion Ove"lo!(in*:
Overloading re"ers to use o" the same thing "or di6erent purposes. C>> also permits
overloading o" "unctions. !his means that we can use the same "unction name to create
"unctions that per"orm a variety o" di6erent tasks. !his is known as function polymorphism
in <<,.
2sing the concept o" "unction overloadingL we can design a "amily o" "unctions with one
"unction name $ut di6erent argument list. !he "unction would per"orm di6erent operations
depending on the argument list in "unction call. !he correct "unction to $e invoked is
determined $y checking the num$er and type o" the argument $ut not on the "unction type.
For e%ample, an overload !((, - "unction handles di6erent type o" data as $elowA
(unction prototypes
)declarations* (unction calls
int add=int a, int $;L cout OO add=#,10;L
int add =int a, int $, int c;L cout OO add=1#,10.0;L
dou$le add=dou$le a, dou$le $;L cout OO add=17.#,).#;L
dou$le add=int a dou$le G;L cout OO add=#,10,1#;L
dou$le add= dou$le p, int G;L cout OO add=0.)#,#;L
Re'u"#ive 4un'tion:
. "unction call $y itsel" is called +ecursive Function.
E6!+$le:
SincludeOiostream.hN
int f!'t,int n-E ?? 4un'tion (e'l!"!tion
void main=;
T
coutOO^( "actorial value is^OOf!'t,O-OOendlL DDCalling "act=; "unction in main=;.
coutOO^# "actorial value is^OOf!'t,M-OOendlL DD Calling "act=; "unction in main=;.
V
int "act=int n;
T
int resL
i"=nWW1;
return 1L
else
resWf!'t,n01-QnL DDCalling f!'t,- "unction inside the same "unctions $ody=4un'tion
'!ll# it#elf;
return resL
V
33
?P 1!/ E6e"'i#e 0& : P"o*"!+ to i+$le+ent fun'tion ove"lo!(in*9 inline
fun'tion9 (ef!ult !"*u+ent9 Con#t!nt !"*u+ent9 C!ll /3 v!lue
!n( C!ll /3 "efe"en'eP?
SincludeOiostream.hN
SincludeOconio.hN
int volu+e=intW;L
dou$le volu+e=dou$le,
dou$le;L long volu+e=long,
int, int;L
inline Koat volu+e='on#t Koat W,Koat;L
int +!in,-
X
int !E
'l"#'"
,-E
cout OO ^Function <verloading ,rogram to 0nd the volume o" 4 Jeometric ,rimitives Un
Un^L
cout OO
^---------------------------------------------------------------------------------------------------------- Un^L
'out BB eEnte" #i(e v!lue fo" 'u/e : SneE
'in AA !E
cout OO ^Call $y re"erence method A int volume=int
R;L Un^L cout OO
^------------------------------------------------------------ Un^L 'out
BB e\olu+e of ! 'u/e : e BB volu+e,!- BB eSn
SneE
cout OO ^Call $y value method A dou$le volume=dou$le,
int;L Un^L cout OO
^-------------------------------------------------------------------- Un^L 'out
BB e\olu+e of '3lin(e" : e BB volu+e,&.M9 U.H- BB
eSn SneE
cout OO ^1e"ault .rgument method A long volume=long l, int $, int hW10;L Un^L
cout OO
^------------------------------------------------------------------------------------- Un^L
'out BB e\olu+e of Re't!n*ul!" /o6 : e BB volu+e,1HH19 QM9
1H- BB eSn SneE
cout OO ^'nline "unction R const
.rgument
A inline Koat volume=const
KoatR,Koat;L Un^L
cout OO
^---------------------------------------------------------------------------------------------------- Un^L
'out BB e\olu+e of ! S$he"e : e BB volu+e,1...9
M.H- BB eSn SneE getch=;L
return 0L
V
int volu+e=int W s;
T
return=s Q s Q s;L
V
dou$le volu+e =dou$le r, dou$le h;
T
return=H.14#19 Q r Q r Q h;L
V
long volu+e =long l, int $, int h;
T
return =l Q $ Q h;L
V
inline Koat volu+e='on#t Koat Wc, Ro!t "F1H.H;
T
return =c Q H.14#19 Q r Q r Q r;L
V
3
C St"u'tu"e# Revi#ite(:
. structure is a convenient tool "or handling a group o" logically related data item. !hey
provide a method "or packing together data o" di6erent types. 't is a user de0ned data type
with a template that serves
to de0ne its data properties.
For e%ample, #t"u't student
T
char nameY70ZL
int rollnoL
Koat totalmarkL
VL
!he keyword #t"u't declares #tu(ent as a new data type that can hold three 0elds o"
di6erent data types. !hese 0elds are known as structure members or elements. !he
identi0er student, which is re"erred to as structure name or structure tag, can $e used to
create varia$les o" type student.
3%ample #t"u't student AL DC declaration
. is a varia$le o" type student and has three mem$ers varia$le as de0ned $y the template.
*em$er varia$le can $e accessed using the dot or period operator as "ollowsA
#t"'$3,A.n!+e9
5Roeve"J-E A."ollno
F 1&.NE A.tot!l+!"2
F UQVE
S$e'if3in* Cl!##:
. Class is a way to $ind the data and its associated "unctions together. 't allows the
data =and "unctions; to $e hidden, i" necessary, "rom e%ternal use. Bhen de0ning a class, we
are creating a new abstract data type that can $e treated like any other $uilt-in data type.
Jenerally, a class speci0cation has two partsA
1. Cl!## (e'l!"!tion
&. Cl!## fun'tion (e7nition#
!he class declaration descri$es the type and scope o" its mem$ers. !he class "unction
de0nitions descri$e how the class "unctions are implemented.
Gene"!l fo"+ of ! 'l!##
(e'l!"!tion i#:
'l!## class[name
T
$"iv!te:
varia$le
declarationsL
"unction
declarationsL
$u/li':
varia$le
declarationsL
"unction
declarationsL
VL
!he 'l!## declaration is similar to a #t"u't declaration. !he keyword 'l!## speci0es,
that what "ollows is an a$stract data o" type class+name. !he $ody o" a class is enclosed
within $races and terminated $y a semicolon. !he class $ody contains the declaration o"
varia$les and "unctions. !hese "unctions and varia$les are collectively called class members.
!hese are usually grouped in two sections, namely, $"iv!te and $u/li' known as visi$ility
la$els and the keywords are "ollowed $y a colon.
!he class mem$ers that have $een declared as $"iv!te can accessed only "rom within
the class, $u/li' mem$ers can $e accessed "rom the outside the class also. !he use o"
keyword $"iv!te is optional. By de"ault, the mem$ers o" a class are $"iv!te. '" $oth la$els
are missing, then, de"ault, the mem$ers are $"iv!te.
!he varia$le declared inside the class are known as data members and the "unctions
are known as member functions. ,u$lic mem$ers =$oth "unction and data; can $e accessed
"rom outside the class. !he $inding o" data and "unctions together into a single class-type
varia$le is re"erred to as encapsulation.
3.
C1ASS
,rivate area
9o 3ntry to
private area 1ata
X
Functions
,u$lic area
3ntry allowed
to
1ata
,u$lic area
Functions
Data hiding in
classes
A Si+$le Cl!## E6!+$le: !he class declaration would look likeA
'l!## Ite+
T
$"iv!te:
int num$erL DD varia$le declaration
int costL DD private $y de"ault
$u/li':
void getdata =int a, Koat $;L DD "unction declaration
void putdata=;L DD using prototype
VL
C"e!tin* o/e't#:
.n o$4ect in C>> is essentially a $lock o" memory that contains space to store all the
instance varia$les. Creating an o$4ect is also re"erred to as instantiating an o$4ect.
!o create o$4ects o" type ite+, use statements such as the "ollowingA
Ite+ 6L DDmemory "or % is created
creates a varia$le 6 o" the type ite+. 'n C>>, the class varia$les are known as objects.
!here"ore, 6 is called an o$4ect o" type ite+. Be may also declare more than one o$4ect in
one statement.
3%ample A Ite+ 69 39 8E
<$4ects can also $e created when a class is de0ned $y placing their names immediately
a"ter the closing $race,
class 'tem
T MM..
MM.
.
V %, y, L
would create the o$4ect 69 3 and 8 o" type ite+.
A''e##in* 'l!## +e+/e"#:
!he private data o" a class can $e accessed only through the mem$er "unctions o" that
class. !he +!in, - cannot contain statement that access nu+/e" and 'o#t directly. !he
"ollowing is the "ormat "or calling a mem$er "unction.
O/e'tCn!+e.fun'tionn!+e ,!'tu!l !"*u+ent-
For e%ample, the "unction call statement
6.*et(!t!,1HH9 QM.M-E
is valid and assign the values 100 to nu+/e" and )#.# to 'o#t o" the o$4ect 6 $y
implementing the *et(!t!,- "unction.
3/
:imilarly, the statement
6.$ut(!t!,-E
would display the values o" data mem$ers.
Dot O$e"!to":
!he dot notation is used to o$tain the value o" the instance varia$les. 't has two parts
namely the o$4ect on the le"t side o" the dot and the varia$le on the right side o" the dot. 1ot
e%pressions are evaluated "rom le"t to right. !he general "orm "or accessing instance varia$les
using the dot operator is given $elowA
O/e't"efe"en'e.v!"i!/le n!+e
Be can store values into instance varia$les using the dot operator as shown $elowA
one.c W 10L two.c W 1#L
Be can re"er to values o" instance varia$les using the dot operator as
given $elowA coutOO ?cW@ OO one.cL
coutOO ?cW@ OO two.cL
De7nin* Me+/e" 4un'tion:
*em$er "unction can $e de0ned as two placesA
1. <utside the class de0nition
7. 'nside the class de0nition.
Out#i(e the 'l!## (e7nition:
'l!##Cn!+e ::
*em$er "unctions that are declared inside a class have to $e de0ned separately outside
the class. !hey should have a "unction header and a "unction $ody. .n important di6erence
$etween a mem$er "unction and a normal "unction is that a mem$er "unction incorporates a
mem$ership Cidentity la$el in the header.
!he general "orm o" a mem$er "unction de0nition isA
retu"n0t3$e 'l!##0n!+e :: fun'tion0n!+e,!"*u+ent (e'l!"!tion-
X
fun'tion /o(3
Y
!he mem$ership la$el tells the compiler that the "unction function-name
$elongs
to the class class-name. !hat is, the scope o" the "unction is restricted to the class-name
speci0ed in the header line. !he sym$ol :: is called the scope resolution operator.
For instance, consider the mem$er "unctions *et(!t!,- and $ut(!t!,- as discussed
a$ove. !hey may $e coded as "ollowsA
void ite+ A A getdata= int a, Koat $ ;
T num$er W aL
cost W $L
V
void ite+ A A putdata= void;
T cout OO ?9um$er A ? OO num$er OO
?Un@L cout OO ?Cost A ? OO cost OO
?Un@L
V
Note: !he mem$er "unctions have some special characteristics that are o"ten used in the
program
development. !hese characteristics areA
:everal di6erent classes can use the same "unction name. !he Cmem$ership la$el will
resolve their scope.
*em$er "unctions can access the private data o" the class. . non-mem$er "unction
cannot do so. =&owever, an e%ception to this rule is a friend function;.
. mem$er "unction can call another mem$er "unction directly, without using the dot
operator.
30
In#i(e the 'l!## (e7nition:
Be can de0ne a mem$er "unction inside the class de0nition. Bhen a "unction is de0ned
inside the a class, it is treated as an inline "unction. 9ormally, only small "unctions are de0ned
inside the class de0nition. For e%ample the ite+ class as "ollowsA
class ite+
T int num$erL
Koat costL
pu$lic
A
void getdata=int a, Koat $;L DDdeclaration
voi( $ut(!t!,voi(-
?? (e7nition in#i(e the
'l!##
X
'outBBnu+/e"BBJSnJE
'outBB'o#tBBJSnJE
Y
VL
Ne#tin* of Me+/e" fun'tion# :
. mem$er "unction can $e called $y using its name inside another mem$er "unction o"
the same class. !his is known as nesting o" mem$er "unctions.
P"iv!te Me+/e" fun'tion#:
'n some situations, we may reGuire certain "unctions to $e hidden "rom outside calls.
Be can place these "unctions in the private section.
DQ 3%ample program "or Ne#tin* of
+e+/e" void sample AA update= ;
fun'tion !n( $"iv!te +e+/e"
fun'tion. QD T
Sinclude Oiostream.hN read= ;L
DD 9esting o" mem$er
"unction.
Sinclude Oconio.hN
DD :imple call, 9o o$4ects
used.
class sample V
T void sample AA write=void;
int mL T
void read=void;L DD ,rivate mem$er cout OO ^* value is A ^ OO m OO^Un^L
DD "unction declaration. V
$u/li'A void main= ;
void update= void ;L T
sample
:L
void write= void ;L clrscr=;L
VL
:.read= ;
L DD!his "unction call wont work.
DD <$4ects cannot access private
void sample AA read= ; DD mem$ers.
T :.update= ;L
cout OO^3nter a value A ^OO^Un^L
:.write=
;L
cin NN mL getch=;L
V V
ARRALS <IT=IN A C1ASS
!he arrays can $e used as mem$er varia$les in a class.
E6!+$leA 'on#t int sieW10L
'l!## array
T
int aYsieZL DD Ca is int type array
$u/li'A
voi(
setval=voi(;L
voi(
display=voi(;L
VL
!he array varia$le !G I declared as a private mem$er o" the class !""!3 can $e used
in the mem$er "unctions, like any other varia$le.
31
MEMORL A11OCATION 4OR OBJECTS
!he mem$er "unctions are created and placed in the memory space only once when
they are de0ned as part o" a class speci0cation. :ince all o$4ects $elonging to that class use
the same mem$er "unctions, no separate space is allocated "or mem$er "unctions when the
o$4ects are created. <nly space "or mem$er varia$les is allocated separately "or each o$4ect.
:eparate mem$er locations "or the o$4ects are essential, $ecause the mem$er varia$les will
hold di6erent data values "or di6erent o$4ects.
Co++on fo" !ll o/e't#
*em$er "unction 1
*em$er "unction 7
&emory created )hen
%unctions defned
O/e't 1 O/e't & O/e't .
*em$er "unction 1 *em$er "unction 1 *em$er "unction 1
*em$er "unction 7 *em$er "unction 7 *em$er "unction 7
&emory created
)hen
ob*ects
defned
+b*ects in memory
STATIC DATA MEMBERS AND MEMBER 4UNCTIONS:
?P E6!+$le $"o*"!+ to u#e #t!ti' +e+/e"
v!"i!/le int main=;
!n( #t!ti' +e+/e" fun'tion P? T
Sinclude Oiostream.hN test t1, t7L
Sinclude Oconio.hN
'l!## test t1.setcode=;L
T t7.setcode=;L
int codeL
#t!ti' int countL DD static mem$er
varia$le te#t : : #ho%'ount,-E
$u/li'A DDaccessing static "unction
voi( setcode=voi(; test tHL
T tH.setcode=;L
code W >>countL te#t : : #ho%'ount,-E
V t1.showcode=;L
voi( showcode=voi(; t7.showcode=;L
T tH.showcode=;L
cout OO ?o$4ect num$erA@
OOcodeOO@Un@L
V return 0L
#t!ti' voi( showcount=voi(; V
DD static mem$er "unction
T
'outOO@countA@OOcountOO@Un@L
V
VL
int test : : 'ountL
32
St!ti' D!t! +e+/e"#:
. data mem$er o" a class can $e Guali0ed as #t!ti'. :tatic varia$les are normally used
to maintain
value
s
common to the entire class. . #t!ti' mem$er varia$le has certain special
characteristics. !hese areA
't is initialied to ero when the 0rst o$4ect o" its class is created. 9o other initialiation is
permitted.
<nly one copy o" that mem$er is created "or the entire class and is shared $y all the
o$4ects o" that
class, no matter how many o$4ects are created.
't is visi$le only within the class, $ut its li"etime is the entire program.
St!ti' +e+/e" fun'tion:
-ike #t!ti' mem$er varia$le, we also have #t!ti' mem$er "unctions. . mem$er
"unction that is declared #t!ti' has the "ollowing propertiesA
. #t!ti' "unction can have access to only other static mem$ers ="unction or varia$les;
declared in the
same class.
. #t!ti' mem$er "unction can $e called using the class name =instead o" its
o$4ects; as "ollowsA class-name , , function-name-
'n the e%ample program, the #t!ti' "unction #ho%'ount,- displays the num$er o"
o$4ects created till the moment. . count o" num$er o" o$4ects created is maintained $y the
#t!ti' varia$le count.
!he "unction #ho%'ount,- displays the code num$er o" each o$4ect.
ARRALS O4 OBJECTS
Be can have arrays o" varia$les that are o" the type class. :uch varia$les are called
arrays o" o$4ects. Consider the "ollowing class de0nitionA
class e+$lo3ee
T
char
nameYH0ZL
Koat ageL
pu$licA
void
getdata=void;L
void
putdata=void;L
VL
!he identi0er e+$lo3ee is a user-de0ned type and can $e used to create o$4ects that
relate to di6erent categories o" the employees.
employee
+!n!*e"YHZL
employee
fo"e+!nY1#ZL
employee
%o"2e"Y)#ZL
!he array +!n!*e" contains three o$4ects=managers;, namely, +!n!*e"Y0Z,
+!n!*e"Y1Z and +!n!*e"Y7Z, o" type e+$lo3ee class. :imilarly, the fo"e+!n array
contains 1# o$4ects ="oreman; and the %o"2e" array contains )# o$4ects =workers;.
OBJECTS AS 4UNCTION ARGUMENTS:
-ike any other data type, an o$4ect may $e used as a "unction argument. !his can $e
done in two
waysA
. copy o" the entire o$4ect is passed to the "unction.
<nly the address o" the o$4ect is trans"erred to the "unction.
!he 0rst method is called pass-by 'alue. :ince a copy o" the o$4ect is passed to the
"unction, any changes made to the o$4ect inside the "unction do not a6ect the o$4ect used to
call the "unction.
!he second method is pass-by-re%erence. Bhen an address o" the o$4ect is passed, the
called "unction works directly on the actual o$4ect used in the call. !his means that any
changes made to the o$4ect inside the "unction will reKect in the actual o$4ect.
4RIEND1L 4UNCTIONS:
The private members of a class cannot be accessed from outside class. In some situations, C++
allows a common function to be made friendly with two or more classes, thereby allowing the common
function to have access to the private data of these classes. Such a function need not be a member of any
of these classes. The functions that are declared with the keyword friend are known as friend
functions.
0
.
"riend "unction have some special characteristicsA
It i# not in the #'o$e of the 'l!## to %hi'h it h!# /een (e'l!"e( !# f"ien(.
Sin'e it i# not in the #'o$e of the 'l!##9 it '!nnot /e '!lle( u#in* the o/e't
of th!t 'l!##. It '!n
/e invo2e( li2e ! no"+!l fun'tion %ithout the hel$ of !n3 o/e't.
Unli2e +e+/e" fun'tion#9 it '!nnot !''e## the +e+/e" n!+e# (i"e'tl3 !n(
h!# to u#e !n
o/e't n!+e !n( (ot +e+/e"#hi$ o$e"!to" %ith e!'h +e+/e" n!+e ,e.*:
A.6-.
It '!n /e (e'l!"e( eithe" in the $u/li' o" $"iv!te $!"t of ! 'l!## %ithout
!;e'tin* it# +e!nin*.
U#u!ll39 it h!# the o/e't# !"*u+ent#.
!he "unction declaration should $e preceded $y the keyword friend. !he "unction is
de0ned elsewhere in the program like a normal C>> "unction. !he "unction de0nition does not
use either the keyword friend or the scope operator ::
?P E6!+$le $"o*"!+ fo" O/e't# !#
fun'tion void ma%=X_` m, .BC n; DD de0nition o" "riend
!"*u+ent# !n( 4"ien( fun'tion P?
DDand <$4ects as "unction
arguments
SincludeOiostream.hN T
'l!##
.BCL DD "orward declaration i"=m.% NW n.a;
'l!##
X_`
cout OO
m.%L
T else
int %L coutOOn.aL
pu$licA V
void setvalue=int i; T % W iL V
f"ien( Koat ma%=X_`, .BC;L int main=;
DD 1eclaration o" "riend "unction in
class 1 T
VL .BC a$cL
'l!##
.BC a$c.setvalue=10;L
T X_` %yL
int aL %y.setvalue=70;L
pu$licA ma%=%y, a$c;L
void setvalue=int i; T a W iL V
f"ien( Koat ma%=X_`, .BC;L return 0L
VL
DD 1eclaration o" "riend "unction in
class 7 V
RETURNING OBJECTS
. "unction can not only receive o$4ects as arguments $ut also can return them.
E6!+$leA 'o+$le6 sum='o+$le6 c1, 'o+$le6 c7;
T
'o+$le6 cHL DD<$4ect cH is created inside a "unction
cH.% W c1.% >
c7.%L
c7.y W c1.y >
c7.yL
return=cH;L DD +eturns o$4ect cH.
V
'on#t MEMBER 4UNCTIONS
'" a mem$er "unction does not alter any data in the class, then we may declare it as a
'on#t mem$er "unction as "ollowsA
void mul=int, int; 'on#tL
dou$le get[$alance= ;
'on#tL
!he Guali0er 'on#t is appended to the "unction prototypes =in $oth declaration and
de0nition;. !he compiler will generate an error message i" such "unctions try to alter the data
values.
1
CONSTRUCTORS AND DESTRUCTORS
Con#t"u'to" i# ! K#$e'i!l@ +e+/e" fun'tion %ho#e t!#2 i# to initi!li8e the o/e't
of it@# 'l!##.
. constructor is a special method that creates and initialies an o$4ect o" a particular class.
't has the same name as its class and may accept arguments. 'n this respect, it is similar to
any other "unction.
'" you do not e%plicitly declare a constructor "or a class, the C>> compiler
automatically generates a (ef!ult 'on#t"u'to" th!t h!# no !"*u+ent#.
. constructor is declared and de0ned as "ollowsA
DD class with a constructor
class inte*e"
T
int m,nL
pu$licA
inte*e"=void;L DD constructor declared
MM.
VL
integer A A inte*e"=void; DDconstructor de0ned
T
mW0L nW0L
V
!he constructor "unctions have some special characteristics, !hese are A
The3 #houl( /e (e'l!"e( in the $u/li' #e'tion.
The3 !"e invo2e( !uto+!ti'!ll3 %hen the o/e't# !"e '"e!te(.
The3 (o not h!ve "etu"n v!lue#9 not even voi( !n( the"efo"e9 !n( the3
'!nnot "etu"n v!lue#. The3 '!nnot /e inhe"ite(9 thou*h ! (e"ive( 'l!##
'!n '!ll the /!#e 'l!## 'on#t"u'to".
1i2e othe" C++ fun'tion#9 the3 '!n h!ve (ef!ult
!"*u+ent#. Con#t"u'to"# '!nnot /e vi"tu!l.
<e '!nnot "efe" to thei" !(("e##e#.
An o/e't %ith ! 'on#t"u'to" ,o" (e#t"u'to"- '!nnot /e u#e( !# ! +e+/e" o" union.
The3 +!2e Ki+$li'it '!ll#@ to the o$e"!to"# ne% !n( (elete %hen +e+o"3 !llo'!tion i# "e:ui"e(.
PARAMETERIfED CONSTRUCTORS
!he constructors that can take arguments are called parameteried constructors. Be
must pass the initial values as arguments to the constructor "unction when an o$4ect is
declared. !his can $e done in two
waysA By calling the constructor
e%plicitly

By calling the constructor


implicitly
E6!+$l
e:
1
. 'nteger int1 W 'nteger=0,100;L DD3%plicit call
7
. 'nteger int1=0,100; DD'mplicit call
CONSTRUCTOR O\ER1OADING ,o"- MU1TIP1E CONSTRUCTORS IN A C1ASS
C>> ,ermits us to use more than one constructor in the same class. Bhen more than
one constructor "unction is de0ned in a class, we say that the constructor is overloaded.
CONSTRCTORS <IT= DE4AU1T ARGUMENTS
't is possi$le to de0ne constructors with de"ault arguments.
E6!+$leA class comple%
T
Koat %,
yL pu$licA
comple%= Koat real, Koat i+!*FH -E ??Constructor with de"ault
argument
MMM
V
2
DLNAMIC INITIA1IfATION O4 OBJECTS
Class o$4ects can $e initialied dynamically too. !hat is to say, the initial value o" an
o$4ect may $e provided during runtime.
COPL CONSTRUCTOR
. copy constructor is used to declare and initialie an o$4ect "rom another o$4ect. .
copy constructor takes a re"erence to an o$4ect o" the same class as itsel" as an argument.
For e%ample, the statementA
inte*e" I&,I1-E
would de0ne the o$4ect '7 and at the same time initialie it to the
values o" '1. .nother "orm o" this statement is
inte*e" I1 F I1E
!he process o" initialiing through a copy constructor is known as copy
initialiation.
DLNAMIC CONSTRUCTOR
.llocation o" memory to o$4ects at the time o" their construction is known as 1ynamic
construction o" o$4ects. !he memory is allocated with the help o" the new operator.
DQ 3%ample program "or dynamic constructor
and :tring AA a:tring= ;
1estructor QD T
Sinclude Oiostream.hN (elete nameL
Sinclude Ostring.hN V
'l!## :tring
T void main= ;
'h!" QnameL T
int lengthL :tring name1=^Pinayaga ^;L
$u/li'A :tring name7=^College ^;L
:tring='h!" Qs; name1.display= ;L
T name7.display= ;L
length W strlen=s;L V
name W ne% 'h!"Ylength > 1ZL
strcpy= name, s ;L
V
void display=void;
T
cout OO name OO ^Un^L
V
a:tring= ;L
VL
DESTRUCTORS:
. destructor, as the name implies, is used to destroy the o$4ects that have $een
created $y a constructor. -ike a constructor, the destructor is a mem$er "unction whose name
is the same as the class name $ut is preceded $y a til(e,d-. For e%ample , the destructor
"or the class :tring can $e de0ned as shown $elowA
dSt"in*, - X Y
. destructor never takes any argument nor does it return any value. 't will $e invoked
implicitly $e the compiler upon e%it "rom the program to clean up storage that is no longer
accessi$le. 't is a good practice to declare destructors in a program since it releases memory
space "or "uture use.
Bhenever ne% is used to allocate memory in the constructors, we should use (elete
to "ree that memory.
'on#t OBJECTS
Be may create and use constant o$4ects using 'on#t keyword $e"ore o$4ect declaration.
3%ampleA 'on#t *atri% X=m,n;L
.ny attempt to modi"y the values o" m and n will generate compile-time error.
3
/* Program using class, object, member function,
constructors and Destructors for calculating area
and perimeter of a circle */
#include <iostream.h>
#include <conio.h>
class circle
{
private:
foat radius, area, perimeter;
public:
circle() { } //Default constructor circle(foat
r) //Parameterized Constructor
{
radius = r;
area = 0;
perimeter = 0;
}
circle(foat a, foat p, foat r=25)
// Constructor with Default Argument
{
radius = r;
area = a;
perimeter=p;
}
circle(circle & x) //Copy constructor
{
radius = x.radius; area
= x.area; perimeter=
x.perimeter;
}
void read(); //Member function1 Declaration
// Member function 2 defned inside the
class void display()
{
cout<<"\n\n Given radius is :";
cout<<radius;
cout<<"\n Area of the circle is :";
cout<<3.14 * radius * radius;
cout<<"\n Perimeter of the circle is :";
cout<<2 * 3.14 * radius << endl;
}
~circle()
{ }
//Destructor
};
//Member function1 defned outside the
class void circle::read()
{
cout<<"\n Enter the radius of circle :";
cin>>radius;
}
int main()
{
clrscr();
cout<<"\n Program for calculating area and
perimeter of a circle";
cout<<"\n---------------------------------------";
foat n;
circle C1;
circle C3(0,0);
circle C4[10];
C1.read();
cout << "\n ** Default Constructor **\n";
C1.display(); //
cout<<"\n ** Parameterized Constructor and
Dynamic Initialization of Objects **";
cout<<"\n Enter radius value :";
cin>>n;
circle C2 = circle(n);
C2.display();
cout<<"\n ** Constructor with Default
arguments **";
C3.display();
cout<<"\n ***** Array of Objects *****";
for(int i=0;i<2;i++)
{
C4[i].read();
C4[i].display();
}
circle C5 = C1;
circle C6(C2);
cout<<"\n ***** Copy Constructor *****";
C5.display();
C6.display();
getch();
return 0;
}

OPERATOR O\ER1OADING:
!he mechanism o" giving such special meanings to an operator is known as
operator overloading. Be can overload = give additional meaning to; all the C>>
operators e%cept the "ollowingA
The o$e"!to"# th!t '!nnot /e
ove"lo!(e( !"e: class mem$er
access operators =. , .P;
scope resolution operator=: :;
sieo" operator=#i8eof;
conditional operator=`:;
!o de0ne an additional task to an operator, we must speci"y what it means in relation to
the class to which operator is applied. !his is done with the help o" a special "unction, called
operator function.
Jeneral "orm o" operator "unction isA.
"etu"n t3$e 'l!##n!+e :: o$e"!to" op,!"*u+ent li#t-
X
fun'tion /o(3
Y
where return type is the type o" value returned $y the speci0ed operation and op is the
operator $eing overloaded. !he op is preceded $y the keyword o$e"!to". O$e"!to" op is the
"unction name.
<perator "unctions must $e either mem$er "unctions =non-static; or "riend
"unctions. !he operator "unctions are declared in the class using
prototypes as "ollowsA
vector o$e"!to"+,vector-E DD vector addition u#in* +e+/e" fun'tion
vector o$e"!to"0, -E DD unary minus u#in* +e+/e" fun'tion
f"ien( vector o$e"!to"+,vector9 vector-E DD vector addition u#in* f"ien( fun'tion
f"ien( vector o$e"!to"0,vector Ra-E DD unary minus u#in* f"ien fun'tion
!he process o" operator overloading involves the "ollowing stepsA
1.Create a class that de0nes the data type that is to $e used in the overloading
operation.
7.1eclare the operator "unction operator op) * in the pu$lic part o" the class. 't
may $e either a mem$er "unction or a f"ien( "unction
H.1e0ne the operator "unction to implement the reGuired operations.
O\ER1OADING UNARL OPERATOR: ,An o$e"!to" %ith onl3 one o$e"!n( i# '!lle(
Un!"3 o$e"!to"-
2nary operators are operators that work with only one operand. 3%ample o" unary
operators
include unary plus, unary minus operators=>,-;, increment, decrement operators
=>>,--; etc.,
2nary <perator overloading
2sing mem$er
"unction
A No
!"*u+ent
2sing "riend "unction
A One
!"*u+ent
O\ER1OADING BINARL OPERATOR:,An o$e"!to" %ith t%o o$e"!n(# i# '!lle( Bin!"3
o$e"!to"-
Binary operators are operators that work with two operands. 3%ample o" $inary
operators include arithmetic operators=>,-,Q,D,b;, arithmetic assignment operators=>W, -W,
QW,DW;, and comparison operators
=O, N, OW,
NW,WW, cW;.
2sing mem$er
"unction Binary <perator overloading
A One
!"*u+ent
2sing "riend "unction
A T%o
!"*u+ent#
Rule# fo" Ove"lo!(in* o$e"!to"#:
<nly e%isting operators can $e overloaded. 9ew operators cannot $e
created.
!he overload operator must have at least one operand that is o" user-
de0ned type.
Be cannot change the $asic meaning o" an operator.
<verloaded operators "ollow the synta% rules o" the original operator.
2nary <perator
overloading 2sing mem$er "unction A 9o argument
2sing "riend "unction A <ne argument
2sing mem$er "unction A <ne
argument 2sing "riend "unction A
!wo arguments
Bhen using $inary operator overloading, the le"t hand operand must $e an o$4ect o"
the relevant class.
.
E6!+$le P"o*"!+ fo" Un!"3 o$e"!to" ove"lo!(in*
DQ,rogram "or unary operator overloading Y>>, void spaceAAoperator >>=;
minus=-;Z with mem$er R "riend "unctions. QD T a W >>aL
SincludeOiostream.hN $ W >>$L
SincludeOconio.hN V
class space void operator-=space Rs;
T int a,$L T s.a W -s.aL
pu$licA s.$ W -s.$L
void input=int,int;L V
void display=;L void main=;
void operator>>=;L T space :L
"riend void operator-=space Rs;L clrscr=;L
VL :.input=10,-70;L
void spaceAAinput=int %,int y; :.display=;L
T aW%L >>:L
$WyL :.display=;L
V -:L
void spaceAAdisplay=; :.display=;L
T coutOO^a value is ^ OOaOOendlL getch=;L
coutOO^$ value isA ^OO$OOendlOO^Un^L V
V
E6!+$le $"o*"!+ fo" /in!"3 o$e"!to" ove"lo!(in*
Sinclude Oiostream.hN void matri%AAdisplay=matri% *;
Sinclude Oconio.hN T "or=int iW0LiOsLi>>;
const sW7L T
class matri% "or=int 4W0L4OsL4>>;
T T
int mYsZYsZL coutOOM.+GiIGIOO^Ut^L
pu$lic
A V
matri%=;T V coutOO^Un^L
matri%=int %YZYsZ;L V
matri% operator >=matri% B;L V
"riend matri% operator -=matri% ., matri%
B;L
void display=matri% *;L void main=;
VL T
matri%AAmatri%=int %YZYsZ; int XYZYsZWT11,17,1H,14VL
T "or=int iW0LiOsLi>>; int _YZYsZWT1,7,H,4VL
"or=int 4W0L4OsL4>>; matri% *1=X;L
mYiZY4ZW%YiZY4ZL matri% *7=_;L
V matri% *H, *4L
matri% matri%AAo$e"!to" +,+!t"i6 B- *H W *1>*7L
T matri% CL *4 W *1-*7L
"or=int iW0LiOsLi>>; clrscr=;L
"or=int 4W0L4OsL4>>; coutOO^UnUn *atri% . Un^L
C.+GiIGI F +GiIGI +
B.+GiIGIE *1.display=*1;L
return CL coutOO^UnUn *atri% B Un^L
V *7.display=*7;L
matri% o$e"!to" 0,+!t"i6 A9 +!t"i6 B- coutOO^UnUn *atri% .ddition Un^L
T matri% CL *H.display=*H;L
"or=int iW0LiOsLi>>; coutOO^UnUn *atri% :u$traction Un^L
"or=int 4W0L4OsL4>>; *4.display=*4;L
C.+GiIGI F A.+GiIGI 0 B.+GiIGIE getch=;L
return CL V
V
/
TLPE CON\ERSIONS:
3very e%pression has a type that is determined $y the components o" the e%pression.
Consider the "ollowing statementA
int % W #.# D 7 L DD % contains 7, the "raction part is lost.
1ata can $e lost when it is converted "rom a higher data type to a lower data type.
C!#t#: Be can "orce an e%pression to $e o" a speci0c type $y using a type cast operator. !he
general "ormA
type-name =e%pression;. DDC>> notation
where type is a valid data type.
For e%ample, to make sure that the e%pression %D7 evaluates to type Koat, write
Koat y W #.# D Ro!t ,&-
:ince the user-de0ned data types are designed $y us to suit our reGuirements, the
compiler does not support automatic type conversions "or such data types.
!hree types o" situations might arise in the data conversion $etween incompati$le typesA
1.Conversion "rom $asic type to class type.
7.Conversion "rom class type to $asic type.
H.Conversion "rom one class type to another class type.
T3$e Conve"#ion#
Conve"#ion "e:ui"e( Conve"#ion t!2e# $l!'e in
Basic Class
Sou"'e 'l!## De#tin!tion 'l!##
9ot .pplica$le Constructor
Class Basic Casting <perator 9ot .pplica$le
Class Class Casting <perator Constructor
Conve"#ion fun'tion ? C!#tin*
o$e"!to"
operator t3$en!+e= ;
T MM
MM =Function
statements
V
I+$o"t!nt Note :
1.!he constructors used "or the type conversions take a single argument whose type is to $e
converted.
7.!he casting operator should satis"y the "ollowing conditions A a. 't must $e a class mem$er
$. 't must not speci"y a return type
c. 't must not have any arguments
/*Example program for Type conversion & String String String::operator +(const String &t)
manipulation using binary operator overloading */ { String temp;
class String temp.length = length + t.length;
{ char *name; temp.name = new char[temp.length+1];
int length; strcpy(temp.name, name);
public: strcat(temp.name, t.name);
String() { } return (temp.name);
String(char *s) }
{ length = strlen(s); void main( )
name = new char[length + 1]; {
strcpy( name, s ); char* name1="Vinayaga ";
} char* name2="College";
void display(void) clrscr();
{ cout << name << "\n"; String S1(name1);
} String S2 = name2;
String operator +(const String &t); cout<<"\nGiven Strings are : \n";
operator char*() S1.display( );
{ return(name); S2.display( );
} String S3;
~String(); S3 = S1 + S2;
}; char* N = S3;
String :: ~String() cout<<"The Joined string is : <<N<<"\n";
{ delete name; getch();
} }
0
IN=ERITANCE
C>> support the concept o" reusability. !he mechanism o" deriving a new class "rom
an old one is called inheritance )or derivation*. !he old class is re"erred to as the base
class or super class and new one is called derived class or sub class.
4o"+# of inhe"it!n'e:
1. :ingle 'nheritance =. derived class with only one $ase class;.
7. *ultiple inheritance =. derived class with several $ase classes;.
H. &ierarchical inheritance =<ne $ase class with several derived classes;.
4. *ultilevel inheritance =1eriving a class "rom another C1erived class;.
#. &y$rid 'nheritance =Com$ination o" two or more types o" inheritances;.
A A ) A
) , ) , %
i :ingle inheritance
ii *ultiple
inheritance iii &ierarchical inheritance
A
A
) ) ,
,
%
iv. *ultilevel 'nheritance v. &y$rid inheritance
DE4INING DERI\ED C1ASSES:
'l!## derived-class-name : visi$ility-mode /!#e0'l!##0n!+e
T MMDD
MMDD mem$ers o" derived class
VL
!he colon indicates that the derived-class-name is derived "rom the base.class.
name. !he visibility-mode is optional and, i" present, may $e either private or pu$lic. !he
de"ault visi$ility-mode is private. Pisi$ility mode speci0es whether the "eatures o" the $ase
class are privately derived or pu$licly derived.
E6!+$le: class .BC A private X_` ??,rivate
derivation class .BC A pu$lic X_` ??,u$lic derivation
T T
mem$ers o" .BCL mem$ers o" .BC
VL VL
class .BC A X_` ??private declaration $y
de"ault
T
mem$ers o" .BCL
VL
1
Class B
Not inheritable X X Not inheritable
Private
Protected
Public
Class D1 : public B
Class D2 : private B
Private
Private
Protected
Protected
Public
Public
Class X : public D1 : protected D2
Private
Protected
Public
Effect of inheritance on the visibility of members
\i#i/ilit3 of inhe"ite( +e+/e"#
B!#e 'l!##
De"ive( 'l!##
vi#i/ilit3
\i#i/ilit3
Pu/li' (e"iv!tion P"iv!te (e"iv!tion P"ote'te( (e"iv!tion
,rivate 9ot inherited 9ot inherited 9ot inherited
,rotected ,rotected ,rivate ,rotected
,u$lic ,u$lic ,rivate ,rotected
All users
Own member functions
derived class
private
and friendly functions
and classes
member functions
protected
public
2
P"iv!te: !he private mem$ers o" a class can $e accessed only $y the mem$er "unctions o"
that class.
P"ote'te(: !he protected mem$ers o" a class can $e accessed only $y the mem$er "unctions
o" that class, and the mem$er "unctions o" the classes derived "rom it.
Pu/li': !he pu$lic mem$ers o" a class can $e accessed anywhere in the application.
SING1E IN=ERITANCE
A
. derived class with only one $ase class.
)
DQ -a$ 4=a;A 3%ample ,rogram using class derived A pu$lic $ase
:ingle 'nheritance QD T int yL
pu$lic
A
Sinclude Oiostream.hN void sety=int n;
Sinclude Oconio.hN T
y W nL
class $ase V
T int %L void showy = ;
pu$licA T
void set%=int n; coutOO^_ W ^OOyOO^Un^L
T V
% W nL VL
V void main=;
void show% = ; T
T derived 1L
coutOO^X W ^OO%OO^Un^L 1.set%=10;L
V 1.sety=70;L
V
L clrscr=;L
coutOO^:ingle 'nheritance program Un^L
1.show%=;L
1.showy=;L
getch=;L
V
MU1TI1E\E1 IN=ERITANCE:
. class is derived "rom another derived class is called multilevel inheritance
class . TM.VL DD $ase class
class B A
pu$lic .
TM.VL
DD B derived "rom
.
class C A
pu$lic C
TM.VL
DD C derived "rom
B
Base class Grand father A
Intermediate
) Father
Base class
Derived class Child ,
.0
DQ ,rogram using *ultilevel 'nheritance QD 'l!## (e"ive(& : $u/li' (e"ive(1
Sinclude Oiostream.hN
T int L
Sinclude Oconio.hN
pu$lic
A
'l!## /!#e
void set=int n;
T int %L
T W nL
pu$lic
A
V
void set%=int n;
T % W nL
void show =;
V
T coutOO^` W ^OOOO^Un^L
void show% =;
V
T coutOO^X W ^OO%OO^Un^L
VL
V
VL voi(
+!in,-
'l!## (e"ive(1 : $u/li' /!#e
T
(e"ive(& 1L
T int yL
1.set%=10;L
pu$lic
A
1.sety=70;L
void sety=int n;
1.set=H0;L
T y W nL
clrscr=;L
V
coutOO^*ultilevel 'nheritance
program Un^L
void showy =;
1.show%=;L
1.showy=;L
T coutOO^_ W ^OOyOO^Un^L
1.show=;L
V
getch=;L
VL
V
MU1TIP1E IN=ERITANCE :
Create a new class "rom more than one $ase class is called multiple inheritance.
)-1
)-2
MM )-n
%
*ultiple inheritance
!he synta% o" a derived class with multiple $ase class A
'l!## D A visi$lility B-1, visi$ility B-7M
T MM
=Body o" 1;

VL
3%ample A
class , A pu$lic *, pu$lic 9
T
pu$licA
void display=void;L
V
.1
DQ -a$ 4=$; A ,rogram using *ultiple
'nheritance QD 'l!## (e"ive( : $u/li' /!#e19 $u/li' /!#e&
Sinclude Oiostream.hN T
Sinclude Oconio.hN int L
'l!## /!#e1 pu$licA
T void set=int n;
int %L T
pu$licA W nL
void set%=int n; V
T void show =;
% W nL T
V coutOO^` W ^OOOO^Un^L
void show% =; V
T VL
coutOO^X W ^OO%OO^Un^L
=IERARC=ICA1 IN=ERITANCE: <ne $ase class many su$ class is called hierarchical
inheritance. !he $ase class will include all the "eatures that are common to the su$classes. .
su$class can $e constructed $y inheriting the properties o" the $ase class.
A
V void main=;
VL T
'l!## /!#e& derived 1L
T 1.set%=10;L
int yL 1.sety=70;L
pu$licA 1.set=H0;L
void sety=int n; clrscr=;L
T
coutOO^*ultiple 'nheritance program
Un^L
y W nL 1.show%=;L
V 1.showy=;L
void showy =; 1.show=;L
T getch=;L
coutOO^_ W ^OOyOO^Un^L V
V
VL
) , %
=LBRID IN=ERITANCE: Com$ination o" two or more types o" inheritances is called hy$rid
inheritance.
student
test sports
result
*ultilevel, *ultiple inheritance
.2
\IRTUA1 BASE C1ASS:
!he Cchild has two direct base classes Cparent1 and Cparent7 which themselves
have a common $ase class Cgrandparent. !he Cchild inherits the traits o" Cgrandparent via
two separate paths. 't can also inherit directly as shown $y the $roken line. !he Cgrandparent
is sometimes re"erred to as indirect base
class.
grandparent
Parent1 Parent2
child
'nheritance $y the Cchild some pro$lem. .ll the pu$lic and protected mem$ers o"
Cgrandparent are inherited into Cchild twice, 0rst via Cparent1 and again via Cparent7. !his
means Cchild C have duplicate set o" the mem$ers inherited "rom Cgrandparent.
Du$li'!tion of inhe"ite( +e+/e"# (ue to +ulti$le $!th# '!n /e !voi(e( /3
+!2in* the 'o++on /!#e 'l!## ,!n'e#to" 'l!##- !# virtual base class %hile
(e'l!"in* the (i"e't o" inte"+e(i!te /!#e 'l!##e#.
class . DD grandparent
T
MM
MM
VL
class B1Avirtual pu$lic . DD parent1
T
MM
MM
VL
class B7 A pu$lic virtual . DD parent7
T
MM
MM
VL
class C A pu$lic B1, pu$lic B7 DD child
T
MM DD only one copy o" .
M... DD will $e inherited
VL
Bhen a class is made a virtual $ase class, c>> takes necessary care to see that only
one copy o" that class is inherited, regardless o" how many inheritance paths e%ist $etween
the virtual $ase class and a derived class.
ABSTRACT C1ASS:
.n a$stract class is one that is not used to create o$4ects. .n a$stract class is designed
only to act as a $ase class to $e inherited $y other classes. 't is a design concept in program
development and provides a $ase upon which other classes may $e $uilt. =3%ampleA Class
/!#e in *ultilevel 'nheritance program;
.3
DQ ,rogram using *ultiple, *ultilevel,
&ierarchical, &y$rid 'nheritance, Pirtual
Base class and ,ure Pirtual "unction,
.$stract class QD
Sinclude
Oiostream.hN
Sinclude Oconio.hN
class GP
T
protectedA
int
%L
pu$licA
virtual void set= ; W
0L virtual void
show= ; T VL
VL
'l!## P1 : vi"tu!l $u/li' GP
T
protectedA
int
yL
VL
'l!## P& : $u/li' vi"tu!l GP
T
protectedA
int
L
VL
'l!## 'hil( : $u/li' P19 $u/li' P&
T
pu$licA
void set= ;
T cout OO ^Un 3nter X value A ^L
cin NN %L
cout OO ^Un 3nter _ value A ^L
cin NN yL
cout OO ^Un 3nter `
value A ^L cin NN L
V
void show = ;
T coutOO^Un X W ^OO%OO^Un ^L
coutOO^Un _ W
^OOyOO^Un ^L coutOO^Un
` W ^OOOO^Un ^L
V
VL
void main=;
T
GP PGE
'hil(
DE G F
WDE
clrscr=;L
coutOO^'nheritance, Pirtual Base
class, ?L coutOO@Pirtual Function
program Un^L
G0A#et,-E
G0
A#ho%,-E
getch=;L
V
.m$iguity may arise in inheritance applications. . "unction with the same inheritance appears
in $oth $ase class and derived classes. Be may solve this pro$lem $y using the scope
resolution operator. For instance, consider the "ollowing situationA
class .
T
pu$licA
void display= ;
T cout OO ?. Un@L V
VL
class B
T
pu$licA
void display= ;
T cout OO ?B Un@L V
VL
void main= ;
T
B $L DD derived class o$4ect
$.display= ;L DD invokes display= ; in class B
$..AAdisplay= ;L DD invokes display= ; in class .
$.BAAdisplay= ;L DD invokes display= ; in class B
V
.
CONSTRUCTORS IN DERI\ED C1ASS:
!he constructor o" the derived class receives the entire list o" values as its arguments
and passes them on to the $ase constructors in the order in which they are declared in the
derived class. !he $ase constructors are called and e%ecuted $e"ore e%ecuting the statements
in the $ody o" the derived constructor. !he general "orm o" de0ning a derived constructor is A
1erived-constructor = .rglist1, .rglist7M. .grlist9,
.rglist=1;
;
$ase1=agrlist1;,
$ase7=agrlist7;,
MM.
argument "or
$ase=9;
$ase9=agrlist9;,
T
$ody o" derived constructor
V
DQ 3%ample program "or Constructors in
1erived classes QD
SincludeOiostream.hN
SincludeOconio.
hN 'l!## one
T
protectedA
int
aL
pu$licA
one=int %;
T
aW%L
V
void show= ;
T
coutOO^Un a value is A
^OOaOOendlL
V
VL
'l!## t%o
T
protectedA
Koat
$L
pu$licA
two=Koat y;
T
$WyL
V
void show1= ;
T
coutOO^Un $ vlaue is A
^OO$OOendlL
V
VL
'l!## th"ee : $u/li' one9 $u/li' t%o
T
protectedA
int
c,dL
pu$licA
th"ee,int 69Ro!t 39int 29int
$-:one,6-9t%o,3-
X
'F2E
(F$E
Y
void show7= ;
T
coutOO^Un c vlaue is A
^OOcOOendlL coutOO^Un d
vlaue is A ^OOdOOendlL
V
VL
void main=;
T
th"ee T,N9 O.H9
1H9 &H-E clrscr= ;L
!.show= ;L
!.show1= ;L
!.show7
= ;L
getch=;L
V
..
POINTERS9 \IRTUA1 4UNCTIONS AND PO1LMORP=ISM
Pol3+o"$hi#+ #i+$le +e!n# one n!+e h!vin* +ulti$le fo"+#.
!here are two types o" polymorphism, namely, 'o+$ile ti+e $ol3+o"$hi#+ !n( "un
ti+e $ol3+o"$hi#+.
4un'tion# and o$e"!to"# ove"lo!(in* are e%amples o" 'o+$ile ti+e
$ol3+o"$hi#+. !he overloaded mem$er "unctions are selected "or invoking $y
matching arguments $oth type and num$er at the compile time. 't means that an
o$4ect is $ound to its "unction call at compile time.
Thi# i# '!lle( e!"l3 o" #t!ti' /in(in* o" #t!ti' lin2in*.
'n "un ti+e $ol3+o"$hi#+, an appropriate mem$er "unction is selected with the help
o" virtual "unctions while the program is running. It i# '!lle( l!te o" (3n!+i'
/in(in* $ecause the
appropriate "unction is selected dynamically at run time. 1ynamic $iding reGuires use o" pointers to
o$4ects.
PO1LMORP=ISM
POINTERS
. pointer is a varia$le that stores the memory address o" another varia$le.
A(v!nt!*e# of u#in* $ointe"#:
pointers allow direct access to individual $ytes in the memory. !hus, data in memory
is
accessed "aster than through ordinary varia$les. !his speeds up the e%ecution o"
programs. ,ointers allow direct access to output devices, like the monitor. !his
speeds up programs that
are graphics intensive.
,ointers allow the program to allocate memory dynamically, only when reGuired,
with the help o" the new operator. !hey also allow the program to "ree the memory
when it is no longer reGuired. !his is done with the help o" the delete operator.
A Pointe" \!"i!/le:
3very $yte in memory is given uniGue address =location num$er; $y the operating
system. !he name o" the varia$le is the location name given to the $yte=s;, in the program.
!he address o" a varia$le is the location num$er o" the 0rst $yte occupied $y the varia$le.
!his address can never $e negative and is usually a very large num$er.
Pointe" to O/e't#:
. pointer can point to an o$4ect created $y a class. <$4ect pointers are use"ul in
creating o$4ect at run time. Be can use the o$4ect pointer to access the pu$lic mem$ers o" an
o$4ect. Consider a class ite+ de0ned as "ollowsA
class item
T
int
codeL pu$licA
void get= ;
T coutOO@3nter code A Un@L
cin NN codeL
V
void show=;
T coutOO@CodeW@OOcodeOO@Un@L V
VL
-et us declare an ite+ varia$le 6 and a pointer $t" to 6 as "ollowsA
item %L
item Qptr W R%L
!he pointer $t" is initialied with the address o" 6. Be can re"er to the mem$er "unction o"
ite+ in two ways, one $y the dot operator and the ob*ect, and another $y the arrow
operator and the ob*ect pointer. !he statements
./
%.get= ;L
%.show=
;L
are eGuivalent to
ptr-Nget= ;L
ptr-Nshow=
;L
since P$t" is an alias o" 6, we can also use the "ollowing methodA
=Qptr;.show= ;L
the parentheses are necessary $ecause the dot operator has higher precedence than the
indirection operator,#
item Qptr W ne% itemL
!his statement allocates enough memory "or the data mem$ers in the o$4ect structure and
assigns the address o" the memory space to $t". !hen $t" can $e used to re"er to the
mem$ers as shown $elowA
ptr-Nshow= ;L
A""!3 of $ointe"# to o/e't#:
Be can create array o" o$4ects using pointers.
class item void main= ;
T T
int codeL item %L
pu$licA item Qptr W new itemY#ZL
void get= ;
??.rray o" # pointers to item
o$4ects
T coutOO@3nter code A Un@L "or=int i W 0L iO#Li>>;
cin NN codeL T
V ptr-Nget= ;L
void show=; ptr-Nshow= ;L
T
coutOO@CodeW@OOcodeOO@U
n@L V V
VL V
Thi# Pointe":
. thi# pointer re"ers to an o/e't th!t 'u""entl3 invo2e# a mem$er "unction. For
e%ample, the "unction call !.#ho%, - will set the pointer Cthi#@ to the !(("e## of the
o/e't !.
3%ample A class one
T
int aL
VL
!he private varia$le a can $e used directly inside a mem$er "unction,
like !F1&.L Be can also use the "ollowing statement to access the
varia$le A thi#0A!F1&..
Bhen a $inary operator is overloaded using a mem$er "unction, we pass only one
argument to the "unction. !he other argument is implicitly passed using the pointer thi#.
<ne important application o" the pointer thi# is to return the o$4ect it points to. For
e%ample, the statement
retu"n Pthi#E
inside a mem$er "unction will return the o$4ect that invoked the "unction. !his statement
assumes importance when we want to compare two or more o$4ects inside a mem$er "unction
and return the invoking o$4ect as a result.
E6!+$le A person R person AA greater =person R %;
T
i"=%.age N
age;
return
%L
else
return QthisL
V
.0
\i"tu!l 4un'tion#
Pirtual "unctions are used to achieve run time polymorphism. !he "unction in $ase class
is declared as virtual using the keyword virtual preceding its normal declaration.
Bhen a "unction is made virtual, &// determines which "unction to use at run time
$ased on the type o" o$4ect pointed to $y the $ase pointer, rather than the type o" the pointer.
!hus, $y making the $ase pointer to point to di6erent o$4ects, we can e%ecute di6erent
versions o" the virtual "unction.
+un time polymorphism is achieved only when a virtual "unction is accessed through a
pointer to the $ase class.
Rule# fo" \i"tu!l 4un'tion#:
Bhen virtual "unctions are created "or implementing late $inding, we should o$serve
some $asic
rules that satis"y the compiler reGuirementsA
!he virtual "unctions must $e mem$ers o" some class.
!hey cannot $e static mem$ers
!hey are accessed $y using o$4ect pointers
. virtual "unction can $e a "riend o" another class
. virtual "unction in a $ase class must $e de0ned, even though it may not $e used.
!he prototype o" the $ase class version o" a virtual "unction and all the derived class
versions
must $e identical. '" two "unctions with the same name have di6erent prototype, C>
> considers
them as overloaded "unctions, and the virtual "unction is ignored.
Be cannot have virtual constructors, $ut we can have virtual destructors.
'" a virtual "unction is de0ned in the $ase class, it need not $e necessarily rede0ned
in the ne%t
o$4ect.
Pu"e \i"tu!l 4un'tion#:
't is normal practice to declare a "unction virtual inside the $ase class and rede0ne it in
the derived classes. !he "unction inside the $ase class is seldom used "or per"orming any task.
't only serves as a placeholder. :uch "unctions are called ?do nothing@ "unctions.
. ?do-nothing@ "unction may $e de0ned as "ollowsA
vi"tu!l voi( #et, -FHE
Su'h fun'tion# !"e '!lle( $u"e vi"tu!l fun'tion.
. class containing pure virtual "unctions cannot $e used to declare any o$4ects o" its
own. .s stated earlier, such classes are called !/#t"!'t /!#e 'l!##e#. !he main o$4ective o"
an a$stract $ase class is to provide some traits to the derived classes and to create a $ase
pointer reGuired "or achieving runtime polymorphism.
.1
<OR[ING <IT= 4I1ES
4ile : . 0le is a collection o" related data stored in a particular area on the disk.
St"e!+ : 't re"ers to a seGuence o" $ytes.
Te6t 7le : 't is a 0le that stores in"ormation in .:C'' characters. 'n te%t 0les, each line o" te%t
is terminated with a special character known as 3<- =3nd o" -ine; character or delimiter
character. Bhen this 3<- character is read or written, certain internal translations take place.
Bin!"3 7le : 't is a 0le that contains in"ormation in the same "ormat as it is held in memory. 'n
$inary 0les, no delimiters are used "or a line and no translations occur here.
'nput :tream
+ead 1ata
1ata input
1isk 0les
P"o*"!+
<utput :tream
Brite 1ata 1ata output
Fig. File input and output
streams
io#
io#t"e!
+
i#t"e!
+
#t"e!+/
uf
o#t"e!
+
7le
io#t"e!+
if#t"e!
+ f#t"e!+
of#t"e!
+ 7le/uf
f#t"e!
+
7le
f#t"e!+ /!#e
St"e!+ 'l!##e# fo" 7le o$e"!tion# ,'ont!ine( in f#t"e!+
7le-
7le/uf A 'ts purpose is to set the 0le $u6ers to read and write.
f#t"e!+/
!#e
A ,rovides operations common to the 0le streams. :erves as the $ase "or
"stream, i"stream
and o"stream class.
if#t"e!+ A ,rovides input operations. Contains open= ; with de"ault input mode
of#t"e!+ A ,rovides output operations. Contains open= ; with de"ault output mode
f#t"e!+
A ,rovides support "or simultaneous input and output operations. Contains
open with
de"ault input mode.
.2
OPENING AND C1OSE A 4I1E
OPENING 4I1E USING CONSTRUCTOR
o"stream fout=-results.;L DDoutput only
i"stream %n=-data.;L DDinput only
OPENING 4I1E USING o$en,-
S3nt!6 : 7le0#t"e!+0'l!## stream-object-
E6!+$le
: of#t"e!+ out%le-
stream-object.o$en,0%lename-E out%le.o$en,5(!t!1J-E
ifstream in%le;
in%le.open(0data1);
MORE OPEN, - 4I1E MODES :
!he general "orm o" the "unction o$en, - with two arguments isA
stream-object.o$en,0%lename9 +o(e-E
!he second argument =called 0le mode parameter; speci0es the purpose "or which the 0le is
opened.
4ile +o(e $!"!+ete" Me!nin*
iosAAapp .ppend to end o" 0le
iosAAate go to end o" 0le on opening
iosAA$inary 0le open in $inary mode
iosAAin open 0le "or reading only
iosAAout open 0le "or writing only
iosAAnocreate open "ails i" the 0le does not e%ist
iosAAnoreplace open "ails i" the 0le already e%ist
iosAAtrunc delete the contents o" the 0le i" it e%ist
.ll these Kags can $e com$ined using the $itwise operator <+ =\;. For e%ample, i" we want to
open the 0le e%ample.$in in $inary mode to add data we could do it $y the "ollowing call to
mem$er "unction open=;A
f#t"e!+ %leE
%le.o$en ,2e#ample!bin29 io#::out a io#::!$$ a io#::/in!"3-E
C1OSING 4I1E
fout.'lo#
e,-E
%n.'lo#e,
-E
DETECTING END0O4 4I1E u#in* if#t"e!+ O/e't :
1etecting o" the end-o" 0le is necessary "or preventing any "urther attempt to read data "rom
the 0le.
3%ample A if#t"e!+ 7nE
7n.o$en,5(!t
!J-E %hile
, 7n -
X 0n.getline=line,9;L
cout OO lineL
Y
.n i"stream o$4ect, such as 0n, returns a value H i" any error occurs in the 0le operation
including the end-o"-0le condition. !hus, the while loop terminates when 7n returns a value H
on reaching the end-o"-0le condition. =!his loop may terminate due to other "ailures as well.;
DETECTING END0O4 4I1E u#in* the +e+/e" fun'tion eof, -:
3%ample A if#t"e!+ 7nE
7n.o$en,5(!t!J-
E %hile
, 7n.eof, -_FH -
X e6it,1-E Y
!he eof , - is a mem$er "unction o" io# class. 't returns a non-ero value i" the end-o"-
0le=EO4; condition is encountered, and a ero, otherwise. !here"ore, the a$ove statement
terminates the program on reaching the end o" 0le.
/0
POINTERS AND T=EIR MANIPU1ATION
3ach 0le has associated pointers known as 7le $ointe"#.
<ne o" them is called the in$ut $ointe" =or get pointer; used "or reading the contents
o" a given 0le location.
!he other is called the out$ut $ointe" =or put pointer; used "or the writing to a given 0le location. Be
can use these pointers to move through the 0les while reading or writing.
4I1E

Def!ult A'tion#
?hello 0le@
<pen "or reading only & 3 - - < B < + - 1
input pointer
<pen in append mode & 3 - - < B < + - 1
="or writing more data;
output
pointer
<pen "or writing only output pointer
Action on %le pointers while opening a %le
4UNCTIONS 4OR MANIPU1ATION O4 4I1E POINTERS :
!he input and output 0le pointers can $e manipulated using the "ollowing mem$er "unctionsA
seekg=; moves get pointer=input; to a speci0ed location
seekp=; moves put pointer =output; to a speci0ed location
tellg=; gives the current position o" the get pointer
tellp=; gives the current position o" the put pointer
!he prototype "or these "unctions isA
:ynta%A #ee2*, o6set, re"position -E
#ee2$, o6set,
re"position -E
!he parameter o6set represents the num$er o" $ytes the 0le pointer is to $e moved "rom the
location speci0ed $y the parameter re"position.
!he re"position takes one o" the "ollowing three constants de0ned in the ios class.
io#::/e* start o" the 0le
io#::'u" current position o" the
pointer io#::en( end o" the 0le
E6!+$le:
%le.#ee2*, 01H9 io#::'u" -E
Pointe" o;#et '!ll#
"out.seekg=0, iosAA$eg;L Jo to start
"out.seekg=0, iosAAcur;L :tay at current position
"out.seekg=0, iosAAend;L Jo to the end o" 0le
"out.seekg=m, iosAA$eg;L *ove to =m>1;th $yte in the 0le
"out.seekg=m, iosAAcur;L Jo "orward $y m $ytes "rom the current position
"out.seekg=-m, iosAAcur;L Jo $ackward $y m $ytes "rom the current position
"out.seekg=-m, iosAAend;L Jo $ackward $y m $ytes "rom the end.
/1
SEgUENTIA1 INPUT AND OUTPUT OPERATIONS ON
4I1ES $ut,- !n( *et,- fun'tion
!he "unction put=; writes a single character to the associated
stream. !he "unction get=; reads a single character "orm the
associated stream.
E6!+$leA 'h!" 'hE
%le.*et,'
h-E
%le.$ut,'
h-E
%"ite,- !n( "e!(,- fun'tion :
write=; and read=; "unctions write and read $locks o" $inary data.
E6!+$le: in%le."e!(,,'h!" P- W obj9
#i8eof,obj--E out%le.%"ite,,'h!"
P- W obj9 #i8eof,obj--E
UPDATING A 4I1E : RANDOM ACCESS
2pdating is a routine task in the maintenance o" any data 0le. !he updating would
include one or
more o" the

"ollowing tasksA
1isplaying the contents o" a 0le.
*odi"ying an e%isting item.
.dding a new item.
1eleting an e%isting item.
!hese actions reGuire the 0le pointers to move to a particular location. !his can $e done
i" we have a collection o" itemsDo$4ects o" eGual lengths.
First, we should 0nd the sie o" each o$4ect $y using the statement
int o/e'tClen*th F #i8eof,o/e't-E
!hen, the location o" a desired o$4ect, say the mth o$4ect, may $e o$tained as "ollowsA
int lo'!tion F + P o/e'tClen*thE
!he lo'!tion gives the $yte num$er o" the 0rst $yte o" the mth o$4ect. 9ow, we can set
the 0le pointer to reach this $yte with the help o" seekg= ; or seekp= ;.
Be can also 0nd out the total num$er o" o$4ects in a 0le using the o$4ect[lenth as
"ollowsA
int n F 7leC#i8e ? o/e'tClenthE
!he 0le[sie can $e o$tained using the "unction tellg= ; and tellp= ;.
ERROR =AND1ING DURING 4I1E OPERATIONS
<ne o" the "ollowing things may happen when dealing with the 0lesA
1. <pening a 0le "or reading does not e%ist
7. Filename given "or a new 0le already e%ist
H. +eading past the end-o"-0le =3nd-0le condition encountered;
4. !here is not enough space on disk "or storing a 0le.
#. .n invalid 0lename given. =Filename with special characters;
(. +eading a 0le in output mode and Briting a 0le in input mode. =<pening a 0le
with wrong open modes;
3rror handling "unctions
4UNCTION RETURN \A1UE AND MEANING
eo"= ;
returns true =non ero; i" end o" 0le is encountered while
readingL
otherwise return "alse =ero;
"ail= ; return true when an input or output operation has "ailed
$ad= ;
returns true i" an invalid operation is attempted or any
unrecovera$le
error has occurred.
good= ; returns true i" no error has occurred.
/2
3%ample A i"stream in0leL else
in0le.open=?.BC@;L i"= in0le.$ad= ; ;
while=in0le."ail= ;; T
T MM MM = report "atal error ;
= process the 0le ; V
V else
i"= in0le.eo"= ; ; T
T MM in0le.clear= ;L DD clear error state
= terminate program
normally MM
; V
V MM
COMMAND01INE ARGUMENTS
Co++!n( line !"*u+ent# are optional string arguments that a user can give to a
program upon e%ecution. !hese arguments are passed $y the operating system to the
program, and the program can use them as input.
File names may $e supplied as arguments to the main= ; "unction at the time o"
invoking the program. !hese arguments are known as 'o++!n(0line !"*u+ent#.
!he main= ; "unction may take two arguments as shown $elowA
+!in , int !"*'9 'h!" P !"*vG I -
!he 0rst argument !"*' =known as argument counter; represents the num$er o"
arguments in the command line.
!he second argument !"*v =known an argument vector; is an array o" 'h!" type
pointers that points to the command line arguments.
!he sie o" this array will $e eGual to the value o" argc.
E6!+$le A C N e%am data
results argc W H
argvY0Z ---N
e%am argvY1Z
---N data
argvY7Z ---N
results
DQ -a$ # A ,rogram "or create, read and write in 0les
QD
Sinclude Oiostream.hN "or = int i W 0L iO9 L i>>;
Sinclude O"stream.hN T
Sinclude Ostdli$.hN "out OO num$erYiZ OO ^ ^L
Sinclude Oconio.hN V
void main= int argc, char Q argvY Z ;
T "out.close= ;L
int num$erY9Z W
T 11,17,1H,14,1#,1(,1),18,19 VL
clrscr= ;L i"stream 0nL
i" = argc cW 7; 0n.open=argvY1Z;L
T char chL
cout OO ^argc W ^ OO argc OO ^Un^L
cout OO ^3rror in arguments Un^L while=0n.eo"=;WW0;
e%it=1;L T
V 0n.get=ch;L
o"stream "outL cout OO chL
"out.open=argvY1Z;L V
i" = "out."ail= ; ;
T cout OO ^Un Un^L
cout OO ^Could not open 0le ^ 0n.close= ;L
OO argvY1Z OO ^Un^L getch= ;L
e%it=1;L
V V
/3
'mportant ]uestions in C>>
2nit I '
1. B!#i' 'on'e$t# of OOPS.
&. Bene0ts and .pplications <<,s.
.. C>> 'D< :treams 0les
N. 4o"+!tte( 'on#ole I?O o$e"!tion# ,O"- io# 'l!## +e+/e" fun'tion#
M. M!ni$ul!to"#
2nit I ''
O. O$e"!to"# in C++
). <perator ,recedence D .ssociativity
U. E6$"e##ion#
V. \!"iou# Cont"ol St"u'tu"e# in C++
2nit I ''
1H. 4un'tion Ove"lo!(in*9 Inline fun'tion9 4"ien( 4un'tion#
11. P!"!+ete" P!##in* ,C!ll /3 v!lue !n( C!ll /3 "efe"en'e-
1&. Cl!##e#9 O/e't# !n( Me+/e" fun'tion# (e7nition in#i(e the 'l!## !n(
out#i(e the 'l!##
1.. Con#t"u'to"# !n( t3$e# of 'on#t"u'to"#
1N. O$e"!to" Ove"lo!(in*
1#.:tatic data mem$ers and :tatic mem$er "unctions
2nit I 'P
1O. Inhe"it!n'e !n( T3$e# of Inhe"it!n'e#
1Q. Pol3+o"$hi#+9 \i"tu!l fun'tion# !n( $u"e vi"tu!l fun'tion
1U. Thi# $ointe" ,M-
2nit I P
1V. 4ile #t"e!+ 'l!##e#
&H. O$enin* !n( Clo#in* ! 7le
&1. 4ile $ointe"# !n( thei" +!ni$ul!tion#
77.'nput and <utput operations in a 0le and updating a 0le
&.. Dete'tin* en(0of07le !n( E""o" h!n(lin* (u"in* 7le o$e"!tion#
&N. Co++!n( line !"*u+ent#.