You are on page 1of 57

UNIT-I:

Introduction to Object Oriented Thinkingr- & Object Oriented


Programming : Comparison with ProceQ1,u:al _Programming ,
features of Object oriented paradigm - Merits ,and demerits of
oo methodology; Object model; Elemeots of OOPS , 10
processing.

UNIT-II:
Encapsulation and Data Abstraction - Concept ,of objects : State,
Behavior & Identity of an object; Classes : lde_ntifying clas~es and
candidates for Classes Attributes and Services,Access. modifiers, Static
members of a Class, Instances, Message passing, and Construction
and destruction of Objects.
UNIT-Ill :
Relationships - Inheritance : Purpose and its types, 'is a' relationship;
Association, Aggregation . Concept of interfaces and Abstract
classes.
UNIT-IV:

Polymorphism - Introduction, Method Overriding & Overloading, static


and ru t·1
n rne Polymorphism.
UNIT-V :
Strings E . .
· xcept,onal handling Introduction of Multi-threading and Data
c.ollectio '
ns. Case study like : ATM, Library management system .
UNIT

INTRODUCTION TO O~JECT ORIENTED THINKING·AND


OBJECT ORIENTED PROGRAMMING - COMPARISON
WITH PROCEDURAL PROGRAMMING, FEATURES OF 08JECT
ORIENTED PARADIGM, ·MERITS·AND. DEMERITS OF 00
METHODOLOGY, OBJECT MODELi ELEM_ENTS ~F OOPS,
·I / 0 PROCE,$SING -~.

Q.l. Explain in brief about object oriented (00) thinking.


Ans. An object-oriented programming was developed because limitations
were discovered in the earlier approaches of programming.
In the procedural languages, like C, Pascal, FORTRAN and others, the
statement tells the computer to do something, that is, get some input and after
manipulation display that output. Here, programs are a list of instructions. For
very small programs, there is no need to organize principle. But when programs
become larger, a single list of instructions becomes unwieldy. For this, function
was adopted to make programs more comprehensible. A procedural program
is divided into functions and each function has a clearly defined purpose. The
breaking idea of a program into functions can be extended by grouping a
number of functions together into a larger entity called a module.
As programs grow ever larger and more complex, even tr.e structured
programming approach begins to show signs and strain. The project i·· too complex,
the schedule slips, complexity increases, the schedule slips furth ,r and disaster
ensures. Analyzing the reasons for these failures reveals that there .re weaknesses
in the procedural paradigm. No matter how well the structured programming
approach is implemented, large programs become excessively complex.
There are two related problems -
(i) Functions have unrestricted access to global data.
(ii) Unrelated functions and data, the basis of the procedural
paradigm, provide a poor model of the real world.
4 Object Oriented Programming & M13thorJology (lll•Sem., CS.Branch)
The fundamental idea behind ohjcct-orientcd languages is to combine tni
•nglc unit both data and functions that operate on that data. Such a unit
a s1 d d'
called an object In this sense, we canno~ access ata 1rectly. The data
hidden, so it is safe from accidental alteration.
Therefore, we can say that an object-oriented programming approach l'-a
\Olvc the problem which occur in the procedural-oriented programmingappl'Oaci
The term object•oriented (00) means that we organize software as
collection of discrete object~ that incorporate both data structure and behavioui
This is in contrast to conventional programming in which data structure aOI
behaviour are only loosely connected. There is some dispute about exactly wha
characteristics arc required by an object-oriented approach, but they general~
include four aspects - identity, classification, polymorphism, and inheritance.'
Identity means that data is quantized into discrete, distinguishable entitic·
ca lled object-,. A paragraph in a document, a window on my workstation, an<
the white queen in a chess game arc examples of objects. Fig. 1. J show:
some additional objects. Objects can be concrete, such as ajile in a file system
or conceptual, such as a scheduling policy in a multiprocessing operatini
.,ystcm. Each object has its own inherent identity. In other words, two objec~
dr~ di~tinc:t even if all thei r attribute values arc identical.

\'a ri ahlr 'li;imr Addrr,s


aCrrdil 10000007
a Dr bit
anAccounl
aSavini,Account
13537163
56826358
4520S128
l7J
A Symbol Table A Binary Tree
\
The Gray Tclevlslo1' 1

bl .~
Mike's Bicycle Brian's Bicycle A White Rook
Fig. I. I Objects
Classification means that objects with the same data structure (attributes)
d
ao beh~viour (operations) arc grouped into a class. Paragraph, Monitor, and
ChessP,ece are examples of classes. A class is an abstraction that describes
properti_es i~portant to an application and ignores the rest. Any choice of
classes is arbitrary and depends on application.
. E~ch c_lass describes a possibly infinite set of individual objects. Each
ob~cct 1s said to be a · • ·
n mstance of 1ts class. Each instance of the class has tU
own value for each alt 'b t b h . ·
. . n u c ut s ares the attribute names and operations
with other instances of th , I · f
c c ass. Fig. 1.2 shows two classes and some o
Unit- I 5
its
eir respective instance objects. An object contains an implicit reference to
wn class; "it knows what kind of Bicycle Objects Bicycle Class
ing it is".
Attributes
Polymorphism means that the Frame Size
Wheel Size
ame oper ation may beha ve Gears
ifferently on different classes. The Abstract Material
ove opera tion, for exam ple, Into Operations
Shift
ehaves differently for a Pawn than Move
or the queen in a chess game . An Repair
perat ion 1s an actio n or
ransformation that ·an obje ct
Polygon Class
erforms or is subject to. Right - Polygon Objects
Attributes
ustify , displ ay, and move are Vertices
xamples of operations. A specific Abstract
Border Color
Fill Color
mplementation of an operation by Joto
Operations
certain class is called a method. Draw
ecause an object-oriented operator Erase
Move
s polymorphic , it may have more
han one method implementing it. Fig. 1.2 Objects and Classes
In the real world , an operation is simpl y an abstraction of analogous
ehavio ur acros s different kinds of objects. Each object "knows how" to
erform its own operations . In an object-oriented programming language,
owever, the language automatically selects the correct method to implement
t
an operation based on the name of the operation and the class of the objec
being operated on. The user of an operation need not be aware of how many
methods exist to implement a given polymorphic operation. Developers can
add new classes without changing existing code, as long as they provide
methods for each applicable operation.
Inheritance is the sharing of attributes and operations (features) amon
g
classes based on a hierarchical relationship. A superclass has general infonnation
th subclasses refine and elaborate. Each subclass incorporates, or inherits,
at
all the features of its superclass and its own unique features. Subclasses need
not repeat the features of the superclass. For example, Scrolling Window and
FixedWindow are subclasses of Window. Both subclasses inherit the featur
es
a
of Window, such as a visible region on the screen. Scrol/ingWindow adds
l
scroll bar and an offset. The ability to factor out common features of severa
classes into a common superclass and to inherit the features from the superclass
ca~ greatly reduce repetition within designs and programs and is one of the
rnain advantages of an object-oriented technology.
6 Object Oriented Programming & Methodology (/11-Sem., CS-Branch)

Q.2. IVrite tl,e 11ee,I ofobjec:t oriented program111i11g. (R.GP.V., Dec. 20J
A11s. Refer to Q. I .
Q.3. What is mea11t by object-orie11ted analysis ? What are its beneJitJ
A11s. The definition of an object-oriented analysis model encompasses
description of the static and dynamic characteristics of classes that describe
system or product. This activity is performed by a software engineer. Befo,
we can build an object-oriented system, we have to define th~ classes th
represent the problem to be solved, the manner in which the classes relate 1
and interact with one another, the inner workings of objects and t~
communication mechanisms that allow them to work together. All of the~
things are accomplished during object-oriented analysis.
We cannot build software until we have a reasonable understanding c
the system or product. OOA provides us with a concrete way to represent ou
understanding of requirements and then test that understanding against th
customer's perception of the system to be built.
Object-oriented analysis (OOA) begins with a description of use cases-:
scenario-based description of how actors (people, machines, and other systems:
interact with the product to be built. Class responsibilities-colJaborator (CRc:
modeling translates the information contained in use-cases into a representatioll
of classes and their collaborations with other classes. The static and dynamic
characteristics of classes are then modeled using a united modeling language.
Object-oriented analysis can yield fo11owing benefits -
(i) Maintainabi/fty - Maintainability through simplified mapping
to the real world, which provides for Jess analysis effort, less complexity in
system design, and easier verification by the user.
(ii) Reusability - Reusability of the analysis artifacts which saves
time and costs and depending on analysis method and programming.language.
(iii) Productivity - Productivity gains through direct mapping to
features of object-oriented programming language.
Q.4. What is meant by object-oriented design ?
Ans. The design of object-oriented software requires the definition
multilayered software architecture, the specification of subsystems that per:0
required functions and provide infrastructure support, a descrip~io~ of obJect
tbM form the building blocks of the system, and a descnptton of the
.cqmmunication mechanisms that allow data to flow between layers~ subsyst~ms,
M)() .objects. Object-oriented design accomplishes all of these thmgs. ObJect-
OJie~~ design is performed by a software engineer. .
An object-oriented system draws upon class definitions that are ~enved
1hm1 the analysis model. Some of these de~~itions w!ll have .to be but It from
scratch, but many others may be reused, If appropnate design patterns are
Un it - I 7
·d ( )bJC(t-o n cntc d de
' 'l'" • l ' " , ,ccr si gn cs tublishcs a de sign hluc
,, ' - ''l
11 to dcl ~m e l Ilc OL,.'lJ·CC t-o . 1 ·
print th at en able') a
,, \\ ,II l t- n cnlcu urc lllcc tu rc in
, I
' a man
' l'" ,r u, c . th cn :b y. . . ' I ne r th at
,m pr ov m g ( e ve o pm cn l spec d un l I
'\' ''"nh'' ( en< -p ro du ct qu a lit .y
icl't-ni ,c nt cd ue!-,1gn 1s 1· I d .
('. 1v 1c c mto tw o m aJ.or
1 l, ·r t <.ksign . Sy st em de ncl1..v1t1_. cs
sy st em d~s•gn
l1l\ '' \ l si gn c re ates th e prod
· .. , cr s" th al nc co uc t a rc hi te ct ure de fin
0 1 13 m p I1s . l1c s sp ' {i
ec , ,c sy st I".
in g a
en~", ~Int ar c en ca ps ul at ed em I un c tio'
ns a nd 1dc nt1 fym
' • •
C ( J""I.'~ • by s ub sy ste m s th at re g
,, ste . si de at ea ch la ye r. In
Jd1\1('1l. ·, • rn desi gn co ns id er s th a t s pe c . .
, tl.'rfricl.'. datn m an ag , fi ca t,o n of th re e co m po ne nt s, th e
.
,er In .1 .... (1 em en t fu nc tio n s, an d ta sk m an age
)h1i:c\ ut. :, 1c-11 foc us es o n t \,c m · te rn a l d ct ai· \ f · d · m en t fac ilitie s.
s · d
o m 1v1 ua I cl as se s,
urwu i... t'
1.:~
operatio ns . an d m es sa •
ge de ta ils. de fi ni·n g
An obje ct-o rie nted de
si gn m od e l e nc om pa
~er ,ntcrface de sc ri pt io sses so ft w ar e ar ch itt
n, d_a t~ m an agem en t ct ure,
_ ti·· ~ an d de tai le d de co m po ne nt s, t~sk m an ap ,:m e nt
3d1I '-.;, • sc np ll on s of ea c h cl as
, ch stage . the s to be us ed m th e sys'.:;!m
3 elem e nt s of ob je ct -o . At
\an t, . co rr ec t ne ss . co ri en te d de si gn m od el are re vi ew ed fo r
m pl e te ne ss , a nd co
quir~ men t~ and w ith o ne n s is te nc y w it h cu s to m
an ot he r. er s
Q. 5. H 'h at is ob je ct
or ie nt ed pr og ra ,n m in
t ,ea/world '! g (OOP) ? H ow is it ne
ar to
c Aus. ObJec t-o rie nted
pr
(R.GP.V., D ec . 20 13 )
og ra m m in g is an ap pr
oa ch th at pr ov id es a w
\
modulanzing pr og ra m s by ay of
cr ea tin g pa rt iti on ed m
functi ons that ca n be us em or y ar ea fo r bo th da
ed as te m pl at es fo r cr ta an d
g on demand. Th us, an ea tin g co pi es of su ch m od ul es
ob je ct is co ns id er ed to
1 memof) that sto re s da ta an
be a pa rt iti on ed ar ea of co m pu
d se t of op er at io ns th te r
tne memof) pa rti tio ns at ca n ac ce ss th at da ta
are in de pe nde nt, th e . Si nc e
) d,fierem progra m s w ith ob je ct s ca n be us ed in
o ut m od if ic at io ns . a va ri et y of
ObJect-o n e nted prog ra
m m in g is a pr ac tic al
1 me thodology
th at enco urag es m od ul an d us ef ul pr og ra m m
ar de si in g
data a~ a criti ca l el em e gn an d so ft w ar e re us e. \
nt in th e prog ra m de ve O O P tr ea ts
no\\ frcel) around th e sy lo pm en t an d do es no t
ste m . lt tie s data m or al lo w it to
Jpcrate on It , an d pr
ot ec ts it fr o m ac ci de
e cl os el y to th e fu nc tio
ns th at \
1 ntal m od if ic at io n fr o
'1ncllun~. OO P allo w s m ou ts id e
de co m pos iti on of pr ob
-a.lied 0 bJcc b and th en bu le m in to a nu m be r o
ild s da ta a nd fu nc tio ns f en tit ie s
a ro un d thes e ob je cts.
, The ba~1<.. philo so ph
y of us
~~c '-'orld 1~ com po se d of in te in g o bj ec ts in pr og ra m s is a s im pl e o ne - th at
u1crd ur1: p ra ct in g, cl as sifia bl e an
~ ru am~, to o. ca n us eful d id en tif ia ble ob jects,
IJ 1l\\ dft : dppl
gi
\y be st ru ct ur ed m . .
an d
th is .
11 1 H.:ati o ns se rv e pe op le w ay. S mee all \
'JU d n11n o 1 \ I
• . I
li vi ng in the re al w or ld i -
11 ~ un d- "lt: rt;a w or ld as , th e n that so ft w are
closel y as po ss 1b · · ·
'--a, 1:rl) 1n g de~,g,n ..l le , bo th m 1ts w o rk m·
g an d m ·
- tu p1 og,ram ")imp Iy, o bJC' C t-o .
nc ntt! <l prog ra m m m . g 1.s
a m ore •na tu ra 1,
)
og ram mi ng & Me thodo log y (/11-Se m., CS-Bran ch
8 Oh1er:t On en ted Pr
/i / nv1ronm en t wi ll e
ient£d upprom :h differ from object-based approac
Q.6. Hm-. does oh jed-or 1 f so ft ware syster.
t-o rient
e majo r differen ce s between object-based and objec ertainly going to c
An s. Th
nd implement fut
approaches are as follows -
Ob jec t-o rie nt ed Ap pr oa ch Q.8. W ha t art
Object-based Ap pr oa ch
S ..Vo
object- It inc lud es aJJ th e fea tur es c-,--~ xp /ai.n.
(i) Th e major features of
ta ted by object-based approach
based programming are - da re s of ,Va m e th e cit,
wi th tw o ad di tio na l fe atu
encapsulatio n, da ta hiding, ding.
up of inh er ita nc e an d dy na m ic bin
automatic initialization, clear-
g_
objects and operator overloadin t·~ "'- - W ha t ar e th e
Language s tha t su pp or t ob jec
or t object-
(ii) Languages that su pp s
based programming are ca
lled nted approach ha s all facilitie Ans. Th e bas
tio n, inh eri tan ce , po l
ob jec t-b as ed pr og ram mi ng
encapsula ol lo ws -
or t ism s, an d dy na mi c bi nd in g,
languages. They do not supp ph (i) Em
g. hence, are kn ow n as ob je.ct- or ien
inh eritance and dy na mi c bindin (ii ) Pro
lan gu ag es. (ii i) Da1
ac t da ta a
ta but not It su pp or ts bo th ab str (iv ) Fur
(iii) It supports ab str ac t da id e inh eri tan
cla sse s whic h prov
classes. th e da ta str uc tu
and polym orph ism .
(v ) Da1
es that su pp or t ob j
(iv) The languages tha t su
pp or t Th e languag (v i) Ob_
ar e Ad a 95
ob jec t-b as ed programming oriented approaches (vu) Ne1
+, Sm al lta ~ Ja va ,
are 83 Ad a an d Modu.Ja-2. Modula-3 , C+ (viii) Fo l
n
ar e pr om isi ng ar ea s fo r application of oh je ct -o rie Q. 9. Explain
Q. 7. ~h at
pr og ra mm mg ?
~t po pu lar a~ pli ca tion of object-oriented programming An s. Refer tc
Ans. Th e mo
erf ac e de sig n su ch as wi nd ows. Hundreds of windo
been area of user int d programming tee . Q. J0. W ha t
system ha:~
been develop
as '.or ap
ed
ph
~sin_
ca
g
t1o
the ob jec t-o riente
n of object-oriented program
ming incru ro gr am mi ng far.
Th e pro m1 ~m g are
(ii ) A I and ex pert systems Ans. Some of
( i) Real tim.e system .
. ( iv) Object-orie nted datab
a~ rogramming are
mu lat ,o n an d mo de lin g
(11 1) CS, · Obj
AD/CA M system s (i)
(\) (v i) Office automation
, ramming riented system. 1
r(\ ,iJ Ne ural nct\,ork~and parallel prog
hypermedia. f data or any ite:
. ""') E.x perte \l. hypcrte~t ancJ se r-defined data
>
Real-business ~ystems are oft d en ~u ch more co mphlex and co ntain na lyz ed in ter ms
jec ts w1 1h co mp ! d . .
. more ob ,ca tc attrib_ut es . and met o s. ObJect-on
s, l When a prog
programming is useful in thc y~ e~ 01 ap pli ca tions be ca us e it ca n sim
1
,} • c-0 mplex pro
ble m Th b c ne another. For e.
. c o ~echt-o nented pa rad.igm spra ng from the Ian
, hen the customer
, s ma tured into design • anc l as recl!ntl d·
int o analysis.
·
pli ca tion of ob ·~ . Y mo ve e bank balance.
' Ap .
1ect-on ented pr o)grammrng ar e b~ginning to
·.. ,.,. ~, Th l:. fl C110 1:\ ~ ,. b· - )bJecL" ca n intera
rta nct' in many ari"" ·>
.• •
0 0
1~ct-ori ~nted prog
.w .;1-: _ • :.:~ -.~
\, "

... f ·.::... ••

~
Unit- I 9

nvironment will enable the s~ftware industry to improve not only the quality
f so_ftware. systems but also its productivity. Object-oriented technology is
ertamly gomg to change the way the software engineers think, analyze design
nd implement future systems. '
Q:8. What are the major characteristics ofobject-oriented /angauages ?
xp/am. (R.GP.V., Dec. 2013)
Or
Name the characteristics of object-oriented programming.
(R.GP.V., Dec. 2015)
Or
What are the main characteristics of object-oriented language ?
(R.GP.V., Nov. 2018)
Ans. The basic characteristics of object-oriented programming are as
ollows -
(i) Emphasis is on data rather than procedure.
(ii) Programs are divided into what are known as objects.
(iii) Data structures are designed such that they characterize the objects.
(iv) Functions that operate on the data of an object are tied together
1 the data structure.
( v) Data is hidden and cannot be accessed by external functions.
(vi) Objects may communicate with each other through functions.
(vii) New data and functions can be easily added whenever necessary.
(viii) Follows bottom-up approach in program design.
Q. 9. Explain object oriented programming languages with its features.
(R.GP. V., May 2019)
Ans. Refer to Q.5 and Q.8.
Q.10. What are the various features supported by object-oriented
·ogramming languages ? Explain each of them.
Ans. Some ofthe concepts (or features) used extensively in object-oriented
ogramming are as follows -
(i) Objects - Objects are the basic run-time entities in an object-
:ented system. They may represent a person, a place, a bank account, a table
data or any item that the program has to handle. They may also represent
!r-defined data such as vectors, time and lists. Programming problem is
ilyzed in terms of objects and the nature of communication between them.
When a program is executed, the objects interact by sending messages to
! another. For example, if customer and account are two objects in a program,
n the customer object may send a message to the account object requesting for
bank balance. Each object contains data, and code to manipulate the data.
jects can interact without having to know details of each other's data or code.
,
10 Object Oriented Programming & Methodology (//1-Sem. , CS-Branch)

(ii) Classes-A class is a collection of objects of simjlar type. Obj .


arc variables of the type class. Once a class has been defined, we can ere
any number of objects belonging to that class. Each object is associated w· ~
the data of type class with which they are created. Classes are user-defin
data types. For example, mango, apple and orange are members of the cl '
fruit, if fruit has been defined as a class, then the statement - i
Fruit mango;
where, mango is an object.
(iii) Data Abstraction and Encapsulation - The wrapping up ,
data and functions into a single unit (called class) is known as encapsulatio -1
Data encapsulation is the most striking features of a class. The data is n
accessible to the outside world, and only those functions which are wrapp
in the class can access it. This insulation of data from direct access by
program is called data hiding or information hiding.
Abstraction refers to the act of representing essential features of an obj
without including the background details or explanations. Classes use
concept of abstraction and are defined as a list of abstract attributes such
size, weight and cost, and function to operate on these attributes. Th
encapsulate all the essential properties of the objects that are to bercieat
The attributes are sometimes called data members, because they ho
information. The functions that operate on these data are sometimes call
methods or member functions. Since the classes use the concept of d
abstraction, they are known as Abstract Data Types (ADT).
(iv) Inheritance - Inheritance is the process by which objects
one class acquire the properties of objects of another class. It supports
concept of hierarchical classification. The concept of inheritance provides
idea of reusability. This means that we can add additional features to an exist'
class without modifying it.
Bird

Attributes

Flying Bird Nonflying


Bird
Attributes Attributes

Sw1dlow Penguin Kiwi

Attributes Attributes Attributes

Fig. 1.3 Property l11herita11ce


Ur11t - l 11

hH l':--.amplc. thl: bird 'robi11 · is n purt or the \;luss ' llying bird· whi ch is
i;_:lln :, part nf the dass ' bird ' .

\ (,•) Po~r111orp/1i.~111 - It means the ability lo take more than one fotm i.e.,
i HK' 11amc, multi pk forms ·. In
OP an operation may exhibit Shupe

,fft·n.·nt behaviours in different


l>l'IIW ()
,~t:mccs. Concept of polymor-
h1sm is implemented using the
, l'rloadcd functions and opem- r------- Triangle
c 1rc1c Object Uox Ohjcct
ors . The overloaded member 1 - - - - - - 1 Object

unctions arc 'selected' for Drnw(Cl.l'clc) Drnw (Uox) Drow


(Trl11nglc)
n, oking by matching arguments, _ _ ___,
1th type and number. Fig. 1.4 Polymorphism
(i1i) Dynamic Binding- Binding refers to the linking of a procedure
311 to the code to be executed in response to the call. Dynamic binding (also
nown as late binding) means that the code associated with a given procedure
all is not known until the time of the call at run-time.
(vii) Message Passi11g - An object-oriented program consists of a
et of objects that communicate with each other. The concept of message
assing makes it easier to talk about building systems that directly model or
imulate their real-world counterparts.
Message passing involves specifying the name of the object, the name of
e function (message) and the information to be sent.
(viii) Re11sability - Once a class has been written, created and
ebugged, it can be distributed to other programs for use, this is called reusability.
, n OOP, the concept of inheritance provides the idea of reusability. This means
at we can add additional features to an existing class without modifying it.
is is done by deriving a new class from the existing one. The new class will
nherit the capabilities of the old one, but is free to add new features of its own.
Q. J1. What are t/,e benefits and risks of object-orie11te,I development ?
Or
Write merits and demerits of object-oriente,I programming languages
as compared to procedure-oriente,l languages.
Ans. Object-oriented development is a new way of thinking about sotlware
based on abstractions that exist in the real world. The new technology promises
: greater programmer productivity, better quality of so fl ware and lesser mainlcnath.:e
. cost. The major benefits of object-oriented development are as follow~
(i) Object-oriented syskms can be casily upgrack<l from small to
large system.
(ii) The dat.a centered design approach enabl es us to capturl! 1110n:
,_. details of a model in an implementable form .
· (iii) It is easy t.o partition the work in a project based 0 11 objec ts.
12 Object Oriented Programming & Methodology (/11-Sem., CS-Branch)

(iv) It is pos.5ible to map objects in problems domain to those in the pm Q.13. Write theJet.
( v) It is possible to have multiple instances of an object to co-e · riented languages seJ
without any interference. .
(vi) We can build programs from the s~ndard workin~ ~odules
ranguages are procedu
Ans. Procedure-oi

commumca · te w1·th one another, rather than havmg . to start. wntmg the c ells the computer to d
from scratch. This leads to saving of development time and higher productivi list of instructions. Fea
(vii) Message passing techniques for communication b~tween obj : (i) Emphasi
(ii) Large pre
makes the interface descriptions with external systems much sunpler.
(iii) Most of
(viii) We can eliminate redundant code and extend the use of exist'
(iv) Data mo
code through inheritance. ( v) Functior
(ix) The principle ofdata hiding helps the programmer to build sec (vi) Employ:
programs that cannot be invaded by code in other parts of the program.
Merit - Procedm
(x) Software complexity can be easily managed. 1ist of instructions fort
(xi) We can categorize the object into various classes. into groups. We can 1:
Other advantages are reuse, an emphasis on modeling the real world: the flow of control fr<
consistent and seamless package, naturalness, resistance to chang Demerit - In a 1:
encapsulation and abstraction, etc. used by which functior
Though it is possible to incorporate all these features in an object-orien is that it does not mode
system, their importance depends on the type of the project and the prefere are action-oriented an<
of the programmer. Object-based L:
The specific risks involved in applying object-oriented approach .to supports encapsulatio
software problem include - object based program
(i) Resource Demands- Since an object-oriented prpgram can reg ' (i) Data er
a much greater processing overhead than one written using traditional methociSi (ii) Data hi
°:13Y work more slowly. This is not good from a customer point of view. (iii) Autom
(iv) Operat
(ii) Object-persistan ce-An object's natural environment is in
~ ,a dynamic entity. This is in contrast to traditional data storage in files Languages that i
~,tabases where the natural environment of the data is on external stora based programming I
~~' causes problem when we want objects to persist between runs of binding. Ada is a typi
P.1'9,~m. even more so between different application. Object-orient.
programming feature
. . (iii). C~mplexity - '.he message passing between many objects it
CO.~.~lex a~phcat1on can be difficult to trace and debug. and dynamic binding
by the following stat
. . . 'l, (iv! Reusability- When inheritance is used it is not easy to prod Object-based fe
,_ r ~ .J~ obJects between applications, since it makes their classes cloSt
Merit and De11
t- ·-.~OIJJ'l~,tt<>,th e r~st of th e_hierarchy. Objec t can become application specifi~
:,.-..r, ·
•: <.,: r~usewith mherttance. It 1s extremely cl,. ffit cLilt to coorct mate very 1arge syste Q. I 4. Describe
p rogram.
-. e1z. Write merits and ,lemerils. OJ.,·oh')ect · .
onente,/ methodology, A ns. Procedure
;~ s. Ile.fer to Q.11. (R.G.P. v., Nov. 101_ nt' instructions for th
··.rr..·-' ~
Unit - I 13

Q. /3. JJlrite thefe ature s ofpro.ced11re-orie11ted, objec t-bas ed anti objec t-


riented langu ages separately. Also write merit s and deme rits of
each.

t Ans. Procedure-oriented Lang uage s- C, Pasca l, FORT RAN , and


Jangu ages are proce dural langu ages. That is each statem ent in
simil ar
the langu ~ge
langu age 1s a
\ ells the comp uter to do some thing. A progr am in a proce dural
as follo ws -
) ist of instru ction s. Featu res of proce dure- orien ted langu ages are
(i) Emph asis is on doing thing s.
ons.
(ii) Large programs are divided into smaller progr ams know n as functi
(iii) Most of funct ions share globa l data.
ion.
(iv) Data move openl y aroun d the syste m from funct ion-to funct
( v) Funct ions trans form data from one form to anoth er.
sec-a,•.,.
(vi) Empl oys top-d own appro ach in progr am desig n.
n. ng a
Merit - Proce dure- orien ted progr ammi ng basic ally consi sts of writi
instru ction s
Iist of instru ctions for the comp uter to follow , and organ izing these
repre sent
into groups. We can use a flowc hart to organ ize these actio ns and
the flow of contr ol from one action to anoth er.
is
Demerit - In a large progr am it is very diffic ult to ident ify what data
appro ach
used by which function. Anot her seriou s draw back with the proce dural
se funct ions
is that it does not mode l real world probl ems very well. This is becau
the probl em.
are action-oriented and do not really corre spond to the eleme nts of
rily
Object-based Lang uage s - It is the style of progr amm ing that prima
requi red for
supports encap sulati on and objec t identity. Majo r featu res that are
object based progr ammj ng are as follow s -
(i) Data encap sulati on
(ii) Data hidin g and acces s mech anism s
(iii) Autom atic initia lizati on and clear- up of objec ts
(iv) Oper ator overl oadin g.
objec t-
Langu ages that suppo rt progr ammi ng with objec ts are said to be
and dynam ic
based progr ammi ng langu ages. They do not suppo rt inher itance
bindin g. Ada is a typica l objec t-base d langu age.
ed
Obje ct-or iente d Lang uage s - It incor porat es all of objec t-bas
inher itance
programming featur es along with two additi onal featu res, name ly,
cteriz ed
and dynamic bindi ng. Objec t-orie nted langu age can there fore be chara - ··
by the following statem ents -
Objec t-base d featur es + Inher itance + Dyna mic bindi ng
Merit and Deme rit - Re fe r to Q. 11 .
orie11led
Q. 14. Descr ibe how data are slu,re d by ji,m:tions in a proce d11re-
progr am.
. . Ans. Proce dure- orient ed programmi ng basica lly consists or
w ri11n g a li~t
:lto n:-. 1111 n
of instructions for the comp uter to follow , and organ ii'i ng these instnt<
od Pr,1qro n
1ry1,n.:; "
-
MPl1JO,JL11uyy ',,,-..:.em.. c;s-Branch,,/
•~
'""blo
l' d
-• ( )nf''l l • • Unit - I 15
.
\\ , u, c ,1 tlo" c ha rt to organize these acf
, , n a, (lin, 11,,n, l
•r ,ur' "'h 11
----~ 10111
I 111 s. Object-orie11ted Programmi11g
1:,' .,~ni thr ll,111 ,,1 l·0ntn' ln' Globall>~ Pmcedure-oriented Programming
r, rr. l anNhcr \\ 111 Ir " c No.
,,nc :i,·11,,n II' ' ,
It emphasizes on data rather than It emphasizes on doing things o r
. ,n,cntrate ,,n the Jr, cl,,rim nt
,, er, 1111k attrn11,111 procedure. algorithms.
,,1 tun, 11,,n~. ' - Programs arc decomposed into Large programs are decomposed
e data t11at arc being
J\ ('.1\Cn h' \h F L!lrol Dain Local Data
u,;d t" ,am"us funct1,1ns ·1g. objects. into functions.
. . th"' relation bet11 ccn Data structures used characterize Most of the functions share global
l ~ S h(l \\ ' Fig. l.S Relationship of Daio Olltl the objects. data.
data .and functi,,ns JO a proccdurc- Fu11ctiom; i11 Procedural Prog
11 ,,,_.._il. Data is hidden and cannot be Data move openly around the system
cmented prng:ram. accessed by external functions. from function to function.
m0re, ulnerable to an inadvertent change by 8 (v} OOP follows bottom-up approach POP fo!Jows top-down approach
Global data are
is , erv difficult to I·dcnt1·fy what data 1s ·
used by
In a larce procram 11 . . Id in program design. in program design.
' 1 •' e require 10 revise an extema ata structure, we also
tunct,on. n case. " •
·ons tJ1at access the data. This creates an opportuni
w re, ,se aII fu nCtl · b · th · Q.1 7. W1lat is object oriented programming ? How it is different from
buc~ 10 creep JO . An otller drawbacJ.... of .
this approac 1s at 1t docs not
. • rocedure oriented programming? (R.G.P.V., June 2015)
real "orld problems , el') 11 ell. This 1s because functions are acbon-ori
Ans. Refer to Q.5 and Q.16.
and do not reall) correspond to tlle clements of the problem.
Q. I 8. Wl,at is object oriented programing ? How is it different from
Q.l 5. Hn"' are daJa andfw,clio,rs organized ii, an object orienled
rocedure oriented programming ? What the the uniq11e advantages are of
Ans. Object oriented programming Object bjectorientedprogram? (R.G.P.V., June 2013)
100P) treats data as a critical element Or
10 the program development and does What is object orie11ted programming ? How does it differ from
not pernu1 11to f1011 freely around the tructured programming ? Disc11ss the characteristics of object oriented
-~ stem. It ties data closely to the nguages. (R.G.P.V., June 2016)
tuncuons that operate on it and prevents
11 from moddicat1on from outside Ans. Refer to Q.5, Q.16 and Q.8.
funcuons. OOP decompose a problem Q.19. What are die different types ofmodels ofobject modeling teclmique ?
1010 a number of entities known as xplain briefly.
objects and then build s data and
funcuon near these obJects. The data Ans. The three types of models of object modeling technique are as follows -
of an object can be accessed only by (i) Object Model - Object model describes the structure of objects in a
its funcuons. Ho11 ever. functions ofone stem - their identity, their relationships to other objects, their operations and their
object can access the functions of other ttributes. It provides the essential framework into which the dynamic a11dfunctional
objects. Fig. 1.6 shows the orgamz.ation Fig. 1.6 odels can be placed. We can say that objects are building blocks of model.
ol data and funruons m OOP. The goal in constructing an object model is to capture those concepts from
Q. 16- _What are f undame11ta/ differences between object ori e real world that are important to an application. In modeling an engineering
programmmg and procedure/structured oriented programming ? roblem, the object model should contain terms familiar to engineers~ in modeling
. Or · business problem, terms from the business; in modeling a user interface,
. Differentiate b~1wee11 procedure oriented programming,:and·· nns from the application domain. An analysis model should not contain computer
oriemed programmmg in brief (R.. GP. V., ,lfov. nstructs unless the application being modeled is inherently a computer problem.
Am. The ma_1(,r differences bet\\ een OOP and procedure/s ch as a compiler or an operating system. The design model describes how to
oncntcd programming are as follows - . Ive a problem and may contain computer constructs.
,.,,-i,,nv S Methodology (111-Sem., CS-Bran~.w,, .,1 Unit - I 17
't>...., C'~ .~
), ,. - ,)-.c>' • l .
•t ' · ' lh n:prc,clltl·<l " 111. ObJCCl• dia&nuns con
1 1
•r3rh1, .1
,ni:t·d 111 H, h1cmrc 111cs s 11a nng cooun0 .. 13y mnjor, we mea n 1hot n mode l with o ut any o ne of thc~c d cmt:n l'i ' " not
1 1 , n1 ,,h ' L • •
l:i" ''' ;in .,rr: . • ,, th 1)tlwr l' Ia~Sl:S.· • C lasses define th·" o hJl:Cl-oricn tcd.
L • 1., ...-, J ~f\.• :1, ,\'h. l,J 1l l 1 1
t • • C
,1 , 11,, " .,.
t,;hJ ' ,.,1ir :in • • . . 1 10 , 1:inrc a nd the o pcrnltons which ,..._.11 There a rc three mmor e le mt:nt.s of object model
.,n,1 ,J t,, c:ich ,,1'it , . ........u
(i) Typing (i1) Con c urrency
, 1lu1> ';irnt I ·
· ,r unJ•·~•'t' ' ·
rcrt11f11l' ' . , 1 def _ The dyna mi c mode descnbcs those (iii) Persiste nce.
··1 Drnam1c " . f .
111 • d 1111 umr :ind the seque nc ing o opernti""• By minor, we mean that each of these elements is a useful. but not e sse ntial
, 1 a ,,,tt'ITl u
. ,nccrm· " ,,,t,cn,cs ot• c, cnts. states that defineV\Q the
' i.. ·ham:c,. ,t., part of the object model.
,., .-nL' that ni:ir ' - 13110 n o f e, e nts a nd dstates..
The.dyn ...:_
.
nd tlic on.':lnt ~
-""" Abstraction - A n abstracti on denotes the esse ntia l c harac teris tics of an
1,,• "' cnts.
3
h ··,r•·l·t tir" a sy~tcm that th escnbes. the --,llelci
ntr<1I t at ·• ' object t11at distingui sh it from nil oilier k.inds ofobjects and thus prov ide c risply
, :ir1un> cfl · th 1111 n·cnrd fo r w ha t e operations do• ...a....
thJI t, ·cur. ,, i L - "1111
defined conceptual boundari es, relative to the perspecti ve of the viewer.
,,rx-ratH'"' · h ' " the\ ~ implemented. ,
h . II "th A n abstracti on is o ne of the fundame ntal ways that we as human cope
•'P'·r.!lr on· dia-
--o>--
M t •
c,del 1,. rt·pn:sc
nted grap tea Y w1 stnte
Thr d,11:imtr m s penrutted
• •
in 8 5)-.i wi th complexi ty. An abstracti on foc uses o n the o utside v iew of an object, and
sho", the st:Jtt.' and e vent sequence
models A,..;_· . so serves to separate an o bject's essentia l behaviou r from its impleme ntation.
,utr dt 3 ~f t, .. Statr d,agrams also re fer to the other • • -
,,nc ' d
·Is..~ ('I ('I Jl'CL'
· ~ cc,m-sPond to functions
-
from the funcbona l model ~ Hoa re suggests, "abstract ion arises from a recogniti on o f sim ilarities
· · th b. "'~
th,· ,t:il(' ,acr.irru
• '-.."C\1 me on..•ranons on o bjects m e o ~ect model between ccrtajn objects. situation s, o r processe s in the real world. and the
1
d ~
decision to concentr ate upon these similarit ies and to ignore for the time being
3 <.tllC I S ~ "
..., Funrriorwl Model- A fun ctional
(/// fi .
model isa descri3
.
. of{ the differenc es."
-a s,-stem that tr.lnsform , alues us inc uncllons , mappmg s, ....,
uoa
01 - - Sh~w defines, "a simplifie d descripti on, or specifica tion, of a system that
fun,n~nal dependC'nc,es. e mphas izes som~ of~e system's details or propertie s while s uppressi ng o thers.
The functJonJI modc:ls sho" ho\\ output va lues in a computatiooll'C
A good abstracti on 1s one that e mphasiz es details that are significa nt to the
&c,m mput ,·alues "rthout regard for the order in which the vaJues arc
read~r or _u ser and suppress es details that are, at least for the mo m ent, immater ial
It co!bL'-lS of mulnple data flo" diagram w hic h shows the flow of values or d1vers1o nary."
e\lemal inputs. through operanon and internal data stores, to external
There are the followin g types of abstracti on -
It also sho" s a compu tation and the functiona l derivatio n of tbe
,-alucs in ,1 " 1thout mdicatmg how. when. o r w hy the values are (i) E'!tity Abstr~ct ion -An o bject that represen ts a useful mode l of
The d~nam1c model controls which operations are performe d and the a problem domain or solutton- domain entity.
"h,ch the) are applied. The obj ect model defines the structure of _(ii) Action Abstract ion - An object that provides a generali zed set
the operallon operates on. For batch-like computa tions such as co of operauons, all of which perform the same kind of function .
numencal computat,o ns. the functiona l model is the prim"ary (iii) Virtual Machine Abstract ion - An obiect that gro t th
large system all three models are important. o f th · " ups oge e r
ilera ions ~t ~ all used by some superior level of control or operatio n s that
In funcoonal modeling I.he data flow diagram shows the re a use some Jumor-le vel set of operations .
e~n values in a computation. A data flow diagram is a grapli o
b..•f\1 k
. (iv) Coincide ntal Abstract ion - An o bject that
D3 ta flo11 diagram can be nested h1erarc h1ca lly, but ultimately·the leaf pac ages a se t of
operation s that have no relation to each o ther.
mLI!>t b, specified direct!) as opera tions.
Encapsulation - Encapsul ation is the ~
Q.lO. II 1,ar are the different elements of object model 1 ele men ts of an abstrac tion th at . p ro~ess ot compart mental izing the
(R.GP. V., June 21) c on s t1tute its s truc ture a nd behav iour.
Encaps ulation serves to sepo'""'t th
· • ..," e e contract ual interfa ce O 1· an a b s t.rnc tr•o n
model - and rts impleme ntation.
-Im. There are four maJor elements o f the objec t
I AbstrJcoo n ( 11) Encaps ula tio n Eoc npsulatio n and abstracti on are co m lem
(t
focuses upon tJ1e observab le bel1n . 1· p en tary concepts - abs tracuo n
\fodubnr,- fi v1o ur o an obj , t h
'111 J
(" ) H 1erarchy. oc uscs upon the impleme ntatio n th t . . cc : w ereas e nc nps ula11 o n
a g ives n se to this behaviou r.
M 1/ivdology (/1 /-Sem .. CS-Branch)
r,p,1•~~1m1n<J S i' Unit - I 19
., ,:,,p; ,i.,r•r'i'•' ' . , 1 thr0ti.:.h 111fcm11ation hiding, which
,r, ul.it"'" ,, ni." 1' ,1k11 .1' .1lll \ll ,,btl' l'l , . llicrnrchy - I lterarchy is n ranking or ordering or abstractio n. .
I ii. · , 111 thl' 'l'' rl 1' l' 1 ·111 · · that do· not· contnbute
1 'dd
to its Abstraction is a good thing, but in all except the most tri vial appltcations.
, , ,, ,,1 llllhn~ · • trurtun: l1 I :111 obJeCt ts 11 en, as well
'•h, r r, l l\]ll,Jlh . I1ll ' 11 c: may tind many more difTerent abstraction that we can comp:eh_
h irJ, ll n, 11,, end ~t o ne
,,, ,·nl!:l ' ·
111
,t 11, 11w1h0J, . llml' . Encapsulation helps manage this complex.ity by hiding the ms1dc v1~w of
, , ,mpkn1,•nt:1tH ' , ditfrrcnt abstractions and thus leads
:i 111 • t,:irm·r- :1111,111~ our abstractions. Modularity helps also, by giving us a way to cluster log1_call) \
It pn'I 1J,, C'-P1ll II related abstractions. Modularity helps also, by giving us a way to cluster log1cally
,n ,,f c11n,·cm~
h' , k:ir ,cpar:im h . propcrt, of a system, that has been related abstractions. Still, this is not enough. A set of abstractions often fonns \
. \h1Jul:m1, 1~ t l -
a hierarchy. and by identifying these hierarchies in our design. We greatly
\l odulrn~ - . · • d loosely coupled modules. . \
~et ol ec,hcs1, l an
simplify our understanding of the problem.
Jc-..-,,mro'-"d inw 3 indl\ idual components can reduce
:i.rt1110111nl! proc.r:in1 1010 · h The two important hierarchies in a complex system are -
Toe 3('1 111 r _- ., -Althoueh partitioning a program 1s elpful, \
I) , 11111· J, 1.rn: l-
11, ,·nmrIc'-11") ' ' -•
' . .
uonino prol!l<lm 1s tl1at 1t creates a number (i) Its class structure (the "is a" hierarchy)
• I t Ii ·3u0n lor pa I 11 ~
m,,n- I"'" r rl u JU~ 1 1
::
·d b dancs ",thin the program. The boundaries, (ii) Its object structure (the "part of" hierarchy).
f d do·umenll 0un
,,1 "di Je me . ' bl th . comprehension of the program. Inheritance is the most important "is a" hierarchy, and it is an essential
• :m: , alua e m t
,,r 1n1at:i, c,. 10 f d , id inc. a program into modules which can be
• element of object-oriented systems. Inheritance defines a relationship among
\I 1"1ul:m1a11on consists o t - . dul classs where in one class shares the structure or behaviour defined in one or
b h h ha,e connections with other mo es.
I ·d ,epar3teh. ut " ic . more classes. Thus inheritance represents a hierarchy of abstractions, in which
',,mpi ' · dul • are the assumptions wluch the modules
The conne-:uoos bel\1ecn mo c.:5 a subclass inherits from one or more subclasses. Typically, a subclass augments
mJ.1-e , t,...,ut e:ich other . or redefines the existing structure and behaviour of its superclasses.
-
ObJcct-oncntatwn pro, 1de~ -
modulanty it also provides the assumed
· "'is a'' hierarchy denotes generalization/specialization relationship, "part
r-cm·fil' of mod ulanry. name!) - of" hierarchy describes aggregation relationships .
.
(i) Reusabi/iry - Programs can be a~sembled fr~m ?re-wntten Typing - Typing is the enforcement of the class of an object, such that
, l1m1 .ire com poncnlS
that can be used in many different apphcall_ons. objects of different types may not be interchanged, or at the most, they may
.
(ii) £xte11Sibility - Ne" software compon~n_ts can be wntten or be interchanged only in very restricted ways.
dc,elopcd from e, 1stmg ones w1tliout affecting tl1e ongmal components. The concept of a type derives primarily from the theories of abstract data
· · may be applied to types. A type is a precise characterization of structural or behavioural properties
~k, er c11es ti, e cntena for modularity. These cntena
which a collection of entities all share.
:m, ~re-of ;-stem. but are d111icult to achieve using functional decomposition _
The concepts of type and class are similar, we include typing as a separate
(i) Decomposition - Breaking a system down into manageable urut. clement of object model because the concept of a type places a very emphasis \
(ii) Composabiliry - Modules may be freely combined into oth upon the meaning of abstraction. \
~~stem . Typin~ expresses our abstraction so that the programming language in
(iii) Understandability - Understandin g the part contributes for, which we implement them can be made to enforce design decisions. \
undersundmg the "hole. Concurrency - Concurrency is the property that dist:inouishe s an active
{fr) Continuity - Small changes to tlie system imply small chan
object form one that is not active. ~
10 beha, 1our Fo~ :ertain kinds of problems, an automated system may have to handle \-
many d1tl_erent events simultaneou sly. Other problems may involve so much
M Protection - facep11on and error conditions are confined to computation_tl~at they exceed the capacity of any s ingle processor. In each of
module m "h1ch they occur or affect only closely related modules. I
~hese cases, '.I 1s natural to consider distributed set of computers for the target
All these rntena are met man object-oriented system by virtue of obj 1mplcmentat1o n or to
use processors capable of multitasking.
rd lectmg ,emanticall) cohesl\ e un11S" ith simple interfaces,
hiding their i~t . . ~ single process is the root !Tom which independent dyn;mic action occurs
implementa11on In ~ummal'). modualn1y is easier to achieve using obJ with111 a s~ste~1. Every program has at least one thread of control but
onented techntques. and II 1s therefore. easier to take full advantages of1 syste~ which mvolves concurrency may have many such thread · , a
hent'fit, transllo[) d h s. som1.: are
' '· an ol ers t1iat 1ast the entirl.! Ii fetime of the system's execution .
Mertwdology (/11-Sem .. CS-Branch)
p,voramminQ 6 Unit - I 21
7(1 Ob/Pd onented - ,le c r us allow for lruly concurrcntth,-.1.
...,, ,tcm< c,rcuung 3l·rt"' ·
inullq
, runntn!:'.
, crn a single
CPU can on Iy achieve . · the- Q.21. Disc11ss the formatted 110 operations in detail.
01 . Or
,I "hcf\'3~ s~,tc . f control. usually by means of some func.
, t c0ntn · current thrc3ds " • What are the two ways to formatting 011tput information in C ++ ?
dlus10n ,;,f c0n . . Ans. C++ supports many features that could be used for fonnatting the
·inc alg,,nthm h , )'weieht and lightweight concurrency. A
<l,, - h r-, een c3 - b th output. These features include -
\\ c disungu1sh c: . dependently managed y e target opel'lllli...
hran·"r1gtitpfOCCSSL
< one that 1n r gh 'gh ·-..ug
·1s own address space. A t twet l Process
(i) ios class functions and flags
. t;m. and s0 encompa~ses t (ii) Manipulators
rating system process along with other
(~s h a sin2le ope . . (iii) User-defined output functions.
( alh 1t, es ,11t 10 .-
u. u . which s1,are the same address . .space.. Commurucanoa ios Class Functions - The ios class contains a large number of member
ltl!htweight processes. . generally expensive, mvolvmg some form of
- ht processes is functions that would help us to fonnat the output in many ways. The most
d the communication among 11g · h
amonc hca'}"' eig . . .
- mmun1catton. an twcigbt important ones among them are shown in table 1.1.
d
inter-process co d often involves shared ata.
less e>.pens1ve. an Table 1.1
pr<>Ccsses ts - ' . . the property of an object through which its
.. Pe~isteoce 1s . fte • Function
Persistence - . th obiects continues to exist a r its creator Task
scends ttme (1.e. e J • ft .
e\1!lence tran (' the obiect continues to exist a er tis creator width( ) To specify the required field size for displaying an output value.
. t) and/or space i.e. . fr
(' the object's location moves om the auwQJ •""-
J
ceases to ex~s precision( ) To specify the number ofdigits to be displayed after the decimal
ceases to exisl) and/or space t. e.
·h·ch 11 was created). point of a float value.
,pace in " J k up some amount of space and exists for I fill() To specify a character that is used to fill the unused portion of
A biect in ,oft" are ta es
°'
n -
parttcular amount o ume.
f . The spectrum of object persistence encompasses a field.
the following - setft ) To specify fonnat flags that can control the fonn of output
.
(1) Transient results in expression evaluation. display (such as left-justification and right-justification).
(11) Local ,anables in procedure activations. . unsetft ) To clear the flags specified.
. 1es, d h
(ui) Own vanables, global vanab an eap items whose exlenl · IS Manipulators - Manipulators are special functions that can be included
different from their scope. in the l/0 statements lo alter the format parameters of a stream.
( n ) Data that exists bt:tween executions of a program. To access the manipulators, the file iomanip should be included in the
(, ) Data that exists between various versions of a program. program. Some important manipulator functions are shown in table 1.2 -
(\t) Data that outlines the program . b' Table 1.2
The concept of persistence to the obJect · d I
mo e gtv · es rise to o •
Manipulators Equivalent ios Functio11
onentcd databases. Very few object-oriented programming languages P
direct ,uppon for persistence. Persistence is achieved through 8A) setw( ) width( )
numbn of commerc1al l} a,atlable object-oriente d database. 0 setprecision( ) precision( )
reasonable approach 10 persistence 1s to provide an obJect-onen · · ted s setfill( ) Ii II( )
a rcla11onal databa~e setiosflags( ) set f( )
Pcr-,1~1enct dtJI~ ,1tth more than j ust the life time of data. In, resetiosflags( ) unset f( )
on1:ntc·d .wta
1- ba~c~. not onl) dot e; the state of ·
an obJect pers.1·st' butl
jJi
must also tran,ct'.nd an) 111d1 11dual program. so that every progra11l Width( ) - It is used for specifying the licld size to display an output
this s:n cd ,wtl Ill lhl ' Jtn, ,1 J) Th,~ clearly makes it challenging to The syntax is -
the intcg;rt1} of J datJh,i-c J , II gro11"· pa rti cularly if we must change cout. width(w);
of an obJect.
Methodology (//1-Sem .. CS-Branch)
Programn11ng & Unit - I 23
..,.., Ob eel Onented t ·11 b · ·
u 1 f lunms). The outpu w1 e pnnted 10
{i Id" ,dth (number o co fi Id Fill( ) - It is used to specify a character that is used to fill the unused
"hen: " I~ the ,e d I the right end of the ,e .
·tcrs. "i c :i - portion of a field . The syntax is -
:i field ,1f " c h :irac . .
cout.fill(ch); .
For c'\ampk. - = 3000:
0 where ch represents the character which is used to fill the unused portlOn.
mt a -- 4000· b = 60 · c .
,out width( I0) : For example,
cout .._.._ :i << end I; cout.fill(' • ');
rout. width( 10): cout. width( IO);
cout << b<-. endl: cout << 5250 << " \n";
cou1.width( I 0): The output would be
nd
cout « c« e l: Id b specified for each item separately. C++
Note that the fie ld shou d eIh erore if the specified field width is 1*1*1*1*1*1*1 5 12 15 1°1
h •alues an e r 11 ' ti Setf( ) - It is used to specify the fonnat flags that can control the form
nc, er truncates t e '
1 ' 1
be printed C++ expands the 1eld to fit
, mailer than the size of the va ue o ' of output displayed (such as left-justification and right-justification). The
the value. syntax is -
For example. cout.setf(argl, arg2)
int a = 4852: whe re arg I is one of the formatting flags defined in the class ios and arg2 i_s a
coul. width(2); bit field specifies the group to which the formatting flag belongs. Formattmg
cout << a: flag specifies the format action required for the output.
Output will be - For example,
4852 d. · b d ' l yed coutsetf(ios : : left, ios : : adjustfield);
Precision( ) - It is used to specify the number o_f igtts to e isp a cout.setf (ios: :scientific, ios: :floatfield);
after the decimal point of the float value. The syntax is -
The table 1.3 shows the flags and bit fields for setf( ) function .
cout.precision(d); . .
where d is the number of digits lo the right of the decimal poml Table 1.3
For example, Format Required Flag (argl) Bit-field (argl)
cout.precision(3 );
Left-justified output ios :: left ios :: adjustfield
cout << sqrt (2) << "\n";
cout << 3.14159 << ''\n"; Right-justified output ios :: right ios :: adjustfield
cout << 2.50032 << ''\n"; Padding after sign or ios : : internal ios :: adjustfield
,, ill produce the fo llowing output - base indicator (like + ##20)
1.141 (truncated) Scientific notation ios :: scientific ios :: floatfield
3.142 (rounded to the nearest cent) Fixed point notation ios :: fixed ios :: floatfie ld
2.5 (no trailing zeros) Decimal base ios :: doc ios :: basefield
Octal base ios :: oct ios :: basefield
We can also combine the field specification with the precision setting.
For example, Hexadecimal base ios :: hex ios :: basefield
cout.prec is ion(2):
Managing Output with Manipulators - The header file iomanip provides
cout.w1dth(5);
a set of functions called manipulators which can be used to manipulate the
COUI << 1.2345;
output formats. For example, two or more manipulators can be used in one
The output will be state ment as follows -
cout<< manip I << manip2 << manip3 << item;
cout<< manip I << item I << manip2 << item2;
\
\
24
• & MethodoIogy (
Ob eel Onented programming
1 .
/11-Sem. CS-Branch)
-
'
with the ios functions as lollows - Am·. A stream is a sequence of bytes. It acts as a so11rce from which the
Unit· I 25

We can use mampu\ators


i couLseti lios :: showpoint); input data can be obtained or as a destination to which the output data
can be
\ cout.self lios :: showpos): sent The source stream that provide s data to the program is called the
input
cout « setprccision (4); . . . stream and the destination stream that receives output from the program
is
. fl gs , ios •· scientific). called the 011tp11t stream.
cout << set10s a , .. 5678
"~· 110) « 123.4 In other words, a program extracts the bytes from an input stream
cout << se.. ' We can d es1g · n our ow n and
/user-d efined Manip ulators - ---~--, inserts bytes into an output stream as shown in fig. 1.8.
Custom argumen ts for para-
( custom ized) man_i- Input Stream
mcterittd manlpula lor
Input Extraction
pulator s for certain Device 1 - - - - - - - , from Input
..._.__._-' -.&....1-..& ...L.J-1
special purposes: The & output. arguments-If-an)')
Strttm
syntaX for creating _a estream & mallipulator (ostrtam
custom manipulator lS { mulpDlator caller and
Output Stream
sbovm in fig. l.7. : : : (mulpalater code) stream cascading object
Output Insertion
Device into O utput
The followi ng l ~i..-." trt; u • I t Stream
functio n d e fimes a. F' . J. SyntllX of Crtatm

g a
Custom manrpu a or Fig. 1.8 Data Stream
manipulator called unu ,g 7 The data in the input stream can come from the keyboard or any other storage
that ~~ 1c!:f(ostrcam & output)
device. A stream acts as an interface between the program and the VO
Therefore, a C++ program handles data (VO) independent of the device
device.
used.
{ C++ contains several predefined streams that are automatically opened
output <<"inches";
return output; when a program begins its execution. These include cin and cout, where
cin
} represents the input stream connec ted to the standard input device
(usuall y
The statement the keyboard) and cout represents the output stream connected to the standar
d
cout « 36 << unit; output device (usually the screen).
will produce the following output
Stream Classes - The C++ VO system contains a hierarchy of classes
36 inches that are used to define various streams to deal with both the console and
Q.12. WM/~ C++ streaas 1 ';:''"in with the strtam classes. disk
I files. These classes are called stream classes.
,~v----..- The hierarchy of the stream classes used for input and output operatio

I
Writes/tort note on u, .Nl".... h
(R.GP.V. J,me 2002, Dec. 2008) ns
Or
• .,
with the console uniL These classes are declared in the header file iostream
. . This
D ifiM a stremn. Whal ore tlrt three s/rtlllllS usedfor inplllting, olllplllt
ing file should be included in all the programs that communicate with the console
and ,,:th for inplllting and o111plllting '! (R.GP.V., June 2010, 2016)
unit.

Or
Explain the concept ofstrttuns in C++ 11ndgive the hierarchy ofdifftren
types OJ,rstream.
Or
(R.GP. V., June 2011)
t
__ ..__
Pointer
stnambu r
.I
What are input and output streams ? Explain them with illustrations.
(R.GP.V., June 2012)
Or
U1uu are input and output streams? Give example. (R.GP.V., June 2016)
Or
What are input and output stream s? (R.GP.V., Ju11e 2013)
!stream_ wllhassl&a IMIJum..::wltllaalca
Or oit•_wltbass lp
Write and explain 110 stream ltierarclty in C++. (R.GP.V., Dec. 2012)
Fig. 1.9 Stream Closse sfor Console UO Operat ions
/1/-Sem .. cs-Branch) Unit - I 27
. & Methodology (
26 Ob1ect Onented Programming . t tream) and ostream
· · tream (mpu s ) Formatting llags arc a sci of enum definitions in 10S. TI1ey act as on/off
I r I 9 ios is the base class tor ,s . I eam (input/output strean: . switches that specify cboices for various aspects of input and output format
n ig.. . , . b e classes for ,os r I ne copy of its
(output stream) which arc as . I base class so that on y o and operation. The formatting flags are shown in table 1.5.
The class ios .1s decIared as the. v1rtua
Table 1.5
members arc inherited by the ,osrre~m. ort for fonnatted and unfonnatted
. \ provides the basic supp f Tties for fonnatted and Flag Meaning
The ios c ass vides the ac1 , r: lt d
,; s The istream class pro .d the facilities for ionna e skipws Skip (ignore) whitespace on input
VO opera...on . class prov, es U . t and
" rm:itted input while U,e ostream fa ·1·1ties for handling bo , mpu left Left adjust output [ 12.34 ]
un10 ides the c1
outpuL The class ios1rean1 pr~v th d tails about these classes. right Right adj ust output [ 12.34]
The table I .4 gives e e . internal
output stream- f Console Operations Use padding between sign or base indicator and
Table 1.4 Stream Classes or number[+ 12.34]
Conte11ts dee Convert to decimal
Class Na,ne ed by all other oct Convert to octal
Contains basic facilities that are us
ios hex Convert to hexadecimal
(General input/output input and outpu~ c\assesb.ufferobiect(streambefobject) boolalpha Convert bool to "true" "or" "false" strings
Also comainsapomtertoa ~ sary
stream class) d r, ctions that are neces showbase Use base indicator on output (0 for octal, Ox for hex)
Declares constants an . un d utput operations.
showpoint
fior handling formatted mput f.
an o Show decimal point on output
• th roperties o 10s . () uppercase Use uppercase X. E, and hex output letters (ABCDEF) -
istream lnhents e P . h as get( ), gethne ,
Declares input funcllons sue the default is lowercase
(input stream)
showpos Display+ before positive integers
and read() · erator »
Contains overloaded extracllon op scientific Use exponential format on floating-point output
lnberits the properties of ios . [9.1234E2]
ostream ut functions put( ) and write( )
(output stream) Declares ou tp . << fixed
Contains overloaded insertion operator Use fixed format on floating-point output (912.34]
\lllitbuf Flush all streams after insertion
Inherits the properties of ios istream and o~tre~m
iostream through multiple inheritan_ce and thus contams all stdio Flush stdout, stderror after insertion
(input/output stream)
the input and output functJons There are several ways to set the formatting flags, and different ones can
slreambuf Provides an interface to physical device.c; through buffers
be·set in different ways. All the flags can be set using the setf( ) and unsetf( )
Acts as a base for filebuf class used ios files. . . IOS member functions. Look at the following example -
Q.23. List /OS class format flags and exp/am tl,eir usage by giving cout.setf (ios :: left); // left justify output text
example of eacl,_ cout >> "This text is left-justified";
Or coutunsetf (ios :: left); // return to default
What is the purpose of/OS class ? list /OS class flags and explain their
// right justified
use by giving example.
Many formatting flags can be set _using manipulators.
A 11s. The IOS class is the granddaddy of all the stream classes, and
l conra ins the majority of the features you need to operate C++ stream. The Q.24. How can we create our own-manipulators ?
class !OS provides the basic support for formatted and unformatted l/0
Ans. We can create our own manipulators for certain special purposes.
operations. The three most important features are the formatting flags, the
The general form for creating a manipulator without·any arguments is as
error-status flags and the file operation mode. follows -
I
programming & Methodology (
/11-Sem .. cs-Branch)
5
2a ObJeci Onented
. \ to,.(osu-eam & output)
Umt - 1 29
These classes, designed to manage the disk files, arc declared in fstream I
ostream & man1pu a ,, and therefore we must include this file in any program that uses files.
l The table 1.6 shows the details of file stream classes.
......... (code) Table 1.6
Class Co11Jet11s
return outpu~
) filebuf Its purpose is to set the file buffers to read and write. Contains
ani ulator under creation . For
. ulator is the name of the m p Openprol constant used in the open( ) of tile stream classes.
Here. the marup
Also contains close( ) and open( ) as members.
c.xample - .., ostream & output) fstrearnbase Provides operations common to the file streams. Serves
ostream &. curren c" as a
base for fstream, ifstream and ofstream classes. Contains open( )
t and close( ) functions.
output << ..Rs";
ifstream Provides input operations. Contain s open( ) with default mpul
rerum outpu~
mode. Inherits the functio ns gel( ), getl ine( ). read( ), seekg( )
}
and teUg( ) funcuons from ,stream .
\f we use the statement
ofstream Provides output operations. Contain s open( ) \\ 1th defau lt output
cout << \00 << currency;
mode. Inherits put( ), seekp( }, te lIp( ). and \\ nte( ). functions

p
then the output wi\1 be from ostream.
100 Rs • fistream classes. Gi,•e fstream Provides suppon for simu ltaneous input and output op.:rat, on,
.
Q.25. Give name and description of various Contain s open( ) wi th defa ult inp ut mode 'riherits all th\.'
Jes of its usage. function s from istream and ostream cla:,ses through 10:.trl.'am
aa111p
. Ans. The I/O system of C .
++ has a set of classes that define the file
ofstream and fstream. These classes Examp lc-
handling methods. These incl~de •_fstreaID, The fig. I. l O shows stream #include <fstream .h>
are derived from correspondmg ,ostream c1ass. #include <cstdlib.h>
class for file operations. void error(const ch~p. const ch~p2 = ·· ")
{
los

I
cerr << p << • ' << p2 << '\n';
std : : exit(l);
}
lontn,am
int main(int argc, ch~nr gv[])
istrcam {
Fllr
if (argc ! = 3) error ("wrong number of arguments");
std : : ifstream from (argv[l]); // open input file
// stream
if (!from) error ("cannot open input file", argv[l]);
' std : : ofstream to (argv[2]); // open output
f11.ream
Fi.Ir
lfstnam
r // file stream
if (!to) error ("cannot open output file", argv[2]);
char ch;
I fstreambue while (from.get(ch) to.put (ch); //copy l

//characters I

I
if (!from.cot{) // !to) error ("something strange happened");
Fig. I.JO Stream Classes for File O~rotions (Contained in fttreo,n File)
,, ~
(III-Sem .. cs-Branch)
mmmg & Methodology Unit - I 31
30 Object Onented progra .r
,d o•pes OJ st reams. Give nam e a11d Similar to inserters, we can crea te extractors
by overloading the input >>
26. Write in brief about stream a, (R.G P.V., Dec. 20ll , June 2014) operator relative to a class in which it is used
Q. . The general form of an extractor
. fistreani n,etllods.
description of ,,arious _ Refer to Q.22. function is as follows -
~ Stre d 1\•pe s of Stre am istream & operator >> (istream & stream,
An· am an . class-name & object);
fstre am "- tntbods - Refer to Q.25 .
t• ~

te on ostreana.
Q. 27• Write short no . for convertm .
g va\ues
ueam ) · a mechanism ......... II Body of extractor return stream;
(outp ut strea m ts
Ans. Ano s
• runP:< : into sequence o c
f haracters Usually, these characters diare
of \'anous •ir- . . The ostream class han es
\ tput operations. only Extractors return a reference to stream, whic
then output usi~g \ow~r~:v~ ~: fo\\owing table h is of type istream.
output or insertion acuv1 es.. \ shows. the ~ost b~o ~ deal
The last four functions m ta e . Q.29. Write shor t note 011 files .
used member fun ctions of this c ass. Ans. A file is a colle ction of related data
specifically with disk files. stored in a parti cular area on the
disk. Programs can be designed to perform
Table 17. the read and write operations on
these files .
l Purpose The VO system of C++ handles file oper
Function ations whic h are very much
Formatted insertion for all basic (and similar to the console input and output oper
<< ations. It uses fi le streams as an
overloaded) types. interface between the programs and the files.
The stream that supplies data to
Insert character ch into stream. . the program is known as input stream and the
put(ch) one that receives data from the
Flush buffer contents and ·oser
l
tnewlme. program is known as output stream.
flush( ) Insert SIZE characters from array str
write(str, SIZE) Input Stream

seekp(position)
into file. . fr
Set distance in bytes of file pointer om
Read Data
___.._.._._._...
._._... 1 - - - - - - , Dato Input

start of tile.
seekp(position, seek_dir) Set distance in bytes of file po~ter, from
specified place in file. s~ek-:-~tr can be
.
IOS: :
beg ios .. cur or ios .. end.
, •· '
Return position of file pointer, m.
bytes.
I Write Data
Output Stream
.,.__ _ __, Data Outp ut
pos tellp( )
Fig. 1.11 ]!'i/e Inpu t and Output Stre ams
Q.28. Wrilt! short note on extractors and inser The input operation involves the creation of
ters. an input stream and linking it
. I d the 1/0 operators relative to a class with the program and the input file. Similarly
, the output operation involves
Ans. It is posws1hbl~ t:;v: ~e:~ oad << oper establishing an output stream with the nece
1ha1 we create . ator for outp ut, we are ssary links with the program and
e A · rt has the the output file.
creating an inserter function or simply inser
ter. n rnse er
fo llowing form - Q.30. How explain the stream and fdes in obje
. ct oriented programming ?
ostream & operator << (ostream & stream, class
-name obJect); Ans. Refer to Q.22 and Q.29.
Q.31 . What is file mod e ? Desc ribe the
vari ous file ,nod e opti ons
available.
......... II Body of inserter return stream; . (R.GP. V., Dec. 2016 )
1 Ans. File mode specifies the purpose for
I which the file is opened. The
An inser ter returns a reference to stream, whic general form of opening file with the file mod
h is of type ostre am. e is as follows -
stream-object.open ("filename", mode);
I 32 Obj ect Oriented programming
& Methodology (11/-Sem.,

can take one or more co


nstanlS defined in the
CS-Branch)
Ans. A file can be opened in two ways
Unit - I 33

The file mode parameter fil mode parameters. (i) Using the constructor function of the class.
. Th table I 8 shows the I e (ii) Using the member function open( ) of the class.
c\ass ,os e
Tablet .8 TI1e first method is useful when we use only one file in the stream. The
Meaning second method is used when we want to manage multiple files using one
1 Pa.ram eta stream.
Append to end-of-file . A constructor is used to initialize an object during its creation. Here,
ios :: app a
Go to end-of-file on opening filename is used to initialize the file stream object. The creation and assignm
ios :: ate ent
Binary file of file name to the file stream object involves the following steps -
ios :: binary (i) Create a tile stream object using the appropriate class depending
Open file for reading only .
ios :: in on the typ'e of the file stream require·d.
open f:a,·1s if the file does not ex.1st . (ii) Initialize the file object with the desired filenam e.
ios :: nocreate Open files if the file already exists
ios :: noreplace With the first method , we open the file for output
Open file for writing only . . ofstream outfile("result"); //output only
ios :: out
Delete the contents of the fil e if ,t eXJSts . . and similarly, for input
ios :: tnmc
. .. t take us to the end of the file when it is ifstream infile("data"); //input only
. ..
( i) ios :: app and ,os .. a e ters is that the ,os .. app In the above statements, the outtile is created as an ofstream object that
0 pc
ned. The difference between the two parame
fil Only while ios :: ate mo de pemu·ts manages the output stream. This opens
the "result" file and attached it to the
allows us to add data to the end of..... the e •
:"g data anywhe re in the
fil
e. output stream outfile. The infile is
to modify the ex,,....... declared as an ifstream object and attacfied
us to add data or d nly it to the file data for reading (input).
(ti) The parameter ,os - .. app can be use o with the files capable
•· With the second method, files can be opened using function open( ) to
of outpuL . • th open multiple files that use the same stream object.
.. ning file in ios :: out mode opens 11 m e ios ··•· trunc mode For example, if we want to process a set of files sequentially, we may
(m) pe
0
create a single stream object and use it to open each file as follows -
by default . •rstream implies input and creating a ,
I file-stream-class stream-object;
(iv) Creating a stream using In th cases' mode parame ters are t stream-object.open("filename");
. f stream implies output. ese ' \
stream using O .d
t necessary to prov, e. ·l. The connection with a file is closed automatically when the stream object
no . h
f5tr am class does not prov1 e
.d a mode by default, so we I exprres (w en the program tennma . . )
tes .
(v) Th e e .. h using an object of fstream class.
,·de the mode exphc1t1y w en We can use to disconn ect the files the statements as follows -
must pro, 1 b·twise or
(vi) The mode can combine two or more parameter usmg ' • ·········· ···
.......... ...
operator (symbol I) as follows -
outfile.close( ); //disconnect from outfile
r,out.ope ("data" ios .. app I ios :: nocreate )
n ifstream infile("salary");
, ..
Q.31. Explai11 the process of opening and closi11g a file.
Or infile.close( ); //disconnect from infile
Describe how ca,i files be opened a,rd closed expP.IV.icitJly it1 a2p0rl~gr;~';4)
(R.G .., une , Q.33. What is meant bu initializing of file stream objects '/ W!,at are
11 ,,
I Or input a11d output stream s? Give example. (R.GP.V., Nov. 2019)
. .. . . jil bject

I
Wltat is meant by 1111t1al11 .1ng a , e stream o ? What are the ways Ans. Refer to Q.32 and Q.22.
J 2012)
of doing ii ? Give example code for eacl, of them. (R. GP. V., une
I
nch) Unit - I 35
34 Object Onented Programming & Methodology (111-Sem . CS-Bra
Q.35. Write short h11ote 011 seleci·1011 str11ct11re.
Q.3./. ll'iit<' short not<' o,i contro l statem ent i11 C ++. Ans In C++
. , we ave two types of selec1·ron structure
An.~ The flow of control jumps from one part of the progmm to anoth~
r r.) n .
Program statem ents thJi ,., ,e ifStateme11t - The if statem . . .
depending. on calculations pcrfonn ed in the program . .ent is implemented in two forms -
ing thl (a) Simple if Stat
cau..--e such jumps arc called control statements. One method of achie, emeot - It is in th f; II .
e o owing fonn
t and mainta inable code is to use onl if ( expression is true)
objecti,·e of - an accurate. error resistan
or any combination of the following. three control structure - {
action I ;
(i) Sequence structure (straight line)
lii) Selection structure (branching) action 2;
(tii) Loop structure (iteration or repetition). action 3;
.
(b) If..... else Statem ent_ 1 • 111
Eatr)'
if (expres sion is True) t is the following fonn
ActiD• l {
action I ;
Actlon l
Actio■ l Action?
Acuoa2 else

action 2;
Amoa J
I
Exb action 3;
I Actio■ J
(ii) The Switch Statement _ Thi • .
I: (a) SetfuLnu (b) Selection (c) Loop where, based on a condition th ~ ts a multipl e branching statement
possible_points. This is imple~e:te~ontr~l 1:S transferred to one
Fig. 1.12 I of the many
Jo~/ as o ows -
All program processing_can be coded by using only these three sw1tch(expression)
of these basic contro l constru / {
~ crures. ~e a~proach ofusing one or more
~ programnun~ 1s ~own as strudu redprogramming, an important techniq~
Cl: case I:
{
in software engineenog.
ents then action J•
. C~ supports all the three basic control structures and implem } ,
statements as shown in fig I
· · 13 · This s bows th at Ct,
usingb. vanous control case 2:
paradigm
com mes the power ofstructured programming with the object-oriented {
action 2·
Control Srructurt } ,
case 3:
{
action 3·,
Sequence }
default:
{
action 4·
£1il-<ontrol £ntry-<ontrol } ,
}

I Fig. 1.13 action 5;


od I y (11/-Sem CS-Branch)
36 ObJed Onenred Programming & Meth o og , Umt-1 37
·1h example. #include < iostream.h >
Q.36. £\plain if. if ..- else sl/lltmmt Kil . , if
.. werful decision making\\ 1th I state111l!n1 #include < conio.h >
Ans. C ~ language also gi, es po e flow of execution of statements. The void main()
and if statement 1s used to control th . .
.- d . n control l.llStrucuon. . {
keyword I} lS a ecisto D . g the execusion of a simple 1!
int X, y:
(i) Si.tnplt i[_Sta~emt~:;If ,:~ition is true, the statement blocl
statemenL at fust condinon IS tes Entry
cout << "Enter the first no.":
" ill be e.'(ec.uted. otherwise the s~teme~t cin >> x;
1..; ped and the execunon will
_,, be s... eout << "Enter the second no.";
blockww p
·ump to the statement outside. Flowchart True cin >> y;
~f simple if conlJ'Ol is shown in fig. 1.14. if(x> y)
Exampk- cout << "x is greater no.";
#include <iosneam.h> else
void main() cout << "y is greater no.";
{ getch( );
int num; Nut Statement
cout << "Enter the nwnber"; Fig. J.14 Flowcl,art of Simple
In this example, there are two separate statement-blocks. Jf we can
cm » num; if Control
if (num > == 5) "· enter the first number 5 and second number 6 then check the condition in if
cout « ..number is greater than or equal to 5 , statement-block. if condition is false because 5 < 6 then else statement-blocl-.
getch ( ); will be executed and print massage ''y is greater no:'.
Q.37. Write short 11ote 011 loops in C++ with example.
1 ' ~e run this example. lfwe type number greater than or equal to 5, \I t
II I
J get a message. ·thin {&} If there an
Ans. Loops cause a section of our program to be repeated a certain
It is not required to enclose single statement wt . • , number of times. The repetition continues while a condition is true. When the
more than one statement in statement-block. it would be reqwred to enclos~ condition becomes false, the loops ends and control passes to the statements
following the loop.
within {&}. h
In the above example, statement-block will be executed w en con 1tJo:
d .. f
There are three kinds of loops in C++.
is true, otherwise noL l (i) The for Loop - The for is an entry-controlled loop and is used
(ii) if.._.else Statement - The if... ....... els~ statement is used H- when an action is to be repeated for a predetermined number of times. The for
execute statem_ent-block or a single statement depending on the value of t· loop has three p~i.pal elements -
condition. The rf ... else statement E■try (a) The start condition
contains two statement-blocks.
(b),~c :termination condition
First s1atement-block will be True Falle J (c)·Th~.action which takes place at the end of each iteration.
executed when condition is true, ,
otherwise second statement-block _ ___,__ _..., The format is as follows -
followed by else will be executed. for ( initial value; test; increment)
Flowchart of if .... else control is {
shown in fig. I. I5. Example - action I;
-
Program for greater of two }
Nut Statemuit
number Fig. 1.15 Flowch11rt ofif .... else Con/Ti action 2;

f
I' ' ,
I (Ill Sem CS-Branch) Untt -I 39
~
38 Object Onented Programming & Methodo ogy • . .
1 sed m brackets folio,, mg th~ Example - A program to generate number s I ...... N.
Toe three parts of the statement are enc _o
e arated by semicolons. #include <iostream.h>
word 'for' and that they are s p dis I , the number ].... N. void main ()
£umple - C++ program to p DJ {
#include < iostream.h > int n;
\'Old mainl) cout << ''How many integers to be generated :•· :
t cin > > n;
int n; . Ci?Cl'S be displayed :''; inti = O;
cout << "How many mt - 10 do
cin >> n;
for (mt i = O; i < n; i ++) cout << 1 << cndl:
cout << i << endl; i++;
} . Th 'while' loop is also a loop structure, but ' }
. an
r,,, T1re w#lilt Loop - taXe is as follows -
:1
nv -ntrolled one. The syn }
while (i < n};
,s en~J.......,
while (condition is true) Q.38. Describe the various co11trol statement with example.
{
action 1; (R.G. P. V., May 2019)
Ans. Refer to Q.34, Q.35, Q.36 and Q.37.
}
action 2; Q.39. Explai11 tl,e file pointers a11d the fu11ctio11 for the ma11ipulatio11
•- C*proura ,, fl t JOO odd numbers. of the file poi11ters.
EsampK- ,:, m to generate u l t ,rs
#include < iostream-h > Ans. Each file has two associated pointers that is called lhr: ji/e poimers.
void main () One of them is input pointer or get pointer and the other is output pointer or
{ put pointer. We can use these pointers to move through the tiles while reading
int a, a _max; "· or writing.
cout << "First 100 odd numbers\n ,
When we open a file in read-only mode, input pointer automatically set at
a= I ; the beginning so that we can read the file from start. When we open a file in
a max = 100;
write-only mode, the existing contents are deleted and the output pointer is set
~ile (a<= a_ma.x)
to the beginning. This enables us to write to the file from the start.
{
cout <<"a="<< a << end); "Hdlo" File
a = a+ 2;
'
I
o,.............,i, IHl•ILILl 0 1 lw(o(o(Llol
I Input Polater

I I I I I I -I I I I I I
} (iii) The do-whik Loop - The do-while is an exi~-controll_ed _loop. i
Based on a condition, the control is transferred back to a parncular pomt m the
program. The syntax is as follows -
o.,, ,. .,... . Mod, ff E L L O w O R L D
(for Wrltillg more D1t1)
do Outp•t Pelaler
(
action I;
} Open for Writing only !1-.....11........,_.....,_..__,J,.,.....11........_~----
while (condition is true); 0utput Polotu
action 2;
Fig. I.I 6 Action for File Poin ter While Opening a File
Unit - I 41
40 ObJect Onented Programming & Methodology (/11-Sem.. CS-Bra nch)
re data the file is open in fout.seekg(m, ios :: cur); Go forward by m byte from the current position
lf we wan\ to open ar1 existing filI e to add mo · . fout.scekg(-m, ios :: cur);
'append' mode. This moves the output pointer to the end of the file (1.e .. end Go backward by m bytes from the
current position
of the ex1stmc. contents). fout.seekg(-m, ios :: end);
~ . . F'I p · s _ All the actions on file Go backward by m bytes from the end.
Functions for Mampulation of , e om1er
. b d c It The file stream classes suppon
pointers take place automat.Jcally Y e1-au_• . Q.40. What are the J1mctio11s supported by file stream classes for
the fo\lowinc. functions to manipulate the situations - .fi d •
(i) ~ st<ekg() - h moves get pointer (input) to a spec1_ie 1ocat1on. performing 110 opera.ions ? (R. G. P. V., June 2009, Dec. 20J5)
ii) suh()- It moves put pointer (output) to spec1fi~d location . Or
( ..,, ·· f th get pointer
(iii) tellg() - It gives the current posit.Jon o e . . Illustrate tire/unctions oft~e ifstream and ofstream class for character
(o~ tdlp() - It gives the current position of the put pomtcr. ;,rput a11d output and nunrer,c tnput and output with examples.
(R.G.P. V., Dec. 1010)
For example, A11s. The file stream classes support a number of member functions for
infilc..seekth
filg(IO~; ter to the byte number 10. Note that, the bytes in a perfo~ing the input an~ outp~t operations on files. put( ) and get() functions
It moves e e pom . . . are d~s1gned for _handling a _smgle character at a time. write( ) and read( )
file are numbered beginning from zero. Therefore. the pointer will be pomtmg
functions are designed to wnte and read blocks of binary data.
to the 11th byte in the file.
Now, consider the following statements - put() ~nd get() Func_ti~ns - The function put( ) writes a single character
ofstream fileout; to the assocrat~d stream. Smularly, the_function get( ) reads a single character
fileouLopcn (''heUo", ios : : app}; from the associated stream. The follow mg program shows how these functions
int p = fileouLtellp( }; . . work on a file. First,. the_program requests for a string. On receiving the
On lhc execution ofthese statement, the output pomter IS moved !o the end string, the program wntes 1t, character by character, to the file using the put( )
ofthe file 61ieUo" and the value ofp will represent the number ?(bytes m the file. function in a for loop. for loop is tenninated by using the length of the string.
Seek fimctions seekg(_) and seekp( ) can also be used with two arguments Then, the program displays the contents of the file on the screen. The get( )
as follows - function is used to fetch a character from the file and continues to do so until
seekg(offset, refposition); the end-of-file condition is reached. The character read from the file is displayed
r . setlp(offset, refposition); on the screen using the operator <<.
The parameter offeet represents the number of bytes the~~ poin!er is to //1/0 Operations on Characters
be moved from the location specified by the parameter refpos111on.
#include <iostream.h>
The refposilion takes one of the following three contents defined in the
#include <fstream.h>
ios class -
#include <string.h>
ios : : beg Start of the file
ios : : cur Current position of the pointer int main()
ios : : end End of the file {
The seekg<. ) function moves the associated file's 'get' pointer while seekp(_ ) char string[80];
function mo\'es the associated file's put pointer. l cout <<..Enter a string \n";
The iable I .9 lists some sample pointer offset calls and their actions. foul I cin >> string;
is an ofstream object int len = strlen(string);
Table 1.9 fstream file; // input and output stream
file.open("TEXT', ios :: in I ios :: out);
Seek Call Action for(int i=O; i<len; i++)
fout.seekg(o. ios :: beg); Go to start file.put(string[i]); II put a character to file
fou1.seekg(o, ios :: cur); Stay of the current position file.seekg(0); // go to the start
fouL.seekg( o, ios :: end); Go to the end of file char ch;
fout.seekg(m. ios :: beg); Move to (m + l)th byte in the file wbile(file)
42 Ob,eci Onented Programrron9 & Methodology (/11-Sem . CS-Branch)

file.1?et(ch):
rout- << c.h:
ect 3 character from file
display it on screen
outfile.close( ):
foiiint i=-0; i<4: i++)
heigbt[i] = 0:
ifstream inti le;
close the file for readino
/ clear array from memo~·
Unit- I 43

) in.file.open(filename);
return 0: infile.read((cbar *) & height, sizeoftheieht))·
'
·,rrite( ) and rud( ) Functions - The functions ~nit~( ) and read( ).
unlike the functions put( ) and get( ). band.le the data ID binary fo~. Thi,
foiii=O; i<4; i++)
{
coutsetf(ios::showpoint);
- '

means that the values are stored in the disk. file in the same fonnat m which cout << setw( I0) << setprecision(2)
th~ are stored in the internal memory. Fig. 1.1 7 shows bow an int value 2594 « beight[i];
}
is ~tored in the binary and character I - 2 b~10 --1 infile.close( );
formats. An inl takes two bytes to store its Biliary Format (00001010\0010001 0] return 0;
,-alue in the bin3J)• form irrespccti"e to its }
size_ Buta 4 digit int will take four bytes to Qw-ader Formatl 2 ! l !
5 j
4
1 The output of Program would be -
S10rC it in the character fomL The binary I - 4 b)ffl - l 175.50 153.00 167.25
format is more accurate for storing the Fig. 1.17 Binary and Cltaracter Q.41. Describe the d,is pointer with one example in the conJext ofC++.
numbers as they are stored it in the Formats ofan Jnleger Value Or
character form. Defme tlre term this poinler. (R. G.P. V.. Nov. 20 J9)
The binary format is more accurate for storing the numbers ~ they ~e Ans. C++ programming language has the facility of this pointer. The this
stored in the exact internal rq,resentation. There are no convemons while pointer is automatically passed to any member function, when it is called. 1t is.
saving me da!a and therefore saving is much faster. The binary input and this pointer to the object which generates the function call. For example,
output functions takes the following form - obj.show( );
infilund((cbar4) &V, sizeof(V)); Itis automatically passed a pointer to object obj (the object which invokes
outfile.write((cbar4) &V, sizeof (V)); the call). The automatic pointer is called this pointer.
These functions take two arguments. The first is the address ofthe variable It is clear that we have been using this pointer in the statements of the type -
V. and the second is the length of that variable in bytes. The address of the ol.getdata( ), o2.getdata( ), o3.show( )
\Wble mll5t be cast to type cbar4 (i.e., pointer to character type). Program Here, we·can use the this pointer explicitly.
given below shows how these two functions are used to save an anay of float Fo example,
numbers and then recover them for display on the screen. #include <iostream.h>
class dist
//1/0 Operations on Binary Flies
{
#include <iostream.h> float m;
#include <fstream.h> float cm;
#include <iomanip.h> int mm;
const char • filename = "BINARY"; public :
int main() void getdata (float a, float b, int c)
{ {
float height[4] = {175.5, 153.0, 16725, 160.70} ; this➔m = a;

ofstrearn outfile; this~m = b;


this➔mm = c;
outfile .open( filename):
I outfile.write((char*) & height, sizeoftheight);
}
void show()

. d I (/11-Sem. CS-Branch)
44 ObJect Onented Programming & Metho o ogy ·

l << this➔m << ....


cout < "\n"
« this➔COl << " "
« this➔ mm:

l:
int mam()
l
dist di , d2:
d t .getdata ( 10.2, 20.5. IO);
d2 = di: ,. ·~NCAP~U_LATION AND DATA ABSTRACTION, CONCEPT OF
cout « ''\n The value of object d 1 : ;
' OBJECTS - STATE, BEHAVIOUR AND IDENTITY
d I.show( ): ,, Of AN OBJECT
cout « ..\n The value of object d2 : ;
d2.sbow( );
Q.l. Write short note on e11capsulatio11 i11 OOPs. (R.GP.V., Ju 11e 1015)
}
Toe output would be - Ans. The process of compartmentalizing the elements of an abstraction
that const!tute its structure and beha viour is known as encapsulation;
Toe value of object d I : encapsulation serves to separate the contractual interface of an abstraction
)0.2 20.5 10 and its implementation.
The value of object d2 : Encapsulation is the wrapping up of data and function into a single unit.
10.2 20.5 10 The most important feature of class is data encapsulation; because data is not
When 8 binary operator is overloaded using a membe_r ~c~o~, we pass accessible to the outside world and only those functions which arc wrapped in
only one argument to the function. The oth~r ~eot 1s ~pbc1~ly pa_ssed . the class can access it. This insulation of data from direct access by the
using the pointer this. One important application of the this pointer 1s to l
program is referred to as data hiding or infonnation hiding.
return the object it points to. For example, the statement 1 A process of including in an object everything it needs, hidden from other
return •this; I objects in the system is encapsulation. The internal state of an object is not
inside a member function will return the object that invoked the function. This directly accessible from outside and cannot be changed by external changes
statement assumes importance when we want to compare two or more objects to the application. Likewise, changes to the internal implementation details are
made without affecting the external interface.
inside a member function and return the invoking object as a result. Example-
~erson & person : : greater (person &p) i Q.2.' What are ihe advantages qj encapsulation ?
Ans. The object-·orien~ed class and the objects drawn from class
if p.age > age encapsulate data and the operation·lhat work on ·the data in a single package.
return p; This offers us following advantages -
else (i) The internal implementation details of data and procedures are
return *this: hidden from outside world. This minimizes the propagation of•side effects
when changes occur.
Suppose we invoke this function by the call (ii) Data structure and the operations that manipulate them are merged
max = X.greater (Y); in a single named entity-class. This allows component reuse.
The fu nction will return the object Y if the age of the person Y is grc:ater (iii) Interfaces among encapsulated objects are simplified. An object
than that of X. othern ,sc. it wil l return the object X using pointer this. that sends a message does not require details of internal data structures. Hence,
interfacing is simplified and the system coupling tends to be minimized.
•••• ••••
'
I
46 Objec. O,, ented Programmmg & Methodology (/1/-Sem . CS-Branch)

Q3. Jl ),a,~ ""1o hiding "! H"'4· it~ do~ in t1hjed oriolled p':'grommin!: ?
Unit - II 47

Ans. Abslr.lctJOn refers to the act of representmg e~sential ft.-atures \\ itbout


I
I

Rnat arc tltt tU/lvmtagcs of dllla hiding'! (R.GP.I., June 10131including the background details or ex planauons. Classes use the concept of
3bS
tr11ction and are .defined as a list of abstract attributes such as size. \\•eight
Or -
(R.GP.J(, Nm•. 1019J 311
d cost and fun_c11on to oper~te on these attnbutes. They encapsulate all the
Dqint tlrt' ,~"" dtllll hiding. essential properties of the obJects that are to be created. The attnbutes are
Or
sometimes called data members, because they hold in fonnation. The functions
H'1rat 41, ,~., lflnll by infon,u,tion hiding'! (R.GP.J:, June 1016)
that operate on these data are sometimes called methods or member functions.
-n..-· · fda.... and functions into a single unit called cla_.,s
Since the classes use the concept of data abstraction. they are known as
,.fftS. I UC Y.Tapptng up O "' .
· ~-..,..,,1.,n· Th dam is not accessible to the outside world, and only Abstract Data Types (ADT).
\.S ~ - on. e . Th fun .
"'-~
wvx
functions
· \\·hich are \\=nped
. ..,,
in the class can access 1l ese
Th' · I ·
ct1on~ The process of deciding what parts of a real world object are essenual to
pro,ide the interface bdwecn the objcctS data and the programd d ts:.~~ at1on
modeling the solution to a particular problem is called abstraction. Abstraction
of the data from direct access by the program is calle ala I mg or is the representation of all the essential features of an object. which means its

=
ilifo,...,_,. ltMilrK-
Tbc -
pm·aie.
mcd,anism for hiding data is to put it in a class and make it
data or functions can only be accessed fro_m within the class
possible
type'
and how
states and behaviour~. Th~se are 'encapsulated' into an ·abstract data
which define how all obJects m class (type) of object are to be represented
they behave.

,
' I
"bcreas public dala or functions arc acc:essi"blc from outside the class.
Data biding means hiding the data from parts of the program that do not
need so aa::ess iL More specifically, one class's data is hidden from other ,
classes. Om hiding is designed to protect well intentioned programme~ from
boDe:sl mishkes
Abstraction is a mechanism that enables the designer to focus on the
essential details of a program component with linle co~cem for lo\, er-level
detail. Abstraction is a relative concept. As we move to higher levels of
abstraction we ignore more and more details, i.e., we give a more general look
of a concept or item. We give a more specific view of a concept or item. as
we move to lower levels of abstractioa, we introduce more details.
Plugs arms who .really want to access private data b~t ~ey will find it Abstraction permits one to concentrate on a problem at some level of
bard 10 do so by accidml This is the significance of data hiding. generalization without regard to irrelevant low-level details; use of abstractioo
Also, dlJa hiding helps to achieve encapsulation which is the process of also permit one to work with concepts and terms that are familiar io the
hiding aU the secrets of an object that do not contribute to its essential problem environment
dwacteristics; typically, structure ofobjects and implementation ofits methods At the highest level of abstraction, a solution is stated in broad terms
is hidden. using the language ofthe problem environment At lower levels of abstraction,
Adnac.ges of Data Hidiag - Refer to Q2. o. more procedural orientation is taken.. Problem oriented terminology is coupled
with implementation-oriented terminology in an effort to state a solution. Finally,
Q.4. DeflM m,sabilily and dAlll hiding. (R.GP.V., Dec. 2014) at the lowest level of abstraction, 1he solution is stated in a manner that can be
An.s. Reusabiliy - In object oriented programming, the concept of directly implemented.
inbentance provides the id~ ofreusability. This means that we can add additional Q.6. Explain abold abstract data types with proper aa111pl~
fearu.res of an existing class without modifying it This is possible by deriving (R.GP.V., Dec. 20ll)
a oc~ class from the existing one. The new class will have the combined Or
features of both the classes. The real appeal and power of the inheritance Explain abstract data type with example. Whal ore its """"1rmges '!
mechamsm is that it allows the programmer to reuse a class that is almost, but (R.GP.V., Dec. 2015)
not ex.act!~. "hat "e wants. and to tailor the class in such a way that it does Or
not mtroduce any undesirable side effects into the rest of the classes. What are abstract data types ? (R.GP.V., J11~ 2016)
D2t.a Hiding - Refer to Q.3. Or
Define abstract data types. (R.GP. V., J,me 2014)
Q.5. DefIM and a:p/ain abstractio1L
Or Ans. The term data type defines the type of data which a particular variable
WriJe short note on dala abstraction. (R.GP. V., Dec. 2016) can hold - it may be an integer, a character, a float, or aoy of a range of simple
red p,oorammmg &
Metnodo/ogy (/11-Sem .. CS-Branch)
Unit - II 49
Ill
,s Obfed onen - ·I we build objecHmentcd systcn
Q.8. What;_., a11 object ? How can do we use objects in program ?
ar ~cniat1ons. I ➔ o,,·e\'cr· " ienb -ct data types, wh ,ch
.
rcprc, en
11
data storae- •~y• - known as a s.. w ·
(R.GP. V., Dec. 1005, Nov. 1018)
we u_<e mo....
"
cornple.x data types.
.
•..ht be interested m reprcscnt1nl:!~',
le we m1,.;. Ans. An object has property, state. behaviour. and identity. The tenn object
re realisnc enrioes. For c~amp · .bes how all bank accounts arc handle~
mo
·bank account . data I\""" which dcscn
, r-~ d instance arc interchangeable. Object is uniquely identified by its name and
:defines a state which is represented by the values of its attributes at a particular
in a progrrun. . plexity. ignoring unnecessary de1J,1
time. The object's state changes on the basis of the methods which are applied
Abstraction is about reducmgth~m . supPosed to contain the esscn11a1
· of some mg is · • to it These possible sequences of state change are called as behaviour of the
An abstract representation
. . resented. For example' realistic . pamtmg
. contains
object.
rearures of what 1s being rep an abstract painung mtends to re0cci
all the details seen by the eye. whe_reas The object's behaviour is defined by the set of method which can be
. featureS ofwbat is being seen. . applied on it. Property specifies current state of an object.
the cssentiaJ . abstra I dati type is that 1l represents what 15
Another key pomt about an f .... ft. :,.rricular thing, not just an individuai Generally, an object represents an individual identifiable item unit, or entity,
~ .ecn all examples o W4l r-- . either real or abstract, with a well defined role in problem domain. The basic
COIDffl()l1 r: • ffiee cup' would be a representation of
absUact data type ,or
(}<;<..
co . run-time entities in an object oriented paradigm are called objects. They may
ex.ample.
.i.:
An that an: common to all coffec cups, not just a parttcular one. It
represent a place, a person, a bank-account, a table of data or any item that is
all the WJllgS absttact da1a type contams· no val~ -. it only defines the. types handled by the program.
means dw an
ofdata or data sttuCIUrCS w
hicb together will define the state of any obJect of
Q.9. Explain different types ofobjects. (R.GP. V., Dec. 2005, Nov. 1018)
that ~ of Abstract Data 1ypes - The advantages of abstract data Ans. There are four types ofobject which we may instantiate in a program.
arepmbdow- The first three are objects with specific names, but the fourth, dynamic objects.
• - ~-•:· lniimmdtnct - Most of the program codet cannot be identified in this way -
types (iJ ....,.a~-" -r .
becomes independent of the abstract data type's representation, so that (i) External (Global) Objects -An external object is one which is
,ep,hl adllic.-i can be update without breaking th~ full program. . persistent and visible throughout a program module - i.e. its scope is an entire
(i,J M°"11Mity _ Wrth representation mdependence the differeru module (source file). It may also be made visible in other modules. Objects
_.,_ become less dependent on other parts and on bow • which fall into the category of 'external' would be one whose number and
parts of a program i;uui;
those other parts are implemented- . . I identities remain constant throughout an application.
(iii) III/DCMllgabilily ofParts - Different unple~entations of an[ (ii) Allto111lllic (Local) Objects-As well as external, global objects,
abstract d.ala type can have different performance features wt~ abstract d~ta we may also have.a nu.mber,of]~ly declared '.automatic' objects - objects
a program code ~ use an unplementatioo
types, it becomes easier for ea.ch part of_ which exist in a predictable manner for a particular period.of time. The key
ofits data types that will be more efficient for that specific part of the program difference between •
an external -and

an automatic object is that whereas
I
an
automatic object is instantiated within the scope ofpart of a !?~gram module,
Q. 7. WM/ 'HH ofabslrtldion is employed in an external object is instantiated outside ofany scope.(~ <;++,scope is define~
{i) Proc.tJl,ut
by braces). 'Automatic' objects are automatically destroyed when ~ey fall-
(ii) Objtct-orunwl progra,,rming ?
out of the scope in which they were instantiated.
(R.GP. V., June 1009)
(iii) Static Objects - We know that external objects are persistent
Ans. Table 2.1 lists the programming styles with the different types of and visible throughout the lifetime of a program, whereas automatic objects
abstraction they employ.
are only persistent and visible within the scope in which they are declared
Table 2.1 Types of Programming Paradigms There is also the possibility in C++ to explicitly declare a variable or object
which has the scope (in tenns of visibility) of an automatic object but the
S.No. Progran,ming Style Abstraction Employed lifetime of an external object.
(i) Procedure-oriented Algorithms
(ii) Object-oriented (iv) Dynamic Objects - Lifetime may be controlled· within a
Classes and objects
particular scope.
_ _
~"7A..AI_ __ _ _ __ _
\
.I J
(f/1-Sem.. CS-Branch) Unit - II 51
·n & Methodology
50 ObJect Oriented Programm, g
O
,fobject in a cla!i.<i ? Advantages of Global Object - There arc several advantages of global
,. ... decide the lift 0nd scopt (R.GP. J(, Dec. 20 l JJ . ts are as follows -
Q JO. HOM' con ·~ ... obJec .
· . ro nt. its lifetime and v1s1b1l1t) (i) Jt can be access m who 1e class.
8
cd object '" P gm b f tJirec types -
Ans. When we create a nam ed 0 bjects may e o . (ii) Only one global object can be used in all function declared in that
. · lied only by it.c; scope. Nam _ . siantiatcd inside the local scop~ class.
1s contro t,'cObjedS-ObJectsin d fined by braces. They onl)
(i) A11tom11 .th its bodY e Disadvantages of Global Object - There are several disadvantages of
structure w1
of a function or other . fun bal objects are as follows -
.. l while they are in scope. Ob·ects instantiated outside any ct1on glo (i) If variable has declared as global it cannot declared as local with
ex1s .. Extnntu Objects - . ~ fi the lifetime of the program.
,-me name in the functions.
(1~ have •file scope··an~ ex.i_st ortiated inside local scope and having the s-,-,. .
body. Tbcs (i.,1 s,.ricObjects-Ob1ect~sdian)aratioo to the end of the program. , , (ii) It is time consuming means when one function does not need to
,u, .. trom their ec
the gl~bal
1
variable yet compiler reads the global variable when object call the
local ,risibility, but persisung b ·ec/S ? Also explain wl,at do you •1, ,, .
WU/ ore globol 11nd loe11l O '1 (R.GP. V., June 2011) class. ,, 1
; /JJ objed life ,;,,,e. ' Advantages of Local Object - TI1ere are several advantages of local
Q 9 and Q.I0. . objects are as follows -
,4,rs. Refer to · / d local objects. Also write their (i) It can be access in function bodies in which it is declared.
J2. DijferellDllte beMll" globa an (R.GP. V., Dec. 2016)
Q• . ~-111ges. (ii) Different-different local objects can be defined in different-
lllhwJIUtes llM iis••,,.,• gJ b I and local objects are as follows - different functions.
,4,rs. The difference between o a
Local Object (iii) Local objects can be defined when function needs.
/ 1 G/JJbol Objed . .
S.No. _ Local objects are declared ms1de the Disadvantages of Local Object - There are several disadvantages of
1
(i) Global objects are d~lared ou function bodies. local variable are as follows -
side the function bodies. _ Only that function in which local
(ii) All ~ctioo can access the gJ object is defined can access local
0 (i) If object has declared as local it cannot declared as global with
bal obJects· objects. the same name in the class and cannot declared as local in other function.
Local object gets first precedence. (ii) It has limited scope.
(iii) Global object does not get first
precedence. For example - (iii) Local object of one function cannot be used in other function.
(iv) For example - #include <iostream.h> (iv) It consumes more memory because specific task has specific
#include <iostream.h> #include <constream.h>
#include <constream.h> local variable.
class text
class text { Q.13. Differentiate between global and local objects.
{ public : public : (R.GP. V., J1111e 2012)
void show (c~c) t°id show (char*c) Or
{ << "\n" << c; cout << "\n" << c; Compare the global and local objects. (R.GP.V., Dec. 2011)
cout }
Ans. Refer to Q.12.
}; } . }; . .
r.exrg; // gJobaJ object declaration void mam( ) Q.U. Differentiate between static and dynamic objects.
void main( ) { (R.GP. V., June 2012, 2016)
{ text local; . Or
: : g.show ("Global"); //local object declaration Compare the static and dynamic objects.
// call using global object local.show ("Local"); (R.GP.V., Dec. 20ll, June 2014)
//call using local object
} Ans. There are several differences between static and dynamic objects
are given below -
• ..._kJNJV (/11-Sem.. CS-Branch) Unit· II 53
52 Objed Oriented Programming & #.feITTUU"""I,
Dyn11mic Object
- that ofa ~oble ofany basic type. The ne~essary memory space is allocated to an
ot this stage. Note that the class specification, like a structure, prov,•ctcs on 1y
S.No. S,.tic Objtcl A dynamic obje~t gets it memory ob,i..,..
~""''
A static object gets its ~or)' D•'f
1111/J/ale and does not create any memory space for the ob·~ cts
.
(i) allocated at runtime.
Obiects can also be created when a class is defined b 1 · th ·
preallocated before runbmc. If you define an a~y of_variablc ~ I · YP acmg err names
._ _.djately after the c osmg brace, as we do in the case ofstrucures. Th .
I at 1s
(ii) lfyou define an_arn~ ofl~ length as dynamic obJect. its .. n
'"""'- tlte defimt1o
five as static obJCCl its 1':21 length can be change ot runtime. 10 say,•
cannot be change II runtJJ1JC- It is not faster for particular set of
class class_name
·cu1ar set of {
It is faster for pat1l elements.
(iii)
elements.
-
• d? Com'P are static and
. ,aaJII by llft t1111t of"" obJt
Q.15. ~ a (R.GP.V., Dec. 2012)

"--~ AIIS, Refer to Q.10 and Q.14.


• ofUlll ludinl with an exmnple. Comport
.;_;/;,.,.J ill
(R.GP.V., June 20/SJ
.}
X. y, z;
Q.J'-ExplottM;,1&,...1--
-,c oJ IJ-Dllk oljtcts. would create the obj~ct x, Yand z of type item. This practice is seldom followed
AIIS. Refer to QJ and Q.1 4. bec3use we would l~e to declare the object close to the place where they are
. rA~ bdw«n activt andpassive slllle ofobjects ? used and not at the lime of class definition.
Q.17. WuJ,stM ..u• (R.GP.V., Dec. 2013)
Q.19. A method implement the behaviour of an object Justify.
• the differences between active and passive objects _ objects use the method to pe11onn
..r
AJ1S. Followmg are . Ans. Method is defined for the class and
.
. h thod .
(i) An adiPt objtct is one that encompasses its own thread of control. an acbon. Eac me IS synonymous with a behaviour or a series of methods

ll'hercas a pasi'Pe objtct does not . which, when executed constitutes a behaviour. The object on which method
,
(ii) Active objects are generally autonomo us meanmg th_at they can operates is called the receiver objects, operating through its attnbutes and methods.
exhibit some behaviour without being operated upon by another obJect. On the
when explicitly Q.20. Write short note on object as software modul.es_
other hand, passive objects can onJy undergo a state change
· Ans. Objects are s~~are representations of real-world entities. To capture
acted upon.
(iil) Active objects serve as the roots of control. ~ our S?15tem _involves the features and capab1ht1es of real world, object consists of both attributes
multiple threads of controL then we will usually, have mulbple acbve obJects. On and operational information. An object is a software bundle of related variable
the other hand, sequential systems, usually, have exactly one active object, such and methods. Software objects are often used to model real-world object that
we find in everyday life.
as a main window object responsible for managing an event loop that dispatches
messages. In such an:bitecture all other objects are passive, and their behaviour 1s . Objects are cen~l idea behind object-oriented programming. Objecl-
ultimately triggered by messages from one active object That is, passive object onented programmrng treats data as a critical element in the program
never operates on other objects but it is only operated upon by other objects. development and does not allow it to flow freely around the system. It ties
data more closely to the function s that operate on it. and protect it from
Q.18. Whatare ohjects? Howare theycrea ted? (R.GP.V., Dec. 2016) acciden~I modification from outside functions. OOP allows decomposition of
Ans. Object - Refer to Q.8. problem mto a number of entities called object and then builds data and functions
Once a class has been created, we can create variables of that type b) around these objects.
using the class name. For example, . In object-~riented programming (OOP), an object is a self-containing
class_name X; //memory for Xis created enllty that consists of data and procedure to manipulate the data. Objects are
th~ thing, we think about first in designing a program and they are also the
creates a variable of type class_name. In C++, the class variables are knO\\ n as
uruts of code that are eventually derived from the process. An object is what
objects. Therefore. Xis called an object of type class_name. We may also declare actually runs on the computers.
more than one object in one statement. The declaration of an object is similar to
r

y (/11-Sem .. CS -B ran ch )
54 Ob · Ct On en ted Pr og ram mi ng & Me tho do log Unit - 11 55
IJe e
,ti on of ob jec ts ? W hy
is it ne ed ed tun ction is ca lle d au to ma tic all y wh ne ve r a ne w O b~ec .
1 type co un ter 1s.
1r a, is tly1 111 111 ic i,, itu ,fb '
· . ( ) tem en t created
Q- 2 I• JJ 11 Ste . 1bU S in ma m , the sta ·
CO -,, lis J, d; ,, C+ + 1 mG ·
Ho,,., is it tlC Co un ter cl c2
Or · .. .
1 ils ur rp or tan ce wi t/, ts, •but ~l so m1
c ;., ;,; .b fin ,. of ob jed:S 1 JIISlijj ~" no t only cre ate s o ob jec
tw tializes the ir
co un t va ria ble s to o.
H'1u,t is ,6'1MMi uu ,ri ,rg 1 (R .G P. V. , De c. 20 1 ra m in C+ + " d
s ~ br pr ov ) I Q.11. Wrile a pr og 0 ti
em on str ar e tlt e cr ea ~~~ef
€X 4.l llp k. Ro w it i Or ob jec ts.
1a irti c
,, ofob.feds ac lri nd
1 fR._ ~ v. . Dec. 2016 if1 . o-r, ,..,. . de
Ro.,,., is ,6. .... .... - -,; .6 :,, do
t th e 101bal va lu e of
tJ Ans. Th e fo llo wi ng pr0 c,, .... . , monstrares th e creati.on and use .
c
ob jec ts ref ers tha of dy na rru
.ation of •
An s. Dy na mi c ioitializ advantage of dy na mi c ini tia l.iz ati an ob Jec ts -
du rin g nm time.. On e
00 #include <i os tre am.h>
ob jec t ma y be pro vid ed , us in g ov er lo ad I
e \'a rio us ini tia liz ati on fo rm ats #include <s tri ng .h>
ts th at we ca n pr ov id us ing dif fer en t fo rm at of da ta ed cla ss ca r
vides the flexibility of

I
co ns tru cto rs. This pro ar J {
_ _
on the situation. .. pr iva te:
ru n tim e ~epcoding up proVJdes a co un ter va
ria bl e th
ch ar co lo ur (! 0J-

r=:.::::::: "!
CO UN TE R wh ich
C.oDSJdcr, the ex am ple
.. :J.
'
pu c:bli
ca r( cb ~ co lo ur in )·'
fimctioos.
ch ~ ge tco lo ur () ;

I
can
};
#in clu de <i os tte am Ji> {ar : : ca r( cb ~ co lo ur _i n)
na mc spa .cc std ;
us ing
cla ss Co un ter ur in )·
stm cp y(co lou r, ';co lo - • 9 •
l co lou r(9 J = '\0
JJm'ate: II co un t }
un sig ne d int count; ch ~ ca r : : ge tco lo ur
()
public:
Co un te r() : count(0
ty bo d~
)
/}
II co ns tru cto r
I {
ret ur n co lo ur ;
( I-e mp }
II in cr em en t co un t
void in c_ co un t() int m ai n( )

};
{count++;}
in t ge t_co un t( )
(ret ur n co un t;}
II ret ur n co un t
I {
ca r* ca rs( I0 J; II deRe
ca rs( 0J = ne w ca r("
cla re s an ar r

ca rs[ JJ = ne w ca r(" Gr llo w")-


r(" Ye
d" )·
ee n: ')·
ay of ten 'ca r' ob jec
t po inters

int m ai n( ) ca rs[ 2J = ne w ca
{
Co un ter c J ,c l; II de fin e an d ini tia lizIe ca rs[ JJ = ne w ca r(" Bl ue ur ( )·
tco
co ut << ca rs( 0J - > getco lou r( /
")· '
l~
cl. ge t_c ou nt( ); II di sp lay ge
co ut << "\ nc J= : << co ut << ca rs[ l J -> tco lo ur( ):
"\n c2 = << cl. ge t co un t( ); co ut << ca rs [l] - > ge Jo ur( ):
co ~ << - en t c J tco
cl. m c_ co un t( ); II in cr em
t c2 colut << ca rs[;3] - > ge '
co un t( ); II in cr em en d e ete ca rs[ OJ
c2 .in c_
c2 .in c_ co uo t( ); II in cr em en t c2 cars[O] = NULL·
let e ca rs[ J J; •
co ut << ::'ncJ=:: << cl. ge t_ co un
cl .g et count( )·'
t( ); II di sp lay ag ain de
ca rs[ JJ = NU LL ·
co ut << \oc 2= << - de let e ca rs[ 2J ; '
re tu rn O·
} ' cars[2] = NU LL·
. de let e ca rs[ JJ ; •
e Co un ter is fiirs t cre ate d, we wa nt tts co un t to b( ca rs( JJ = NU LL ·,
When an obInjectht of typ es thi s. Th i; }
ini tia liz ed to o e co un ter cla ss th e co
ns tru cto r co un ter do
.
I
56 Ob O . & • ..,_.... _,4,,.Jn,yv (/11-Sem .. CS-Bra nch) Unit - II 57
1ect nented Program ming ,.,..,u ~,

Q.23. Jf'rit~ slror1 not~ on ob/eel,, ,.,,__,.


. ~,J~_,.,.. (R.GP. V., Dec. 2008J
.
Q.]S. Whal is obje,·t idemiji er ?
. .
(R G
· P. V., Dec. 2 014)
. .
three element s _ a unique name, attribut es 3 0 d Ans. ObJect o nented languag es have built-in nleeh anisms for 1dentifyin
. . • . g
Ans. A class is defined by 'd ti~ stale and be havio b
·ecis, and ways to tes t o l)ectIf1dent1ty. There is typ·
ica 11 y no need to create
I
I s ln contras t. an o bject is defined by I en •J• . ur. ob~ . 'd .fi
method types. you need a un ique obl)ec · t •d .fiier you ca
ln ~ c h o f these three cases. the property of the classaJre1Iates mhso nb~e wa) exPlllin . er
licit obJect I entl fr
om
th
e sys tem. In C ++ an o b · ,
1 cnh
n
The artnbute s of the class ow eac o ~ect lo it at run tJme
.d . l)ect s actual me mory
. ob
. .
and can be o bta· d b Y applyin .
to the property of the obJCCL •b t The method s of tJ1e c lass ddreSS serves as a unique I bentifier me g the &
• ..a_ value for each attn u e. r, the concep t ofidc nti • · ce O b . .d .
contain state u.sta - one . b' t Howeve (addreSS of) operato r to an o ~ect or object referen I
I) · l)ect enti ty can be
define the poSSJble behaV1ours of the IJCC
O
tested by pointer (addres s).
. . lex than the oame of the class.
1s shghtJy more . comp . be ·d tified by a unique name · r,..or note on object mode/l ino. (R ,,,...P. V.
r nvorific obJCCt to • en Q.16, Write a brief - ~ • . , Dec. 2012)
It is poss ibIe ,ora ~r-: th re might be a fixed and linuted , . • b
ts is t .
· · ii field control system, e . . Ans. 11,ie first step m analyzi ng the require men
one easily identifi able by a unique • ' b ' d I h o constru ct an o bJec t
m stance m _an _o . ua1 01·1 umps each odel. The o ~ect mo e s ows the s tatic data s truct ure o f the real-world
, P• .1 p~pi• and so on. Howev er, thi~ simplic it) / [ll • • •
number of m~•".'d b.
1 1
ruzes it mto workab le pieces. It describ es rea l- Id b'
name such as oila1pump 1the ' OJ
case. In some
.
satuano

ns,
th
ere are many o ~ec1s system ~forga
o biect d wor do IJect
. . . . . h 'd . ti classes and their relationships to each o ther The
mo e I prece e s the
of adcnnty is nol ways lf it is numng , w at I enti aes each . · . · .,
. -..a d destrov ed. because static structure 1s · usuall y better
constan tly being creau;u an J •
dynalJlJC model and functlo oal. model .
u.Id be absurd to suggest that we could name _eve~ ra indrop, {

p
. ? on applica tion details more stable as the sol -
ra.mdroP · 11 wo . d th•-for e must have some kind ofumq ue identity. lo defined,. less depend ent ' u110 0 evo1ves
'
but eac.h does CXJSt an .... ... · &"; 11 and easier for humans to underst and.
•d that each obiect can have a uruque name ,a s down. lo
some cases, the J ea J • • I th Jnfonnatioo for the object model comes from the problem statement, expert
fact. wbaf differen tiates one raindr~ p fro_m another 1bs_srmp Y be ul sp~ce that f th li · d
of any o ~ect may e tamatel, mowle d~e o . e app cation_ o main, and general kno w ledge of the real world.
. · t ft.hcula r time The identity . . . d 1
· d r,
1t occupie s a a p..... · .
s If the designer 1s not a domam expert, the informa tio n must be obt.a me Tom
definab le only by this space time relation ship. In_ob1ect- ~r1ente program · d h k
Ii cation expert an c e~ ed aga ins t the m od el rep eatedly. O bject mo de l
which are ~onstan tly/ the app
which have to keep track of a large number of o~Jects_
diagrams promot e commu mc ation betwee n c ompute r profess 10na · 1s an d
being insmntiated and destroy ed, objects will ?e 1deo~ ed by their m_e mory · · oo-d oma m · experts .
applica~
location s rather than by unique names, but obJects which are unpred ictable
I Firstly, identify classes and assoc iations as they a ffect the overall struc ture
are identifi ed by location . basic
and approac h to the problem . Next add attribut es to further describe the
I Q.21. Wrik sJ,ort note on persiste nt objects. network of classes and associa tions. Then combin e and organiz e classes us·
(R.G.P. V., Dec. 2011, 2012, June 2014) ~
inheritance. T~ to s~ecify inherita nce directly w ithout firs t describing low-le:
Or preconc e ived
(R.GP. V., Dec. 2015;
classes and thelf attribut es often distort the class structu re to match
WJuzt do yo111n un by object persist ent? notion~. Add ope1:3tions to classes later as a by-pro duct o f constructing
the
existen ce inside / o ns modify o bjects and therefo re cannot
Ans. The lifetime of an object can vary from a momen tary dynannc and functmo al models . Operati
the body of a function or method , to persiste nce for the life of the program . I be fully specifie d until the dynami cs and functio nality are understood.
There are three levels at which objects may persist - Hence, the followi ng step s are performed in constructing an object model _
(i) Identify o bjects and c lasses
(i) Object persisti ng during a run of a program
(ii) Prepare a d ata dictio nary
(u) Objects persisti ng between runs of a single program
(iii) Identify associa tio ns betwee n o bjects
(Iii) Objects persisti ng between differen t program s.
(iv) Identify attribut es of o bjects a nd links
Objects wruch only exist while a program is running are known a s transie~
tim, (v) Organi ze and simplif y o bject classes using inherita nce
objects . They have no existenc e ind~pen dent of a single progra m run
rur (vi) Verify that access pa ths exist for like ly queries
Those whose lifetime s extend beyond the bounda ries of a sing le program
is ont (vii) Iterate and refine the m od e l
are known as persist ent objects. This means that a persiste nt o bje c t
whose data can be saved to disk. (viii) Group classes into m odules.
58 ObJect Onented Programming & MethodoIogy

Q.2 •. H ltat is dtt ntcd of modtl111g


An~ 11,e process of crcahng am
.
(//1-Sem., CS-Branch)
, ? (R.GP.V., Dec. l0J,1
.
odel helps an analyst clanfy and rcliric
ms as he or she completes a d
i
Unit - II 59

·,nplcmented as empty classes during the first few implementations of the


1 ~CCL These empty classes are also known as stubs. The empty classes arc
pr\ 1in exception handling.
r
05e1U
·1 Th 31lalyst Ica questions . .
wlulc creating
11
rcqu1rcmcnl.s and design detai s. e rnise Q.JJ. W/rat are tl,e different varieties of classes ? Explain it1 brief
I
lhcn sludics parts of the model. Analf-1 a s:ccss continues. New pieces ar~ I Or
model and answer them as the mode;;: :valuated and again questioned. I~ Lisi out tht different kinds of classes. (R.G.P. v., Nov. 2019)
Ans. Following are the basic varieties of classes _
added. \he conscqucn~ of chan~:lf provides direct benefit t~ the analyst
th,~ respect. the modeling process od 1. valuable in itself, even rf the analyst I (i) Abstract Class -A class that has no instances or that is not used
\ The technique used to create the m e '!e else
never shows a particular m~el to 31\YO • 10
create objects. An abstract class is designed only to act as a base class.
.,(ii) Conllliner Class - A class whose instances are collections of other
met diagram ? (R. GP. V., Dec. 20 I4J
Q· ]&. "Ml is drt IISt. ofsyston
Ans. The sequence diagram
Stt/ll .
is an VML diagram used to show'the dyna1111 c
diagram shows the messages that arc
I
objects, C,ontainer _classes may denote homogeneous collections or heterogenous
coUection..s.~Contamer cl~es-are most often defined as parameterized classes
properties of a system. A seque~ce system In order to be a strict-sequence with some parameter des1gnatmg the class of the contained objects.
...... rwo components m a . I h f , (iii) Gentric Class - A class that serves as a template for other
~ uu••ccn . have to be objects. In the ear y p ases 'O systern I
d1ag12D1. these l\'O parts sed in the diagram can be e.g. GUI, database classes, in wh_ich the templ~te may be par~eterized by other classes, objects,
development the components u Sequence diagrams applied in this way are and or operatJo~s. A genef!C clas~ must be mstantiated before objects can be

D
fi
Even though they have no orma standing
, 1·otemets or subsystems. I · created. Genenc classes are typically used as container classes. The term
seners, d.
called system sequence ,agrams. · th · d try generic and parameterized are interchangeable.
in the UML 2.0 definition they are widely used m e m us . I
(iv) Base Class - The most generalized class in a class structure. A
; ,. ,.. .. --,";J. . . - •r a class from which other classes are derived.
(v) Derived Class - A class that inherits some or all of its members
Crom another class is called derived class.
(vi) Super Class - A class which has one or more members which
are classes themselves.
(vii) Object Class - Classes that do not explicitly extend any other
class implicitly extend the object class. If we do not specify a super class for
Q.19. Wlu,J is II class ? How does it accomplish data hiding ? /
to be the object class.
(R.GP.V., Dec. 2016) our class, it is assumed

I Ans. cws -A clllss describes a group ofobjects with similar properties.


common behaviour, common. relationships to o!her objects an_d com~oo I
Q.32. What do you understand by class declaration ? Explain.
Ans. A class is a way to bind the data and its associated functions together.
semantics. Person, company, anunal, process and wmdow are all obJect classes. It allows the data to be hidden, if necessary, from external use. When defining a
Each person has an age, IQ and may work at a job. Each process has an class, we create a new abstract data type that can be treated like any other built-
owner, priority and list of required resources. in data type. The class declaration describes the type and scope of its members.
Dita Hiding - Refer to Q.3.
The general fonn of class declaration is as follows -
class class name
Q.30. What art tmpty classts ? Can instance empty class be created ? { -
Gfrereason. (R.GP.V., May 20/9) private:
Airs. We know that the main reason for using a cl~ is to encapsulate data and variable declarations;
code. However, it is possible to have a class that has neither data nor code. ll1at is. function declarations;
public:
it is possible to have empty classes. The empty class is declared as follows
variable declarations;
class xyz { ); function declarations;
In rhe initial stages of development of a project, some of the classes are };
eirbernol fully identified, or not fully implemented. In such situations, they ar1
...._..uJNTY (//1-Sem.• CS-Branch) Unit - II 61
60 ObJecf Onented Programming & MeUIIJU"'"" .
ture dcclarnt1on. The body of . Subclas ses ore not limited to the methods provided to them by the super
The class dcclarat10n · 1s · ·1ar to 3. strU
· s1m1 cdcby a sem1co
· Ion. The c1ass bod ' They can also have their own data members and methods apart from
· · b c1ass.
c\ass is enclosed w1thm races and. temunntd functions. Th ese function · l
s and those l ·nherited from the super class.
·
contains the deeIarat1on ° f vanables an
35
lass mem~ -
\'ariab\cs are collectively known c sections. namely, private and public
The process
. .
of combmmg the common attributes and functions among a
lo p of related classes may be repeated at different levels of abstraction with
They arc usually grouped ~ t\:i which ofthem are public. The keywords
,1_')~-hich ofthe members arc privlllC ,_.....,. and arc followed by a colon.
fusolt objective of extending classes. As hierarchy structu re becomes
uu"' . visibil ity~ t egressively higher, the amount of specification and implementation inherited
pii\'alc and public arc l.no\\11 as · b
beeD declared as pnvate can e accessed ~rothe lower level classes increases. We may repent the process until we arc
The class members that have bl' members can be accessed from ~ that no new class can be fonned. Fig. 2.1 shows two level
• • laH' and the pu IC 5 iteration process.
only from within the c.........
outside the class also. . d laration) is the key feature of objeq.
The data biding (using pnvatthe eek yword private is optional. By defau1,
G] 0
. The use of e e '
'
oriented programnuog. rivate
the members of a class are ~ . ~ Jass are called data members and tht
@]
The ,'Miables declared ms1de. e cOnly the member function s can have
,'
functions are call
ed member funcllons.
access to the private data members and private function
.
s.
0 0
: , (a) Objects i11 (b) First level of Hierarchy (c) Second level
uample- Sol11tion Spaces of Hierarchy
class class_data Fig. 2./
( An example of super class and subclass is air tickets. Air tickets can be of
private:
int a, b; two types, confinned and request. Both these tickets have a lot of common
public: . . q) attributes, for example, flight number, date, destination and time. However, a
void putdata(mt P, mt confinned ticket would also have a seat number, while a request ticket would
{
a=p; have a status.
b = q; In this example, air ticket is a super class and two subclasses are con finned

'
void show_data( )
{ cout <<
and request which inherits same properties or attribute from super class.
Q.34. What is 11ested class ? How does it differ from local class ? Create
"\n a ="<< a << "b ..JI
- <<b·' a date as a nested class ofst11de11t qualifier class and do the ma11ip1
1latio11 of
reading and printing the date of birth and date ofjoi11ing of a studcnL
I };
Q.33. Exp/Jlin hierarchy ofclass wiJh example.
Ans. A class declared inside the declaration of another class is called nested
class. Nested classes provide classes with non-global status. Host and nested
Ans. To reuse as much as data and/or functions that have been designed
classes follow the same access rules for members that exist between non-
already, we create a class hierarchy. Class hierarchy consists of a base class
nested classes. Nested classes could be used to hide specialized classes and
and derived classes.
Organization of the class hierarchies involves identification of co~~oo their instances within a host class.
attributes and functions among a group of related classes and then combmrn1 Classes can be defined and used inside a function or a block. Such classes
them to form a new class. The new class will serve as super class and tlt are known as local classes.
others as subordinate classes (which derive attribute from the super class). ·Problem-
A super class is a class from which another class inherits properties.
A #include <iostream.h>
super class shares its properties with its child classes. A subclass is a cla.s;
that inherits attributes and methods from a super class. 1
class student

. ....--.1ogy (lfl-Sem.. CS-Branch)
62 Object Oriented Programmmg & Me",uuv, Unit- II 63
student( )
'
\ {
private : roll no = O;
int roll no; name[OJ = ' \O';
char name[30); branch[O] = '\O';
cli:u branchf20]; - -•-- -= "·
manes v;
int marks: }
public : -student( )
class date {
( }
int day; void set()
int month; {
int year; cout<< "Enter student details- "·
public : cout << "Roll_no:"; '
dale() cin >> roll no;
( day == month = year = O; cout << "Student_name:";
cin >> name;
} cout << "Student_branch:";
void set_dob( ) cin >> branch;
{ cout << "Marks:";
cout << "Enter date of birth-";
cout <~ter day:"; cin >> marks;
dob.set_dob( );
cin >> day;
cout << "Enter month:"; yoj.set_join( );
cin >> month; }
cout << "Enter year."; void show()
cin >> year, {
cout << "RoU no:" << roll no·
}
void show_dob{ ) cout << "Student_name:" << ~ame;
{
cout << "Student branch:" << branch·
cout << "Date of birth:"<< day<< "-" month << "- " << cout << "Marks:''<< marks; '
year << end/; dob.show_dob( );
} yoj.show_join( );
void set_join( ) }
{ };

I
coot<< "Enter date ofjoining-"; int main()
cout << "Enter day:"; {
cin >> day; student sl;
cout << "Enter month:"; s I.set( );
cin >> month; sl .show( );
cout << "Enter year."; return O;
cin >> year; }
}
void show.Join( ) Q.35. Wltat are tl,e different types of object diagrams ?
{
cout << "Date ofjoining:" << day << "-" << month << Ans. There are two types of object diagrams -
"-" << year << end/; (i) Class diagrams (ii) Instance diagrams.
} A ,class diagram is a schema, pattern or template for describing many
} dob, yoj; possible instances of data. A class diagram describes object class.

64 Objed Onented Program ming & Mefhc,do logY (/11-Sem.. CS-Bran ch) Unit - II 65

An mstance diaeram descnocs how a particula r set of objects ~elate to Tbe associat ion icon connect s two classes and denotes a s eman I ic
each 0ther An instan~ diae:ram describe s object instanC~- lnStaocc _d iagrains ction. Associa tions are often labeled . with no ua P h rases. s uch as
conlle .
the relations hip - A c Iass may have an
. - (specia.lly scenano s) and discussing _ , denoting the nature of
ds to an infinite set of instan £JrfP'',0,or---·. , _ _
are useful for ~ocumen b.D~ test cases ce _ _i_.;.,.n to itself (. called
.
a reflexiv e associat ion)· It ,·s also poss,·bl e to bave
example s. A gi,-cn class d i ~ correspon ~11...,.. .
the same . . ns may
pair of classes. Assoc1at:1o
than one assoc,at:. Jon between
. . .
d. d ,n0re · th " 11owmg-
di3..2J'ams. diaS?r3ID and one possible instance 1agrarn escribed .c• .4her adorned with their cardmah ty using the
syntax tn e ,o
- t,e 1w...

c(P~on))
Fig.. 22 shows a clas.s _
e.'(an>ples -
b~ It. 0 None
One
I •
0 .. 1
Some (0 to infinjty)
None or one
Objects
I..• One or more
F«. 1.2 Objed Dillgrm,,s 2 . .4 Two, three, or four
'-- object instance is a rounded box. The class name in 7, I J Seven or eleven
Tbe svmbol 1uo an Ob. .
: orii sr·s ~ at the top oftbe object box in boJ~ce . !.lect n3:111es are lasted The-card inality adomme_nt is applied to the target end of an associat ion,
~ normal fOOL 1bc symbol for class is a box with class name m boldfac e. and denotes the -number of links between each instance of the source class
m di3grmJS describe the ~eral case in modelin g a system. Instance and instances of the target class.
Class osed mainfv 10 show-examples to help to clarify a complex class generaliz ation/spe cializatio n relations. h Ip .
· ( I.e.,
• ~- , ~are • . ce .icon denotes a
The inheritan
,"'1._... . ~ • tbe "is a" relations hip), and appears as an associat ion with an arrowhe ad. The
- The distinction between the class diagrams and the instance diagram s is arrowhead points to the supercla ss, and the opposite end of the associat ion
m fact artificiaL classes and instances can appear on the same object diagram . des.igµates the subclass . Accordi ng to the rules of the chosen impleme ntation
but in gcnc:nJ it is not useful to mix classes and instances . language, ~e subclass inherits the structure and behavio ur of its supercla ss.
Also accordmg to these rules, a class may have one (single inheritan ce) or more
(!J6. WJuct is tJu plll'JHISL ofclass diagram ? De.sfrib e icons used for
(R.G.P.V., Dec. 2012, 2015) (mwtiple inheritan ce) supercla sses. Name clashes among the supercla sses are
c11HS rmuiD,rs/rip.
also resolved accordin g to the rules of the chosen language . Jn general, there
An£ Onex CRC cards and use cases have been generate d, class diagram s
maybe no cycles among inheritan ce relations hips. Also, inheritan ce relations hips
prmide a way r.o c.'Cpl"CSS the relationships among the classes, and to record may not have cardinal ity adornme nts.
the in.formation on the CRC cards. The Universal Modelin g Languag e (lJML)
The "has" jcon den_o tes a whole/p art relation ship (the " has a" re lationsh ip
speciiies how class relationships are depicted on class diagram s. Exploring
also known as aggregat ion), and appears as an association with a filled circle
class relationships with the class magrams may again reveal that addition s
or
at the end denoting the aggrega te. The class at the other end denotes
the pan
changes need to be made to the original c.Ja.sses, resulting in further revision s
whose instance s are containe d by the aggrega te object.
to die CRC carrls.
When the CRC can1s.. use cases. and class diagrams have been complet ed. The using icon denotes a client/su pplier re lations hip. and a ppears as an
the final program design is ready to be coded. / mociation with an open circle at the end denoting the client. ll11s re lationshi p
am ong j indirates tbat the client in some manner de pends upon the s uppl ier to provide
lco.ru Used for Class Relationships - The essential connect ions
f rertain services. It is used to indicate the dec1s1on that operatio ns of the:: c l Jent
cl:?sses are associat ion. inheritan ce. -1ias.., and "-using.. - - - - Associatio n
da~ invoke operatio ns of the suppl ier c lass. o r have s ignature s who~e return
rel2tions hips, whose irons are shown in fig. 23. Each - - - - Jnberiran cr
class or azguments are instances of the s upplier class.
such relation sbjp may include a textual label that • Ua)

docume nts rbe name of che relations hip or suggests its


purpose. Relacion sbip names need not be g]obal, but o--- - Using
must be unique ~itbin their conte_'<L Fig. 2.3 Class
Relation ship Icons
Q.37. Whal is the purpose ofclass diagram ? Describe ico11s IL.fedfor class
rtlir.iollSlrips. How we ca,, use object as software modules ? (R. GP. V., Dec. 2014)
Ans. Refer to Q.36 and Q .20.
l_
m , CS -Br anch )
► Un, t · II (jl
& ~ oJogy (11/~
66 Ob]eCt On ent ed Pro gra mm ing
"' 1111d objcY t diu ~ro ,,, ? . , u.. lly n dcf oul t vu• luc -
d<1 J'Ol l Mt tm by clt, ss dill...~
,plJ(ll
Q.3 ,t. If 1t<Jt 1
• A Att nbu rc name- o nly
~xrs11.-nlt>
~T .lm is us«.'1_to .tjH) w tJ1~ • :c Attribute- cla ss onl y
.-4ns. C las s ~ m - A ~Ls..~ 31 ,; cwf ol tt sys r~m . A sin "',,,...- 'I
" c 1a.,1
- -~ therr re13tJ'---
-.u"1 - s ,·n the ~c:
L1ap ~~ •A ; C Att rib ute nam e nnd class

l
.: a..~
""'" •
-"°"
\"Je'
•-
W llf the c~ ,,.,..
--·c1Ul'C
o :i sys
n:-s
O
pon
unn
s:l,
Q
irlli

"
·d tem. .• I - .... ,,1/ v<
c.,
"
.
, ·
01 u,.
'I' • A . c = E Att rib ute num e. cla ss · und def
auJ t c
xpr ess ,on
.
I
--~=............... coounon ro,cs an
.... ,..... "" "'"- -."" ~
,..--~ -"-;: '
-· · igu ous in lhe co o Iext o f th c cla ss.

I
\.Ll~l .J.u.£ 1.1 • ' - • .
~ 1___ .... lllU I-•.. u" e mu st be una mb
we use cw:i.S ui:u :rams ro
, th -=·.,, •L- -•- - •shch.,viour. Dur
~,~,...,. ing des ign . we- ust! , da s..., dia, ........
<::-• -'fl))
' An attr ibu
.
te nam .
v ice prov ide d by t1 •1 . 0
.
Cflt'lt>cs 3l pr( '\ NC u~
...... •Ja. ....- th.st fom , th~ sysrt:m s arc hr tc.'l.::1u.... • '-, An operation den otes som l' ser n ieanc das s. d~c ~t• o~s arc
10 ~ th,: structur
e O f u ,., '- ~
rhl' lr b t nam ed wh en sh ow n ins ide a class ico are 1s Ung u1s hed
t s of.s dss s di.tl-?T3Jll :in- cla
sses a nd .i,,c USu11IIY jus
. par ent hes es or. wh ere nec ess:-✓
, :irv ,o r th e pur pos es
:i I e l• -....
....... d mg r
The ~, o ~n "rom allributes by npp eo .d .
sh1 p,., sho w thl' ~x is t1.·n 1. 1.· O f
11
of the dia gra m. by pro v, ing the_ope rati on ·s com ple
y
te sig nat ure _ I
rclaoon di :1 ~ is _u sed _to Op era tion nam e onl
Ob jec t Diagram _ An obje.:t
1.."h j~ :md the ir rea tion shi ps
in the logt ca.1 des ign ot a sys tem . A sin gk• obwc,
ana h
• N( )
• R N(A rgu rne nts )
Op era tio n retu rn cla ss. nam
e, a nd for ma l I
ong ~1,'
obj ect str uc ~ ofa sys_tcm . Du arg um ent s (if any )
di:lgram represents .s ,1e " of the ics of pnm :uy and sc1.· onJ:i con tex t o f the cla ss
. , obj «-t di. unm s 10 ind icat
e the sem ant
0~ rat ion na, me ; mu s t be ~n ~b igu o us in the •
ign _ i1~ I imp ! , ta .
~ lha l pn:,;,jde a 03c e oft be S)'S
th
tc~ •s beh avi our. ~u ri~g des
tics of me cha nis ms in th /
scc ord mgt o the rue s ior ove rlo adr ng m the c hosen
(ii) Cla ss Rel atio 11s !,ip s - Re
fer to Q.;6_ cm en lJOn lan gua ge.
e og1c-a11
~~a~~:::,,"; ro illu sua te e sem.an
obj ect s and the, r Exa mple - Fig. 2.5 sho ws an .exa mp
le of this nolalJ·o n d
• d. raw.b
ti
n rom the
an obj ect dia gra m are · den mg sys tem . This d ia'" ""m
Tbe ~-o essential elements of dro
....,J,Jcm of tJ1e hYI dpon ies· gar "'' - csc n cs o n 1y a
rc we sc" lh
f t11e 1y rop om cs sys tem c lass s tru ctu re He
relationstlins , small pa.rt o/an, which inc lud c.5 ana ttri but ena med c mp t~g eth erw ·t1 c e;1~ss
Y'""
d /J . ti.' dtningP
Q...J 9-
,--
Wlu ,tis ,ae ofd ass di4 gra ln an °
'}eel ,ag ram • D esc rib e tht
re m odu le·' I
Gar
"""'1 1tio n, exe cute , and one sel ect or ope rnti on. ca1 1Hm ves1.
Tl1 e~ .i_ l one_m ~ ii ll'r
. ... IS an ass ociation•
~ aR tl ji,,rc:la s ~ Ho w am K'L" use objects as sof twa
'R. GP . V.·• Ju e
1 n lo
J 5J
I vy-
betw
-
een
.
this clatiss an- the
d
cla ss . E11l 'iro1 1111 e111 Co1 1tm /ler .• w/i ere ,·n ms
ller mo n -
· a nccs n
d1 1

te t ins tan ces o f the con tro
'
the plan def ine 1e c 1,ma tha 1
I or UII 1110 (1 If}.
,,_ R-.r. Q ""6 Q3 8 and Q -.,0· ,-~ --- --- ........
-~ oe r to .., , examp/t.
1
Thi s dia gra m als o
ada ssd mg ram ? Exp laiJ , wit lr D~nn('s / Ern·lro nme n1n 1.'
(!. ./0. H'l ,11 1an the ~km m1 Sof s tha t the cla s_s
Disaa:smr.,-rWJOlllhvuu:edamc
Airs. Elemr-JJts of a Class Dia
ses and the ir
eptsofclassdmgram
gram_- The two ess
bas ic rela tion shi ps
an

are
d
ent
ln_

as
eir
ial
fol
sig
ele
low
m
nif

s
en~
,ca ,,cc.
of 3
l indi
Env
cate
ironmentContro/ler 1s
an agg reg ate w ho se
,ex act
,-{:;~;;i:::;l!I~":
ly ,' c1·op
C llm
-

: I
l ~---
/ olr. ,;>' ...c o_n_rro_11_er• • •

~ ..
I ,•

·~ __
cla ss dia gra m~ clas tain - .....
____,-.. ______ )
-. iosta hoce s con ;• •• •• -•
ws ilie ico n use d to rep res ent a cJ ... s.s ,,1 r. one coo er and •- euc ut~ ) ' ·t :• l11 • ....
u1r
...
r: !.,<. oolc r: : Ui,:h1 :
fi) Ga sse s- Fig. 2.4 sho
· l 1t · an am·orp hou s"" blo h "/ one eate
• • n•""
: can Ho ___ , , •.,_'\__ ,•
.... ______
,___
c ~ dia
· gra m Its sha pe IS · that of a clo ud Som e cal
the nam e is ___ ,., I any nw nbe rof Jig hts . Th e
Hea lerand Co ole r cla sses
,\ •• _,, •• 7 ..... .
,.\ nam e is req uire d for eac h clas s. If .--· Acl uar or·· -.., , ••--- . --.
par ticu lar ly long. it can eith
Tn2 gni fiea . fae ry cla ss "na
er be elided or the ico
me mu st be uni que to its
n
::
,: n:m
!IUr il>!J
e '·•
r,
• opc r ::it,o n, ,
:
\ I mtu
of
m:
the
a re
. abs
bot h
tra
sub
ct
cla
cla
sse
ss
s
: . ~•a rt Up(
•~
: W,
) ,' :
hulO own () 1) ~.... ______
:
Trm p,•n uur r~
__ ,'

J ges , mo s t ~ · ,-- --' Ac111alo,:," wh ich pro vid es ' .... __ ,,- --- -•'
I os1· ng ~ ass cat tgO l)', For certain lan gua rtU p and
enc stra in . ,"- -•· tbcr pf~! oco l sta
not2bl_v C'T"'T' an(:J Smalltalk.• we ,___
may furthe r con 1i11g Sy.,·rem Clt l\,
be . . Fig . - · .:/ Class Icon , shulD<Jwn, and whic.h uses Fig. 2.5 I lyt frop on ic.'i Gartle1
the se sem wLJcs to requir~ •i--
... w.u eve ry c= name
umque. Dia.<:ra m
ro the sysrem.
· . the ~las s ·Temperature.
.'.d l. CHh. .,
e a 11ri bu1 0 ~ed Co nce pts of Cfo ,s D iag ram - The two ach :inll '
th ,,~n
is ttSefu/ to exp ose som e o f Ad
m arc as foll o\.-.'S -
For ce'.131n cla ss dia gra ms, it C· / of clas s dia gra
ng the fol low ing Jan " Ll.'.l!!
~d ope rao ons l.;v ass oci ated wit h a clahss. Usi ,:- .
(ij Par am elt! riu d C/rr,;.h
.- ~om c ob jl.'.ct- ' ' j
o r bot h. and
I f

IDde nPn den t S"" . 'b y ave a na me , a c las s.


, an att n u1e _ ma I most no tabl y ' II 1. ,c ,\ d ..i. pro , iul· p • I '
I Wib'Uages.
1 • _,,, '- • • , I • •

I
68 Object Oriented Programming & Methodology (f/1-Sem., CS-Bran ch) ► Unit - II 69
paramcte rizc,d c\ass denotes a family of classeS whose Sln>Cturc and l>l.:h,l\ io we moY cfraw a meta relations hip from the object lo its
are defined indcnr,nd t with the earlier use - a meta relations hip shows the c c lass._This
. . .
r · · cnt of its fonnal class parameters. . We. ) muS f;0 match ,1. lJJ 1s consiste nt
formal paramete rs \\; th actual ones (the process ofinstallb abon to ~ 8 concrctt
u ICSe entity (either an object or a class) and its class. onncctio n between some
class in this family: by concrete class, we mean one that may have instances Q,,IJ. Write short note 011 metaclas s.
· are suffic1es:iuy
. · omea~m
•·rt:'.---• Uh"" (R.GP. V., June 2013)
Parameterized classes .,....... d asc::,.., 1
-· nlnin ~- ~- ,o warrant Or
a special adornme nt. As the ~ l e fig.
2.6 shows a panuncteriz.ed class tS vts_uahzed
'°. G•nt~nlnn I JJ'/1at is n,etacla ss ? (R.GP. V., June 1015)
•···-- Pion ., ,Ans. Refer to Q.40.
as a simple class, but "ith a dashed-line box / Plan Set •
in the upper right comer denoting_ its formal
ft!>r.amet en. An instantiated cl_
?.......--·-~ •
.. Q.,12. Draw a class diagram for online co urse reserval .
ton system.
.----- ass 1s_tsadorned
tu.al I
/ r····-·-··• •_.. ...._
• -, (R.GP. V., June 1014)
with a solid-lin e box denotJng I ac ,-.l...,-: ltrm : ,-•Gant . • ..: ;1.ns.
atched positionally to_the ,'• Sd '-••y----•
, - ~ p 1an
eniug,!
paramete
corresponrs.
m .. << CourscRe servatlooH andler >>
ding formal pamne ~ In either -i ____ ) ....---·-·
➔ VlewCoun elnfo(Coo rseCodc)
case. we may optionally supply die formal . •--- _
and actual parameters as text inside the box. F,g. 2.6 Parame terized ➔ DropCoun c(CourseC ode)
Classes
The instantiat ion relationsh ip ~tween_a _paramet erized cla~s a nd ii!,
mstantiated class is shown as a dashed ~e. J>?ID~~.to the_paramet enzed claSs
Most often, the instanriated class reqwres a 'using relation to other concrei
AccouollD : string
'
Account
Student

classcS (such as GanieningP/on in this example) for use as an actual para mete;
A parameterized class may not have any instances and may not itselfb
used as a parameter. An instantiated class defines a new class distinct from al~
Type : string
StudcotlD : siring

CreatcAc:c ouol(Acco untlD)


- StudentlD : strin g
N:1me : slrio,:
Major: string
Gender : string
DoteOffiir lh : dote
other concrete c l ~ in the same family whose actual paramet ers differ. CooflnnAc counl (Accountl D)
Ema il : string
Address : siring
(iJJ MdOdasses - Languages such as Smalltalk and CLOS prO\ ide
metadas-ses. A ~ is the class ofa class. In Smalltalk. the most common USe
of mdadasses is ID prmride class instance variables and operation s, simi Jar to the
C ++ practice ofstdi<' rnc,nbc,s, orto define factory operations that generate instances
AccouotlD : string
CouneCod e : string
'
Reglstrati on
ContontNo : strin g

C reotcStudc nl
(StudentlD )
of the com:spooding class. In CLOS, metaclasses play an importan t role in the
ability to taik.-that language'!; semantics ·
I EnmlD: string
Grade : striae
GctStuden tinfo
(StudentJD)

_M ~lasses a,e also sufficien tly different than plain classes to warrant a CruleReel stratlon(A ccountlD, CourseCo de)
jl
DropCoune(CourseCode)
~iaJ adornme nt As we show in fig. 2.7, a metaclas s is visualiz ed as a
s~le c ~ but ~th a gray-~e d icon. The meta relations hip is shown as a
directed thick gray~ and pomts from a class to its metaclas s. In this example,
the ~Jass proVJdes the factory operation s new and default for generating Co11rseCode : string
'
Course

new lllSWJCCS of the class GardeningP/an. Tide : string


Type : slriDc
. A metaclas s may not itself have any Credit: int
instance s, but may inherit from contain Dale: date
Time: rtrlllg
instances of. use, and otherwis e ~iate Ve.aue : stria&
with other- classes.
, _, ....
Meta relations hips have one other use. / Ganlellille :
--.. lastnactor : strlne

Cruteeou ne (CouneCo de)


On certain class diagrams , it is useful to show -, Plu
an object that serves as a static member for ''••· -----
:

Fig. 2. 7 Metaclasses
GetCoune illlo(Coun eCode)
DropCoun e(CourseC ode)
some class. To show the class of this object,
Fig. 2.8
p
. & Methodology (//1-Sem.. CS-Branch) Unit - II 71
70 Object Onented Programmmg
. , Ho"' is it U..fil'ful in object orient <I _,.,..,.;ed outside the class. For example _
i
Q.43. R 1rat an dass dia~fi ID loboratr class diagrams. c ' l)I,;\,....,., •
c1ass item
r-no-ramming '! Takt> a~r one £'t'll1'1P e (R GP. J" D
P· -~· · . • ., ec. 201 6; {
int number;
,.f~ Oass Diagram - Refer to Q-38. _ _ / public:
. .th tic expressions ,s shown m ti g. 2 . 9 . / int x;
A class diagram for SJmple an me void getdata( );
. djagram for the e.q,ression (X + Y/3)l(X/4 + Y ). void display( );
Fie. 2.10 shows an mstanCC ~
The ~jocl diagram in the above Flrst o naad
d
Term
I J; . ()
int main
figure is 3d]Ja}1y a l]'ICbJOOdd for -~s-~ad::;.i._...-,___,,--...11
{
binary ~ o s. hrcn~ item i;
arc needed for an •~fix i.number; II error, number is private
repcescntation but are not required Variable Coost.q 1 i.x= 10; II ok, x is public
in tbe metaroodel. There are olh~ Name \ ':iiu" i.getdata( );
,cprescntarioos.. like postfix. m i.display( );
which ~ also ~ not
requircd. r« cnq,le, the same
L-----
Fil'. 2.9 Class Diagram for Simple }
return O;

As shown in the above example, only public data members and member

I
~ in a postfix ,cpresen- ~- Aritlimetic Expressions
tatiJo is XY3f+X4/Y+I. functions are directly accessed inside the main program . Private data
members (like number) cannot be accessed directly inside th e main program .
(ii} /11side a Member FuncJio11 oftlte Same Class- Inside a member
(Espnssioa) (EJp':ssion) ID---
function of the same class, both public and private data members and member


+
(X + Y/3) (X/4 + Y) functions can be accessed. For example -
J" 11ad class example
~ J
(Expression) {
I int x;
Y/3
(Coruranr) public:
3 void get()
(Comtaar) pr (\'uiabk) {
4
y cout << "Enter value of x ":
cin >> x ;
F,g. 2./0 Jnst11ncL Diagram for the Expression (X.+- Y/3)1.(X/4 + Y) disp( };
Q.-U. Descrilu d,e mec/umisJrt ofaccessing data member and member }
void disp()
f lUldions in the following CJZSes - {
(i} Inside the main program cout << "Value is ., << x ;
(ii) Inside II memberf101dion oft/1e sanie class r.
};
(iii} Inside a memberfunction ofOf!ol/1er class. . int main()
(R.GP. V., Dec. 2016) {
Ans. {i} Inside die Alain Program·-The data members that are prin1 te. example e:
cannot be accessed directly, inside the main program. The private data o l a e.get( );
return O;
class can be accessed only thiough the member functions of that class. T he
}
data members and member functions that are declared public, can be on l) /
I ,
'
72

Here m the above e.umplc.


r
private data x and pub 1c mem
. & Mett,odology (1/1-Sem., CS-Branch)
Object Oriented Programmtng
. . we find that get( ) function can access both
. d'sp( ) Thus inside the me b
ber funcbOfi I . • m Cr
both private and public data mcmb

Unit· II

Here in the above exa?1pl~. we find that public member function get() of
73

example is accessed m clisp I ( ) function of class example I . This shows


clS.SSpublic data members and member functions can be accessed inside a

function of the same class we can access e rs (hat i....r function of another class.
rnern..,...
as well as member functions. • .rAno/lier Class - We can ac Q.JS. Whal are memberfunctions ? How can you define memberfunctions ?
.. i~.1 MDlll,o F1111dl0" OJ . ccss
(i-,i) - ~ • . ber functions. inside a member functio Or
public data members and public mem nvate data members and private memb/ Differentiate between a member function and a normal function.
of anothei: cl~- We cannot~ pof another class. For example - r (R.GP. V., May 2019)
function. mSJdc a member ti:mC'bOD ,Ans. The variables declared inside the class are known as data members
class example d the functions are Jeno~ as memberfuncdons. Only the member functions
{
int~ :0 have access to the pnvate data members and private functions.
public: Member functions can be defined in two ways -
void get()
(i) Outside the class definition (ii) Inside the class definition.
' oout << ..Enter valoe of x - "·,
(i) Outside the Class Definition - The member functions declared
cin >> x;
. !.oiddisp()
jnside a class have to be defined separately outside the class. Their definitions
are very much like the normal functions .
i
•I
' cout << cndJ;
An importmt difference between a member function and a normal function
• that a member function incorporates a membership identity label in the
cout << ..Value ofx =" << x;
:eader. This label tells the compiler which class the function belongs to. The
J general form of a member function definition is as follows -
};
class example) <return_type> <class_name> : : <functioo_name (argument declaration)>
{ int y; {
public <Function body>
void get)() }
{ c.oot << ..Enter vaJue o f y ,,; The membership label class_name :: tells the compiler that the function
cin >> y; function_name belongs to the class class_name. That is, the scope of the
J function is restricted to the class_name specified in the header line. The symbol
void disp 1( ) :: is called the scope resolution operator.
(
examplee; For example -
e.ger( ); void class_data :: putdata(int p, int q)
e.disp( ); {
rout<< endl;
cout << "Value of y =" << y; a= p;
} b = q;
); }
void class_data :: showdata()
inr main( )
{
(
examplel el ; cout << "\n a =" << a << "b =" << b;
el.get!(); }
el .displ( ); (ii) Inside the Class Definition - Another method of defining ;.
retum O;
member function is to replace the function declaration by the actual function
, ._.......i..wn, (111-Sem .• CS-Branch)
T
74 Object Onented Programming & Met1IINV'V'll' Unit - II 75
function is defined inside a class 11 Q.47. Discuss memory requireme11ts for classes and objects.
defo,tion \tlSlde \he c\ass. Wben 3 ~ -..ctions and limit:itio. · th,~
•-.I . r functi Therefore. aU wC l.__' ns at
trca"u;u as an in me ~n. \icab\e here. Nonnally, only srna AILS- On creating a class, memory is not allocated to its data member.
a-p-p\" \o an inline funct1on arc also at>P . . II there exists a template, but data members cannot be manipulated unless
functions are defined ,nsidc the class definttion. llt':'siance of this class_ is created by defining an object. It might gives an
\
'E.nmp\t- ~ · 00 that memory 1s allocated lo both data member and member function

\ :~lass whe~ an object of a particular class is created. It is partly true


c\ass 1tC:m
e memory 1s allocated only to data member not to the member function
\ t,ecaUS b' .

I
mt mnn: lhe class when an o ~eel 1s created. Member functions are created and
0
t\oa1 pric~ ~ored in memory only once when a class specification is declared. All objects
~i:~id gctdata(int a, float b); //declaration
II inline function
sf lass access same memory area where the member functions are stored.
~c member functions for all the objects are same and there is no point in
. . all~g a se~arate copy for ~ac~ _and every ob~ect created using the same
void puldata(\'oid) //definition ms1de the class
clasS specification. However, an md1~1dual memory 1s allocated for every object's
t dala members becau_se they hold dtffer~nt values. lt enables different objects
coot<<num<<"'In";
coot<<price<<"\n"; to 1..ndle
IJ4U
their data m a manner that swts them.
· Object I Object 2 Object N
}:
Q.'6. f.qai,t ,w tm11.aribllltS IUld ,ntthods in class and object. I Data I I
Or [oaill I Data 2 I I Data 2 I
(A.,.,., w dribldl and mtthod.
.AllS. Attributes- Having decided what our abstract data type is going 10 ( Data MI l Data MI l Data MI
rcprcscnt., we have to identify what elements go lo make up its state. These
arc known as dri)1114 When we identify attributes, we are not specifying
values for them. For example, we mi~t decide that our data type must have
the attribute of a,1o.,, but we do not predetermine what that colour might be
for any individual coffee cup, only that all coffee cups will have a colour of
some kind.
~etbods - The behaviour of our 'thing' is defined by its methods (also
called operations or services), which arc processing routines related lo the
data type. ln ah,,,ract data type, the method acts as the only path between the Fig• .2.11
user and the state data. It is normal practice to limit access to the data so that Fig. 2.11 shows the organization of memory resource for the objects. In
,t C3II only be accessed through these methods. fig. 2.11, we see that N objects of the same class are created and data members
There arc: seven! types of methods. Two of them are selector method oflhose objects are stored at different memory locations. while the member
nod modifier method. functions ofN objects are stored at same memory location. Therefore, each
A St1eci.or method is r~a.d method, one which allows access to an attribute. object contains a separate copy of data members and different objects share
bUI do not allow.tul,attijbutc to be altered. This is analogous lo the idea of a 1lie member function among them. It is simpler to visualize each object as
6incoon. lt i"$,~
~
sq'~ . ...:M ' a..t' me\hod. A 'modifier' method is a write
'~;.t,e~ co~taining both its own data and its own member functions. But in some
'llldhod. allowing lfflI}botes U>ic This is analogous to the idea of a situations, such as estimating the size of an executing program, it is helpful to
-proccdnre and is also·mc,wo know what is happening behind the ~cenes.
i p
Object Oriented Programming & l,,lethodologY (1//-Sem., CS-Branch) { Unit - II 77
76

Q.41. ~ • sltort IIOtt on _,,.of~ I cout <<"l:"<<al.pop() << end/;


cout «"2:"<<a I.push( ) « end/;
AIIS. We can ha,-c may of \-.nabJes that are of the type class. Such I at.push(03);
,'ariablcs arc called -,-,s of,,j,j«:ts. For example,
class employee
I
I
nJ.push(04);
nl .push(05);

char name (20); I a J.push(06);


cout<<"3:"<<al .pop<<end/;
int qe; cout<<''4:"<<a l .pop<<end/;
public: cout<<"5:"<<al .pop<<end/;
,ioid getdlll (n,id); cout<<"6:"<<al .pop<<end/;
void purdlll (wid); return O;
}; }
The idcnlifier upSr, is a user-defined data type and cap be usep to nie•main( ) progr:am in stackarray exercise the stack class by creating an
create objects mar ,dare ro diffi:leot categories of the employees. Example _ objccrh of the class. It p_ush two ite~ on the stack, and then pop them and
•:. ~mmagcr{2J; //array of manager disJ)laY the!11- Thereafter, 1t p~sh four items, pop th:m an~ display them. The
~ fcmmn [!OJ; //array of foreman staet c~ 1s an ~xample ofan Impor:tant feature of obJect onented programming
~ worm [JOO); //array of worker using 8 class to unplement a contamer or data storage mechanism.
•, The may --,er comams two objects (managers) ~ely, manager isiJ. Write a program to explain how an object can be returned from a
~•,N [OJ ud IDIDIJCr [I]. Similarly, the /ora,a array contams IO objects, faldO"' (R.GP.V., June 1015)
, ' (foreman) ml the Mria' amy CODtains 100 objects (workers).
. bs, A function cannot only receive objects as arguments, but can also
'1-"· DocriM .,,..,s a dGS ia 111a,bu. return-them. That is, it is possible to return an object through the called function.
AIU.~ can be used as data items in classes. As an example, consider WJier!~er a function returns an object, it is necessary that a function return
a program, srxbrny that creates a simple stack c~. type iiiust be the class name of that object.
#include <ioslrcam.h> Example-
class SllCk //Prop.m for complex class
( #include <iostream.h>
private ; using namcspace std;
CDIIID {MAX= 10}; class complex //x + iy fonn
intst{MAXJ; {
mttop; floatx; // real part
public: floaty; //imaginary part
stack() public:
{top= O;} void input(float real, float imag)
void push (int var) { x = real; y = imag;}
. {st[++ topJ = var,} friend complex sum(complex, complex);
ml pop()
void show(complex);
) ; {return st[top - -];} };
int main()
complex sum(complex c I , complex c2)
{.
{
stack OJ ;
complex c3;
a 1.pusb(0 J); c3.x = cl.x + c2.x;
a2.pusb(02);
c3.y = cl.y + c2.y;
} retum(c3);
. ~ (1/1-Sem .. CS-Branen)
► Unit - II 79
78 Objed Oriented Programnvng &
es upon the implementa- II focuses upon the observable
void complex . : show(complex c) (iO It. focus · to this
th3 t gives nse · behaVJour.
· behaviour
. of an o b.~ccL
000
I ~
_ roccss of including in an They encapsu late all the essential
coot << c.x << 1- <<c.)
· <<"\It-: 11
(iii) 1115 pve-"hing it needs, hidden properties of the objects that are
objeCt e ,yu• . b
l fiOOl other objects m the system. to e created.
int main( )
{
.. Class and Metacla ss - The class holds the attributes and
complex a. b. c~ ~h will apply to objects of the class - it is the class of the objects.
a.inpul(J 1. 5.6.5): inetbods w taclass bolds the attributes and methods which will apply to the
b.input(2 i5. 1.2): ,:iie ID~ therefore it is the class of class.
c = sum (a. b~ ~ itself Jass bas only one metaclass, and the metaclass has those parts of
rout « '"J =-: ubo\\(a) ;
cout «.,, ==-.
="'; b_sbow(b);
E~\ are not appropriate to be duplicated for every specific object.
rout « ~, c.sbo\\1C); a dJSS w ~ is basically a repository for those parts of a class which must
1
,ctmnO;
1be IDethtac -"' time of a program, whether or not there are objects of the class
c¢a1 e,wu
. e.<lstence.
111
S2. What is the difference between class m,d object ?
~i.1 •j 5.65. b =275 + j12., c =5.85 + j 6.85 Q. Or (R.GP. V., June 2014)
Q.5l. Diffna,DIIIL ben«Dt diL following - • :tr. t_.:A,e beJween class and objecL (R.GP. V., Dec. 2014)
. D1ptri ruuu
(i) Obj«.ts llJ'l4 dtmt:s (ii) Encapsulation and abstracllon A!IS- Refer to Q.51 (i).
(iii) Oas ll1'l4 •tJW«SS.
Q.SJ. Explain the difference between structure and class.
(R.GP.V., Dec.. 10/2J
Airs. (i) Obj«Itlll4 a.sz- The differences between objects and classes Ans. Toe difference between structure and class are as follows -
3.,--e as foll011•s - Structure
if{o. Class
S.ft"o.
(i)
01,jeds
A single object is simply an
Gasses
A class is a set of objects.
- (i) A structure is a convenient_tool
for handling a group of logically
A class is a way to bind the data
and its associa ted functio ns
instanct of a class. related data items. together.
(n) Objects may be crea1Cd and Once we have defined a class. {ii) Structure holds only data. Classes hold both the data and
desrro}'ed at run time. it exists all the time a program is function s.
running. (m) Toe members of a structure are The membe rs of a class are
(iii) An object has idcnrity, state A class bas a unique name, attri- public. . . private or public.
and bdia,-iour. butes and methods. [IV) The variables declared ms1de the The variables declared inside
(i,·) For example, structure are called structure the class are known as da ta
For example, members.
fruit mango; members.
fiuit mango;
I where mango is an object where fruit is a class. Q.51. What do JYJU mean by access control specifiers ? Explain each of
{ii) Elra,ps"'-1111111!A/Jstraction- The differences between d'.ita bin brief.
abstracrion and data encapsularion are as follows - Or
..l\'ol W/rat are the visibility labels for members ? (R.GP. V., Dec. 2015)
Encaps.i.tio11
Abstraction Or
(i) It is wrapping up of data and
It refers to the act ofrepresen ting Explain access control specifiers. (R.GP. V., Dec.. 2012)
functions imo a single unit

7
(c::alled class).
essential features without indud- AM When we define a class, we define members. A user can have different
ing the background detai Is or c ,p- attess privileges to the members. A class differen tiates between access
lanations.
-.,----,-~ -a-r_--•-- -- - -
111-......_
u . 81
:ITcrc.ntUllL and gi, e aamplt!S to bring ouJ the diffuou:c b~01
n~~ Dw· ;r.
" - ~_.., rfraJL access spcciJu"
~(PIMP 1
Or
:due,rrti.aU bel)t.-eoi public and pn~au accas r,pec,f~ with suitable
D%: fR.GPV.. May 2019)
tP"'1 All data members and members functJons of_ c ~ .d uch 2re to oe
•~le ou1Side the cl.ass should be declared m public scct10n.
~ clasS Test
{

po.bl.le : // Access specifier


int age; // Public data member
mt getage ( ), // Public member function
~ -
mu: ).
,-aid dispb) ( J:
Test l
ml a == Lage~ // can access public data
}
t.getage ( ). // can access public function
P,ir.U _ Prin1e means that no one can access the c%
Tbe pmate members of a class ha,e stnct access control AU data
(a) octside tmt class- If someone tnes to access 1k
me l:wn ~ ~ _ a _ ,.. time e:m>L By default class "anab~ a,e:int>ers and member fuocnons of the class are accessible onl) ,nthm the
~ - r::,rrbn .._J ,iiw b -_ ~ s:,une clasS Toe pm ate members of a class are maccessib le out.side the class
at rr,::d,t:r ftmctiDaS zre pm-ate.
class Test
clmXYZ
{
f
povate : Access speedier
pm*:· int age; / Pnvate data member
mu;
mt get:age ( ); // Pnvate member function
void display ( );

}
};
Test t
(iii) ~-Plufteted is similar to _private, it makes class ~ int a=t.age; / cannot access private data
maa't"SS'l>le oatside the class. BlI1 they can be accessed by any subclass af t.getage ( ); II cannot access private function
tba1 class.
classXYZ Q.56. In what respect are protected and private data member different ?
l AIU. The protected keyword is like pnvate, ID that the outside \\ or\d can
IC0CSS class member in a protected secnon only by usmg class members The
protected : diff'aalcc between privau and protected comes 1Dlo play on1y within c\~es
int a; da:ived from the base class. Members of a denved c\ass can acce~s protected
\ 01d display ( ); members of the base class directly, but they cannot dtrectly access pm ate
mmmers of the base class. So members in the protected categof) beha, e hk.e
private members as far as the outside world 1s concerned , but beha\c. hke
public members as far as derived class is concerned
I & Methodology (/II-Som . CS-Branch)

a; Ob•?~ Onented Drogramm r g Unit · II 83

[ \lmplr -
'°mcludr , 10<;tre.1m.h' Dd:
u~m~ namcspa~e i;td: //d.gct_ab( ); WON"T WORK
class B d.mul( );
// d.show_a( ); WON 'T WORK
pm-ate: not mhcritable .
mta: d.display( );
ready for inhentance
1 protc-ctcd.
protrctcd: // d.b = 20; WON'T WORK; b has become private
mt ti: d.mul{ );
mid get_ab( ).
mt get_a(\'oid):
d.display( );
,·o,d show_a(,-01d): return O;
I.
~iass D : priYate B pm-ate deri\'ation
Output -
Enter values for a and b : 5 I0
int c:
a=5
blic:
pu ,,oid mul(,-oid); b = IO
\'Oid displa)(void); C = 50

}: . Enter values for a and b : 12 20


"oid B:: gct_ab(,"Otd) a = 12
{ b = 20
oout « "Enter ,-a.lues for a and b:"; C = 240
cin >> a» b;
} Q.57. Wltat are static data member a,rd static member f uncti.ons ?
intB::gct_ a() Or
{ What do you mean by static class members ? Explilin the characteristics
rcnun a; ofstatic class members with suitable examples. (R. G.P. V., Dec. 20 JO)
} Ans. Static Data Member - A data member of a class is qualified as
void B : : show_a( )
static.
'
}
cout << -a =" << a << --\n"; The properties of a static member variable are same as that of a C static
variable.Astatic member variable contains certain special charactenstics. These
void D : : mu)( ) are as follows -

' get_ab( );
c = b • get_a( ); // a cannot be used directly
(i) It is initialized to zero when the first object of its class 1s created
No other initialization is allowed.
I-
} (ii) Only one copy of that member is constructed for the whole
void D : : display( ) class and is shared by all the objects of that class, no maner how man::,
{ objects are created.
show_a(); II outputs value of ' a' (w) It is visible only within the class, but its lifetime is the ,,hole
cout << "b ::" << b << "\n"; program.
cout << "c ='' << c << "\n"; Static variables allow us to maintain values common to the entire class.
}
For instance, a static data member is used as a counter that records the
int main()
occurrences of all the objects. Program given below illustrates the use of a
. Methodology (t/1-Sem., CS-Branch) Unit - II 85
84 Objeel Oriented Programming &
following progrnm shows the implementation of these characteristics.
!.\a\JC data member - 'fhC I de <iostreom.h>
. h> ~il1C U '
#include <iostream• c1ass test
using namespacc std :
class item
I int code;
I/static member variable
static. int count;
ubhc:
iutic int count: P void setcode( )
int number:
{ code = ++ count;
public: .
,•oid pta(rot a)
loid showcode( )
l
number= a; { cout <<"object number :"<< code <<"\n";
count++;
!tatic void sbowcount(void) //static member function
~id gctcount(void) {
cout<<"count:" <<count<<''\n";
l }
cout<<"count";
cout«count<<"\n"; }; u t·
int test : : co n '
int main()
}; {
int item : : count; test t1, t2;
tl.setcode( );
int main()
t2.setcode( );
{ test : : showcount( );
item a., b, C ; I/count is initialized to zero
a.punt(); I/display count test t3;
t3.setcode( );
b.getoounl( );
test : : showcount( );
c.getcount( ); I . da . · tl .showcode( );
a.getdata(lOO); / getting ta mto object a
.-.1.i.1200) I/getting data into object b t2.showcode( );
b•15"- ; I . da . b. t3.showcode( );
c.getdata(300); / getting ta mto o ~ect c
return O;
'i
l
cout<<"After reading data"«·"n";
}
a.geleount( ); I/display count
b.gctcount( }; Q.5'. When do we declare a member ofclass staJic ?
c.getcount( );
return O; ,4,u. We declare a member of class as static, when all objects of the same
}
Static Member Fll.lldions - Similarly, there are static member functions.
class share a common item of information. A static data member is available
oolywithin the class, but it continues to live till the time program execution does \-·
I~
,ootcome to an end. In that sense a static data member is similarto the ordinary
A member function that is declared static has the following characteristics -
1111ic"Yli'iable.'However, their utility is different. While a normal static variable is
(i) A static function accesses only other static members (functions .uw:d to•ictain infonnation between calls to a function, static data members of a
or variables) declared in the same class. ·.·class ue used ·to share information among the objects of a class.
(ii) A static member function is called using the class name (instead
Q.59. What is the difference between register variable a11d automatic
of its objects) as follows -
milble ? Explain with example. What are other storage classes for
class_name : : function_name; vcriobles? (R.GP. V., J1111e 20IJ)
odology (111-SPm . CS-Bronu11
86 Ob,1ec1 Onented Programming & Meth • , ·
Un,t - II 87
15 u
.
during ,, h, (lilJ Static I ~r,~/J~es - Tl_1c static ~to rage cla,s
◄n~ The extent Clf the ' anablc is the pcnod of tune Stora,, ,ti ' • hose scope is ltm11ed to cllhcr a block· a c ton or asetl
fun t f"I
to defi ne a
t d . th a \'anablc It is charactcm ed by • t,C l l t,1cw Tl I c and exten t
.
mcmon ,, ns~C1e1a e "' lr ~pccifics · of o progr·am. ,c globa l heap allocates th c rncm
the allocat1on of storage ~I)'"cc a,\t-. 1.,;, ,. -n
01~~,,- bl s • . for
. · · -
·,
Th r '-l(lragc c as5 o :i ' f ·anab - . 1
d global vanah cs. tat1c vanablcs that arc dcIi1necl wnhory space
1s defined b,- thc, ~,,fl u, 11tt . ... c
.
..1r b, thc comp1 Ier. The extent of a variable
6. ..tst,UC•· in a ,unct ion
, annll
.
\\,
1
tat\ >.Y' ,.._:, vnlues from t c prev ious call. For example .
- , 1, - of storage classes in ('-H as folio ·nII"'". <iostream .h>
I Th ere arc ,0ur . .,_. - .
c as$e~ ttC'1 #includ.c (VOi'd)
(I') ' ◄ ".,
1,n l'nn'o blcs- All the "anables arc defined as auto I •IT)Jhl 'd rnnt
.. .,
lock 1s entered and uc,1r ~ ,,01
I I
t
..,,~ dcfau II They arc crcat~w" "hen the function/b , . 01
(
I
auto, anablcs lhc rncni o...' ' 'P·-~ stlltic int count = I ;
·h th fun tJ n/bl(lck is finished. For local. bl · 'bl cout << "count = "<<count <<endl·
v. en c c o are v1s1 c to all the n;odu~
,~allocated ◊n the slllCk. The global auto vana cs count = count + I ; •
maa y t1rnc , uni 11~c lh,~
therefore · lhe)' are not defined
of a program and
;!
J
declaratJons. For example -
Ancludc <iostrcam.h>
••~tmain()

int cube(int a);


{ print( );

J l
int main( )

auto int x = 6;
cout «"Cube of" « x <<' is : • << cube(x); 111C

slllllg o
print( );
}
.,,, program outputs a sequence

of numbers stan· wi.th I. .instead f
• tng O a
. f 1's. Although, these static vanables cannot be accessed from other
} of the program. .
int cubc(int a) (iv) ExJern Vana
fl111S bles - When a prog ram span s ac ross d'"'
tuerent files
. . • . van· bl '
{ matio n usrng glob al van ables . Global
...n share infor a es are defined
auto int temp; die)',...... b h
.•1voncein aay of the.p rogram module and they are accessed Ya11 ot ers It
tcm p=a •a•a . . sueh vana . bles as extern variables It ·
{)Ill/
. btained by dee anng 1 · conveys the
rctum(temp); is o • . .
..-nilertbatsucb vanables are defined m some other file· Forexa mp1e, consider
"'",. .
is speeded ,piograin having the following files - .
(i,J Registu Jlariablts - The execution of a program bles
by the allocation ofCPU (processor) register to
variables. When such "ariab!Up · /ffilel.cpp : module one defining global varia
ber of variables, \.\ hich a~ int done // global varia ble definition
are accessed memory is not referred. The num ion - void funcl ( )
declared as register arc limited (typically two
or three), within any funct rt

bles executes faster th~ {


I as global variables. A program that uses register varia
1! is the responsibility of~
'I a similar program without register variables. It
are treated as auto variable1
~mp iler to allot register variables. These variables }
e frequently used variables
I 1f the compiler is unable to do so. It is better to defin void disp()
indic es, as register variables. For exam ple -
like loop {
#include <iostream.h>
#include <string.h>
{
}
char name(30];
register int i; //file2.cpp : module two of the project
cout << "Enter a string"; extern int done //global variable declaration
cin >> name; void func3
cou! « 'The rever se of the string is"; {
for(1 = strlen(name - I); i > = O; i - -)
cout « name[i];
w u,.., ..~,..o!ogy (/11-Sem CS-8 =

~ O!J.oeO o,ented Proqram,'Tlln-;J <> ,...,.u...,v · u rict,1
Um/ - II 89
In file 1.,pp. 1hr statrmcnt hllS the following steps
. . ~ . mtb~o~c. global ,"311ablc. In tilc2.cpp. the ~tatcrne IJ.1fll'ge (i) Creating cla_sscs tbat define Objects and their beha\ •ow.
oelm~ th, ,-ar1a c onr 35 3_ n, (ii) Creating objects from class dcfinttions. and
c~cm mt done. . . r. d . j · h.
. d d ,_.ifics that 11 1s dc1me m some otJ, , (iii) EslJlbhs mg communicat10n among objects.
\lrc\a,-c$ the ,-anab1e one an 5r · er filr . .
..__, th ..,_fi tioo of the ,--ariablc done must appear man) one b·..-ts communicate with one another by sending d
ts nN.COu14t CU\:lnl • II of, I o~~~ an recen 1ng
1'1'.10dule5... w ~ e.,'lCm declaration can appear m any or a module~n~ . tion much the same way as people pass message to one another. ObJects
,.,__ ._,. binds all ~fercnces to the same memory location 11 h I of~ 8 life cycle. They are constructed and destroyed Co
nrogram. ''"" 1Ina.Cf th • bl d en ...nlllD . . . · mmunicahon
• bl- Thus an)' changes to e van a e one 1s , 1, bi t ~- is feasible as 1ong as 11 remains alive
t -·-'-
~---c-unrm i,uu, ,-ana '""· • ", r I ·tb an ob,iect ~ . . .
all the modules ~ g i t ~ fl Objects in nn obJe~t-onente~ programming interact by send ing message
.j . . ~ n ,.,w, tu1 aampl~ . e another. For instance, 1f there are "customer" and "ac C
Q." Eqlol ,,.}«I eed \\1th on then the "customer" object sends a message to the ace:~ ~-n a
Alu. lo order to insWdiate objects. we n
. C As
11
to ~ on an abstract ~ P'°~g- for bank balance. Customer object has data and code to un
blow each class has a umque name by 11 h rcques b' . .
° ~lect
man1pu ate
t\'J)C _ 1 daf m ++. tch t' d8ji·.Customer o ~eel interacts WJth account object without h •
"hl
"'C • . .
· . Obj instantiated with uruque names are th die h , d d . avmg to
m1y be identified. eds . . . osc ow details of each ol er s ala or co e. Objects can interact without having
lifcrimes and identities~ p~ctablc at comptle_tun~.
An object i.s instantiated m C++ by declanng its type, followed b) ,
name.just lil-e od!e:r data typeS. For example,
-ge
: }JloW details of each other's data or code. It is enough to know the type of
acce~ted and the type of response returned by the objects during
objecl intet"dcbons.
ial x; II an insamces of type int Q.62. Describe /,ow objects inJeract and how they are instantiated.
char y; // an instances of type char
BankAa:omltz; // an instance of type 'BankAccount'
~"bell w e ~ x to be of type in~, it m~ ~t w~ can treat x
j Or
(R. GP. V., Dec. 20I I )

DtScribe /,ow objects are instantiated and how they interact with each
the sameasmyodlcrdlll:F',and perform mtcgeranthmetic on 1t. By dee!~ od,tr? (R. GP. V., Dec. 20 I 2)
z to be of type 'BantAccount', we tn:at z as any other BankAccount, w · Ans. Refer to Q.61 and Q.60.
means ii will ~ the aDribules md methods defined by the class.
Q.63. What uan object ? How object oftwo differem classes can interact ?
Q.IL Wrilt • sl,,tt .ie •11 ol,jet::t iltlaw.dio,u. (R.GP. V., Dec. .zoa~ Gfreane.xampleforiL (R.GP. V., June 2010)
Or Ans. Refer to Q.8 and Q.61.
H,w "'1j«a •/two li/faot cmses ca illlDwct 1 Giv~"" exampltfi
iL . (LGP. V., J,au 2005, Dec. ZOJJ, Q.64. What are the diflerent forms of message passing ?
AllS. A,eqoest fnra.eaJtioo ofa procedure is a message for an object, ~ Ans. Message passing may take one of the following forms
M---..
tberdore will call a filnctioo in the .receiving object that provides the dem
ff!SUJt.
___... , -
c:cin · 1••..i-...
g
• •
mclUUQ specifying
the fimction ( - ) __.., the ,_r.
the
- be
fth b"
.
th
name o e o ~ect, e name ,
~
llas wtta
.
·
e action an
d th ·
.
(i) Synclrronous -An operation commences only when the sender
. . - ted th · d
e receiver 1s rea y to accept the message. the
-U&ai<oaiF~- aou m1onnaboo to sent For mstance - =ran receJVer w wait m e mite y uni! oth parties
d _,1_· ill · · d ti · I ·1b · are read) to proc~d
Employee.Salary(name);
(ii) Balking- It is same as synchronous. except that the sender ,111!

Obj~ i
Message
~rmation
abandon the operation if.the receiver is not immediately ready.
(rii) Tune Out - It is same as synchronous, except that the :,em.kr
An obiect-oriented mad f f . . -~will only wait for a specified amount of time for the receiver to be re:i.dy.
• J program e o a set o obJects that commuruca -.
with each other. Therefore, the process ofprogramming in an object-orienl:! .,.: (n,) Asynchronous - A sender may initiate an action regardless of
;i-1-hcther the receiver is expecting the message.
90 o:,•e.::J O,..ented Programm m:i & Meth odolo gy Unit II 'J:
(/1I-S em , CS-B ranrt ,
(! _ ll'/ra f ;,. mc<.<:agc pa,, ing? I/OH ' ohjc
c~ arc inlt' r<u red ,,;,,, , Q 6 i ,VJ,al is con' itruc tor ? I/ow it;, decla r 111
Gnflt l, cr65"! (R.G l ~ I ''{ ' . ed and d ,r. d ?
·· \ ,, ,_ 2 "'..,.
, .. ~. A cons tnJct
. eJ
4 n'- Refe r t<' Q 6 1 and 011 I ber fu ncuo n o f the cl.i~•, It eI ') CJ
orf 1!, a mem •
II <.:d LJLh
Q 64 (l f11C \\•hen an• •obJc
,rca ed an init1ah1..at
• ct. o that c a~s
,.., t.:rcatl.!dn,. .
rcfor c • v.h en JO O JC::CI 1'-
. 1on . needs to be d one ,, h1c h auto mau call d bh
Q.66. Witlr thl' hdp ofa comp/ct~ _c++ P_rog Y one > th
(i) Cfa..,;s dcc/11ration
ram illus~ratc the f oll,,., Ui t... ,ctor func tion.
coll Su., It ts know n as cons truct or since 11 cons· tru
C l <, l h C \ J UC
' 1
(11) Ob1ecl dccl arat wn ,
(iii) Mes ~gc pass ing of dota members o f the class .
(fr} Obje ct passing.
A cons wcto r is decl ared and d efine d as follo
Ans. The follo wmg prog ram 11!ustralCS the v. s
decl arati on o t the l ., .., , 11,.
J ecl:lr 2tion oi obJccts with the opcr auon c1ass integ er
s on its obJe~ts a nd nb 1.:\.I l',1',, ~,
= inclu de ,,0~ 4m .h>
g int m, n;
usmg namespac c std;
class time //cla ss decla ratio n publ ic :
integ er(vo id); //con struc to r dec lared
(

l·:
int hours;
int minuteS;
I j publi c: };
.. l void settim e(int h, int m) integ er : : integ er( void ) //con struc tor de
fined
f hours = h: minu tes == m; {
} m == O;
void gcttime(void) n == O;
(
cout < < hour s << ..hour s and" ; A cons truct or func ti o n has same nam e
colll<<m inut es<< ..min utes "<< ..\n ..; a~ the , lass of,, hich 11 1s o pon
3nd has no retur n type in it.
} When a class has a cons truct or, tl ensu res
void sum(time, time); that an obJl:.'.CI creat ed b) the cla~:,
will be initialized auto maticaUy. Whe n an o bJect
}; ot that dass 1s ercat c<l.. 11 m1u:iltn::,
its data members. It is not requ ired to call the
void time: : sum(time ti, time t2) con,tructor function ,epdf'Jtel) .
{
Whereas the norm al mem ber func tion 1s d efine
d m the cla~s and ,, e \\ ant
minutes = t I .minutes + t2.minutes; to i n i ~ that_mem ber d ata. the n we need
to ca ll them :,ep:irate l) Th ,..,,, ould
hour s= mi_notes/60; be inconvenient, if there are a large num
ber o f objc c b .
minu tes = minutes %60; A defaulJ cons truc tor is a co nstru c to
r that acce pts no p:ira mete rs The
hour s= hours + ti.ho urs + t2.bours;
'default cons truct or of class A is A : : A( ).
} If no defa ult cons truct or is d e fin ed. then
int main ()· the com piler su ppli es a defa ult
{ . const ructo r. Ther efor e, a state men t
time Tl, 12, TI: //obj ect decl arati on Aa:
TJ .gett ime( J: 45); //message pass ing. calls the def?, ult c~ns truct or of the com piler to
c reate the obje ct a.
T2.g ettim e(2, 30); //message pass ing Q.68. WJ,ai is co11struc tor ? Is it ma1rdatory to
tL'ie com truct or i.11 a clas!, ?
T3.s um( TLT 2J; //object passing (R.G P. V.. No ,·. 20/ S)
cout << ..Tl = "; T 1.genimc( );
cout << "'TI = ...; T2.gettime( ); Ans. Refe r to Q .67.
cour << .. n = "; . TI.g ettim e( ); It is man dato ry to us e cons tructors to
in itia lize inst:ince \'an.a ble in :i
rerum 0; · dass. One the obje ct for the class is erea :~d.
92 Ob;ect Onented Programming & Me th0d 0 l0gy (//1-Sem., CS-Branch)
Unit · II 93
Q. 6 9_ Write tlu characteristics ofconstructor flm_ctions. t work. For th is we wi ll have to pass initial \ al
..,ny no . I b. . uc, as argurncnL, l ti
'" ctor funct10n w 1en an o 1ect is declared. That .1 n h:
Ans. TI1c consrruc 1or fw1c11o ns ha ve some special c harac1cr1 ~11l' constrU . . . . . :-,
'~ ioteger m I = mteger(O, I 00), //explicH call
fo llows -
(i) They should be declared in the public sect1~ n. or
( ii) They do 001 have return types, not even vo id and the) c integer in I (0, I 00); //implic it ca ll
ann,)
I return values. . l that, when the constructor 1s parameterized lhc appr
It ·s .
I I . , opnatc argumt:n~
(iii) They are called aulo~atically when the obJects an: created constructor must be p rovided.
I I. (iv) Like other C++ functions, theygJcao hdav~ default arguments
th
for e
·Q. 72. Distinguis!, betwee11 tire followi11g two statements _
(v) They cannot be inherited, thou I a enved class can calJ lh:
I l
Time Tl(TI),·
base class constructor. .
IJt · (,-i) They cannot be referred by their addresses. lime Tl= Tl;
(vu) Consuuctors cannot be virtual. Tl a 11d Tl are tire objects of c:lass time. (R. G.P. v., D ec. l00S)
l
(v-w) They make 'implicit calls' to the operators new and delete 11 hen Ans. A copy constructo r is used to declare and initialize an object rrom
memory allocation is required. nnothcr objecL For example. the s tatement
(!. JO. What is constructor? List ti,~ properties ofconstructor functio~ Time T2(T I);
(R.GP. V., June ]OJ~ WOuJd define the objec t T2 and at. the same time initiali7c it to the, aluc~ ofT I
Ans. Refer to Q.67 and Q.69. Aoother form of this statement 1s

Q. 7J. Wltat is parameterized constructor ? Explain.


Time T2 = TI;
The process of initializ ing th rough a copy constru ctor i!:t kno,1 n .t:, CUflJ
Ans. The constructor can also be used to initial~~ ~e-data members ofal! •,uJializotion. Herc the statement T2 = TI; ,1 il l no1 im okc th, ip) 1.vm,LruL IL)r
the objects to zero. Although, it may be necessary to m1bahze the different ~
~owever, if Tl and T2 are o bjects, thi s statement is lega l and ,1mpl) a,, 1gn,
elements of different objects with the different values when they are created
the values of Tl to T2, member-by-member. This is the 1ask of the 01 crloaJL,J
C++ allows us to get this by passing parameters to the constructor function . as.signrnent operator (=).
when the objects are created The constructors that take arguments are kno111
as ptu11111derizP/ constructors. Q. 73. Write a s!,ort 11ote on destr11ctors. (R.G.P.V., Nov. 2018)
Or
Eumple-
class integer Explain briefly dutruction. (R.G.P. V., May l0/9)
( Ans. The complement of the constructors are the destructors. The
int m, o; destructor function has the same name as the constructor, but it is preceded
public: bya~(tilde sign). The objective of a destructor is to kill the object and to help
integer(int x, int y); // parameterized consttuctor in releasing the memory occupied by the object. That is
- integer()
};
{}
integer: : integer(int X, int y) A destructor never takes any argument nor does it return any value. It is
( invoked implicity by the compiler upon exit from the program ( or block or
m =x; function) to free the storage that is no longer accessible.
n = y; Q.7~ Erpla,COllsllmor '11111 MSlnldorwillf aaa,ples. (R.G.P.V., D«.1001)
}
Or
When a constructor has been parameterized. the object declaration ofit ' Diff~lllil,te /,dwea, co,utructor •nd tkstr11etor wiJJ, suilllble aample.
statement like (ll.GP.V., May 2019)
integer in l;
9.d Ob1ect Onented Programming & MethOdology (l/1-Sem.. CS-Branch) Unit - II 95
copy constructor is defi ned the compiler .
4m:. Constructor - Refer to Q.67 ,vhcn n0 , upp1IC~ Its 0\\ n l()n \
n5trUCtor·
The copy constructor
.
allows us to inswnii-ate an ob~ ect . ,,,.,
Destructor - Refer to Q.73. CO of another in terms of ,ts attributes values. as an nau
E:xamplr- coPYocfinition invokes a copy constructor A constructor th l
. . . . a creates a ncl\
=mcludc <1os~am.h> . ond copies ,ts argument rnto 1t. The defau lt copy c ·
class class_name obJCC1 . b . onstructor which 1~
·dcd
provt automat,cally y the compiler for cvcrv obicct p ,.
, J , er,orms a rnembcr-·
int a. b: by-niember copy. . . .
Th e copy constructor 1s invoked when
. an obJect is· nas
,- sed bY , a1uc to .1
public : .
class name(int x, mt y): //Constru~tor ·on It creates the .copy tliat the function operates on Thus • 1f th e 1•unction
_class name{ ): //destructor function
flJllC U ·
void func (alpha),
void show( ); declared and this runclion were called by the statement
were
I; . . ) func (al);
class_name :: class_name(mt x, mt Y then the copy constructor would be invoked to create a cor y of the 31 object
{ for use by func( ). .
a= x;
b = y; Example-
#include <iostream.h>
)
void class_name: : show() using namespace std;
class code
{
cout <<"\n a=" <<a<<" b =='' << b; {
int id;
} public:
class_name :: -class_name()
code( ) { } // constructor
{ code(int a) {id = a:} // constructor
cout « "\n Destructing the object :'';
.
• I }
code(code &x)
{
II cory .:onstructor

int main() id= x.id; // copy in the , alu.:


{ }
class_name obj(6, 8): void display( vo1dJ
obj.show( /; {
return 0: cout << id;
) }
The output will be };
a == 6b=8 int main()
Destructing the object : ( .

Q. 75. What is 111ea11t by copy constructor ? What type ofoperations ll'il/ code A ( I 00);
code'B (A);·
cause tJ,e copy constructor to be invoked ? Write a program to display tht ) . .code C == A; · •·
use-ofcopy constructor. code, D;
Or D=A; · · .
1
b.plai11 w/1a1 l)pe ofoperation causes to callcopy constructor.to be i,woked. . co·ut << "\n id of A : " ; A.display();·
Write 011 example to sltow the use ofcopy constructor. (R. G.P. V., Dec. 2015) cout·« "\n id of B : " ; B.display( ); ·
cout « "\n id of C : " ; C.<lisplay( );
Ans. A copy constructor takes a reference to an object of the same class as of
coul <~ "\n id D : '' ; _D.display( );
itself as an argumcnl A reference variable has been used as an argument to the retum··o;
copy constructor. \ 1.'1? cannot pass Lhe argument by value to a copy constructor
Unit-I/ 97
& Methodology (/11-Sem .. CS-Branch)
96 Ob1ecl Onented Programming
t can be used on any objects \\ 1thout b. object -
The dcfuult copy construe or . ,· • ~1ng .,..,charf.lY#.,nelude <iostream.h>
h>
ex licttlv defined. though it is poss1bl~ to pr~\ldt: a user d,cfi ncd l'op\ #iflclude <new.
·p · dd. . _, rocessinl! is required, or 1fthe default bch,l\ iour 1 #' elude <cstdlib.h>
c0 nstructor1fa 1t1ona.ip ~ . . s·
the obiccts contain pointer. mce the ck•i:
~1n ~ g namespace std;
• 1..~
ropnstc perhaps \J\."'-'ause J au1i us1n
aPp · . pointer address rather than the data they refcrcn . class array {
copy construct?r copies to override this behaviour. le,
int • p;
we may have. m some cases, int size;
-6 u/J.at is tht importanct of copy constructor ? Under IV/,i('i, public: (. z) {
Q, I • ,.-,. • ? c-•. array ID1 s
con4iaon txplicil dtftnition ofcopy constructor IS necessary . .:.xp/ain by
(R.GP.V., June 20 15 try{p = new mt ' [sz] ;
proptr txiUIIPl4 . . J
. rtBnce of copy constructor ts descnbed below. Let ·s belll } catch(bad_alloc xa) {
Ans. lbe unpo . d . d .,,n cout« "Allocation failure\n";
by restating the problem that, the copy ~onstructor 1s es1gne to solve. By
exit(EXIT_FAILURE);
d fault when one object is used to initialize another, C++ perfonns a bitwise
;PY, that is, 80 identical copy of the initializing object is created in the target
}
size = sz;
object. Although this is perfectly adequate for m:my c~es (~d g~nerally exactly }
what you want to happen) there are situations m which _a b1tw1se copy should -array( ) {delete[ ] p ;}
not be used. One of the most common is when an obJect allocates memory // copy constructor
when it is created. for example, assume a class called Myclass that allocates array(con_st ~y _&a);
void put(mt 1, mt J) {
memory for each object when it is created, and an object A of that class. This
if(i > = O&& i < size)_p[i] = j;}
means that A has already allocated its memory. Further, assume that A is used int get(int i) {return p[1];}
to initialize B, as shown here - };
// copy constructor
Myclass B = A;
array: : array(const array &a) {
If a bitwise copy is performed, then B will be an exact copy of A. This inti;
means that B will be using the same piece of allocated memory that A is using.
try{ . . ]
instead of allocating its own. Clearly, this is not the desired outcome. For p = new mt[a.size ;
example, if Myclllss includes a destructor that frees the memory, then the 1 } catch(bad_alloc xa) {
same piece of memory will be freed twice when A and B are destroyed. cout« "Allocation Failure \n";
exit(EXIT_FAILURE);
The same type of problem can occur in two additional ways - first, when
a copy of an object is made when it is passed as an argument to a function; } . = O; 1. < a.s12e;
for(t . 1++. ) p[')1 = a.p[')
1;
second, when a temporary object is created as a return value from a function.
Remember. temporary objects are automatically created to hold the return int main()
\'alue ofa function aad they may also be created ia certain other circumstances. {
array num[IO];
To solve the type of problem just described, C++ allows you to create a inti ;
copy co11s1ructor, which the compiler uses when one object initializes another. for(i = O; i < 10; i++) nwn.put(i, i);
When a copy constructor exists, the default bitwise copy is bypassed. for(i = 9; i >= O; i- -) cout « num.get(i);
cout<< "\n"·
Following is an example where aa explicit copy constructor function is i // create another array and jnjtialize with num
needed. This program creates a very limited "safe" integer array type that ' array x(num) ; // invokes copy constructor
prevents array boundaries from being overrun. Storage for each array is for(i = O; i < 10; i++) cout « x.get(i);
allocaled by the use of aew, and a pointer to the memory is maintained within return O;
98 ObJed Onenred Programming & Methodology (/11-Sem . CS-Branen
Un,t - II 99
No" loo~ clo~cl) at" h:it happens " hen num is used tu in1t1a'111; string(char •s) II constructor
\ Ir,,
st:itcmcnt {
length = strlen(s);
array :\(num): in\'Okcs copy constructor name = new char[length + I ];
The copy constructor is called. memory f~r the -~ rn arr.i) i :. JlloLJtcu ..
stored in Lp. and the contents of num are copu:d to x s arra). In tl11~ \\ J\ -.,
// one additional character for. o·
strcpy( name,s ):
oum ha,·e arrays that contain the same va_ lucs. but each array 1, \L:PJ;J·1:
distincl (That is. num.p and x.p do not point to the ~ .e piece n'. n1L:ll1nn ~
i: } d1splay(v
void .
o1"d)
the copy constructor had not been_created, the default b1t\\ isc in~tiahlat1on \;1,L {
ha\'e resulled in x and num shanng ~e same memory for th_cir arr-a~ , ''lna1 cout << name << "\n":
num.p and LP would have indeed pointed to the same locat1on). }void
Notice that the copy constructor is called only for initi~lizations. For e,ani join(stnng
. & . &b);
a, stnng
this sequence does not call the copy constructor defined m the above Prngra: 11 }; void string : : join(string &a. string &b)
am1y a(l0); {
II .. - length = a.length + b.length;
delete name;
array b( IO); name = new char[lengtl1 + I ];
b = a; // does not call copy constructor
// dynamic allocation
In this case, b = a performs the assignment operation. If ' =' is strcpy(name, a. name);
overloaded (as it is not here), a bitwise copy will be made. Therefore, in so: strcat(na me, b.name);
cases, you may need to overload the = operator as well as create a co };
constructor to avoid certain types of problems. ii! int main()
,, Q. 77. Expbtin tire use ofdyna,nic constructor wit/r example. {
char •first = " Rahul";
Ans. The constructors can be used to allocate memory while creat' string name I(first), name2('"Kumar"), s I:
objects. This will enable the system to allocate the right amount of me~ s l .join(name I, oame2)
for ~b object when the obj~cts are not of the sam~ size, thus, resulting in th( name I .display( );
savmg of memory. AJlocation of memory to obJects at the time of then name2.display( );
construction is called the dynamic construction of objects. The memo ' . s I.display( );
allocated with the help of the new operator. ~ return O;
Enmpl e-
#include <iostream.h> Output -
#include <string.b> Rahul
using namespace std; Kumar
class string Rahu!Kumar
{ Q.78. Explain the various types of constructor 111itlt a11 1rogrammi11g
char •name; aa,plt. (R.G.P. 1~. Nov. 2019)
int length;
public : Ans. Refer to Q.71, Q.75 and Q.77.
string( ) // constructor Q.79. In which order are the.constructors and destructors called when
( 1
11n object ofdie derived class is created aplai11 wit/, program
length = O; .
name= new char[length + I]; Or
t Write a program ;,, C-++ to s/1ow how co11structors are implenre11ted
INlln 1/,e classes are i11heri.Jed. (R.G.P. V., Der. 2016)
00 ObJed onente d programming & Method ology {111-Se m . CS-a
1 raric1-,
An.~ The constru ctors play an important ro le in initia h 7 ing nh class derived : public base I, publ ic bas e 2
J Ctt
deriYed class nec-d not ha\'e a constru ctor as Iong as tJ1e b~c
da \,. 1lu ' r, {
argume nt constructor. However. if tlle base class h as cons truc to publ ic :
. . r th d . r '• ,,.
o r more .. rm,men ts tllen rt 1s necess ary ,or e en ved c las~ ' \\ Ith deri ved( )
-b- • .
cons tructor and pass tlle argume nts to tlle base class constru ct l o h·
. . d I
applica tion of inheritance, obJCClS of tlle denve c ass are created or~ I •1. {
. I k-nn cout<<''\n No argu men t constru
ctor of lh e den\ ed
makes sense for the derived class to pass argume nts to the co ns tru
. ed I . d h ce } class dem ed":
base class. When an object of a denv c ass 1s create . t e cons truClor of
Clor Of ~,
base class is execute d first and then the constru ctor o f the d em cd - derived ( )
c l I:,
Unlike constructors. destructors m · th I b.Jerarch ass {
. . e c ass y a re in vok ,
reverse order ofthe constru ctor mvocat ion. The d estructo r of that cd in .
cout <<''\n Destruc tor in the derived class dem ed'';
c l 11 It<
constru ctor was execute d last. while buildin g object of the derived
~s h°"<
be executed first. lf destruc tors arc missing in any class in 11
the hie ass. };
classes, that class's destn.tctor is not invoke d. The follow ing progra int main()
:rch} ~,
the order of invocation of constru ctors and destruc tors in handlin {
g i 5 sho-.
of a derived class - derived d ;
n 1anct
//order of invocat ion of constru ctors and destruc tors retrun O;
#includ e <iostre am.h> }
class base I //base class outpu t-
{ No argume nt constru ctor of the base class base t
public: No argume nt constru ctor of the base class base2
basel( ) No argume nt constru ctor of the derived class deri ved
{ Destruc tor in the derived class d erived
} cout <<"\n No argume nt constru ctor of the base class b ase 1~ Destru ctor in the base class base2
-base l() Destru ctor in the base class base I
( Q.80. Can II constructor be privat e? If so what it means. How to 11se as
·cout <<"\o Destru ctor in the base class base I"·
} ,
a private?
Ans. Yes, a constru ctor can be private . A private constru ctor taking no
}; arguments and having no other constru ctors. A private constru ctor
class base2 //base class is a special
instanc e constr uctor. It is comm only used in classes that contain
( static
members only. In such a case, other classes except nested classes
public : are not
base2( ) allowed to create instanc es of this class. For examp le -
{ class Mycla ss
cout<< "\o No argument constr uctor of the base cl& {
private Mycla ss( ) //priva te constru ctor
} { }
~base2 {)
{
public static double e = 2.7182 8;
cout<< "\n Destru ctor in the base class base2" ,· }
The declar ation of the empty constr uctor preven ts the autom
} atic
genera tion of a defaul t constr uctor. Note that if you do not
}; use an access
modifie r with the constr uctor1i t will still be private by default .
Howev er, the
& Methodology (/11-Sem., CS-Br anctiJ
102 ObJed Onented Programmmg
. ' used explicitly to make it clC.Jr l~at the cla,,
pn\'ate modificr _1s usuall) ,-1 , ·(an example ofa
c.'.lilnot t-.e mstant:Jatcd. The fo O\\ mg 1• class using a pn1 a1,
c
:-onstructor - _
usmg Sy$1.em :
public class Mydass

pm11te Myclass( )
l l
public static int counter.
public siaric int IncCowit( )
~ oNSHIPS - INHERITANCE - PURPOSE AND
' mum ++coll lllCr; ~ - · 'IS A' RELATIONSHIP
ns TYPES
'
}
clas's MaiDClas.s p_.J. Defrne the term inheritance witl1 an exam ple. '
{ (R.GP. V.. June 1016)
sutic void main( ) Or
{ Whal does inher itanc e mean ? (R.G.P. v., Dec. 2003)
//lf'JOU comment the following statement, it will gener
ate Ans. Inheritance is the process by which objects of one class
/Ian error because the constrUctor is inaccessible acqutre the
//Myclass myobject = new MyClass( ); //Error properties ofobjects of another class, i.e., inheritance 1s the process of crealin11
~ cJasstS called derived classes, from the existin ~ ,
Myclass.counter = I00; g classes, called base classes
Myclas.sJncCount( ); Toe derived classes inherit all the properties of the base classes,
Console. writeLine ("New count : {O}", Myclass.counter): but can add
tbeiroWD properties. In this process, the properties of base classes are
unchanged.
The general fonn of defining a derived class is as follow
s-
class derived_cla ss: visibility_mode base_class
{
••••••
• ♦ ........... II members of derived class

};
Here, the colon indicates that derived_class is derived from
the base_class.
The visibility_mode is optional, and if it present, may be either
private or
public. The default visibility mode is private.
For example,
class ABC : private XYZ II private derivation
{
members ofABC
};
class ABC : public XYZ // public derivation
{
members of ABC

You might also like