Professional Documents
Culture Documents
!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:
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#+:
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#:
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#.