0% found this document useful (0 votes)
31 views21 pages

Oops

The document discusses the benefits of object-oriented programming (OOP) over procedural programming, highlighting aspects such as modularity, reusability, data security, scalability, and polymorphism. It also covers various programming concepts including type conversion, constructors, enumerations, variable scope, and friend functions. Additionally, it provides examples of code implementations in C++ for better understanding of these concepts.

Uploaded by

wowiha6191
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views21 pages

Oops

The document discusses the benefits of object-oriented programming (OOP) over procedural programming, highlighting aspects such as modularity, reusability, data security, scalability, and polymorphism. It also covers various programming concepts including type conversion, constructors, enumerations, variable scope, and friend functions. Additionally, it provides examples of code implementations in C++ for better understanding of these concepts.

Uploaded by

wowiha6191
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Assin ment

Explaun in breit he benelits ot obpct- oriented


Progsomnming oVer procedure Os ien ted
rgtamting
Tho beniity of otject oriented pro tamy oo)
Over procedare osiented Prgiamning ae

given below :
9 focus i- 00P Jocus on dta athes than PoP treat
Codes sequence pro ce duse,.
2.) Modulaiity ?- 00 P gaizes
0daanizes Code into objet cohich
bundle togethes clota and method, This
apfroach akes prog1am easies to manae
amdl maintain Compaed t Pofs linen fhso.
3)
Reasability: y wmg inhevitamce,
8ame cade and efeate
we can seed
cayses based on
he

ersting ones, t oneduce Code redundant and


improve code maintajnan ce.
4) Data SeCuity i- En capsulation in 00P. hidep am ohjeci
data ipro teoting t oen uintended intelesence.
To Pof, dato is o fen go Baly acc ess ble.
5)scalability 00 pf is etta suted foo manag ing
comþlex and brge-s cale aplication os it emþhasizes
ea stouctue.

6)kvibi lity 3- 00f's polym eshism enabies a singe fnti


nd method to wosk d! erently bayed )
project, injnoving
ott, Java,
tevibity
python, C#,ete.
Tn short, o0p heps CTeqe cleanes, reusable and
flesible code. yaking it great fos lage sale pryjit.
smhes bmd dsk vel on sale yecfelak .
2.) hy do directiVe : # ncludee<kansteas
need Pre -pro cessor
Ani The Needed
re pro cessor directive 1 include <iostream
0) C+t, to incude the input -otput stea (ibsay
ohich pToVides functionality Sor hondling inpt (e-g.
{vom
Tom the key wovd) ovyd autpt (erg- da dhe console)
key (eatu -
Pre
processox nole i -tko # include dire ctive tell lhe
Com pier do inaert the Content oof 'iostrearo' header fil
intoyo code.
*|Access %to stomdod
stan T :-
I/o : ciostream > delines ohject
ke cin (for input) , Coullor ouput), cerlfor eOs
mSSAge) , cog l for dogging)
In short ,# incude <iostream tells the compile
include dho standad 0stream file uhich contain
declosation ¢ al! standas od Iyput /output bbray
tuncton, oi thout it, the compiler won't reconize
these functon amd youn wont able Zo þetorm
these T/lo opevation.
Q3)hat is the Iype convession? 6ive example
Anyi-ype Con vers ion , aso tnown
ype Casting.It
the process of converling a vaçable
one data ype do amothe rom
Tn ct t, it cam be classitied into
Zuo typey
L) Tmplicit type convesion ?
This is atom alicalyy done by the
expliit instxuction. Compilea wthout
Exam ple :
Int a zl0;
Ploot b= a; N a is
std ::Cot
impliity aowerted
eted fsom int to /hat
<< bjouP t 10.0.
2
Explicit tpe conveuion :

Cast opeatos , such a


Exomple :
float num S-7 ;
nt ses= (int) mum ; \Explcitly CoNet tloat to int
std Cout << Tes; \| output:s
4}) Can we have mose than one Constctor in class?
T} yes , enhain wth etnble.
a clas can have mose than one constCor,
Thia eis possible thsough constructos velaading,
whee multiple constructors
are cefined wstk dfisen
pauamele dit (der uin nanber, ype of
within the same cass. agument)
Example:
#include <iostream>
lsing name sh4ce std ;
class peTS on i
Sting ame ;
int
Pyblic :
personl) Delaut constryctox
nome= ( kahu,

Pesson (Sting n, int a)f\N pasa m


eteis ed cotcu
Ma me =n;
Faj
Pevsonlonst pesSon 4P) Copy ConStructor
name p. Dame j

Void dup lay (f


Cout <cName: 2< name ce 'age''e age c end d;

int main ()$


Person ;
pesson p2 ('Alice ; 23)5
Output
Pesson p3 =p2;
P! dis play)} Nane : Rahw, agei 13
Name Alice > a4e:2
display
P3. display); Nome :Alice , aei 25
3
S. |what du enurmeratioD ypes?
Ansi- Jn ctt enum ehaliom u wes-dehined data type that
consist o set d named integal consta nt.
Tn simple, In ths pe, we ue wosd instead o
umbes (cons ant). Enum mak code move Teadable
and mainta inable by reblacing litesal value it
meangtud names
Enample
# include <iosteam>
using nemespale std ;
enum

Red, Detauts to
Yellow 1Defoutti to I
GYeen, l Detauts
Defat to 2
nt man ()?
Tra ic ight signal Red ;
if (signal: - Red )8
Cot << SToP;
else 4(s igal - yeen)
Cout <e"Geen

Descri be s cope and lte o a Vaiable.


Ans: The scope of a vaniable efs to tho eg ion q4 prngn
hhs:
where ths Vaiable cam be accessed a used.
Tt determines the isibi l ity and acess/ bi lity of
Vaiable.
TYpe o scope i
* lo cal Scope ;- Declaued inside a tuncton oA Bock,
accessible On y with in jt.
Void fin ()
Int =I0; local vau ab e
Cout < ;

|* Global scope :- Decl aled otid e a tunctions, acessibl


though out he pogeny.
int x = 0; \ 4lobal scope
Void tun )

3
*| Block scope t- Exist wthin $3 and dust voyed atea
existing the block ;

Vo id fun (0f

Int
in y =20;
,f ny iss not acce ss ible heu
Vaiaþ le (nside a claK Car bp
Class Scope -
accessed using object.
Class student

nt x ;

:
Lle tine af a variabie
The dile time of aa Vaiable
Variable refs
a Vai able exist in) memo
* Auto maliu etime - when thei,
and cyeated
Vasiable declaned locally
is entered omd destoyedl cohen it
Scope
enited.

Void funlU
int temp=7; \\ Created here
Cout << temp;
} s destroyed hene
Statie i{etime
Veviable deoloxed as slatio as glabal
plobad scope exist for
entire proons duation.
static int coutt = o}
Void increment 0F
Cout ttj

* Dynamic ietime - -hese ae


ase Cxe
create duing xantime
mew and enist unti! dekted wing delete
int * dy namic an =neu int(so) ;
delete oyamic
Ihat s viTtua function? Exblain wiHb exanple.
PA vir tual sunctien s a membes unction that ip declasu
oithim a base cdayy and is sedelined (ovorden)
by a denived clas .

5 Virtuel funetion ens we that the Correct


is calle tor am obect unctios
efonce (a poirntey) sed or unetion call
They e inly wed to achieve untim
polymebhim .
fundion ae deol aved uith
vitas Feyword in a
basc clas
The Tesoving a tunclion (s done at ount in.
+include <iostream>
using namesbaes std ;
class Baye
Pub lie :
virtual void diplay (Of nvirtuei functton
cout <<Display method o Base claa)

class Derived : public Base


public
Void display () ovea ride f\l ove de the
baye class
Cout <<iDisp lay method d deived elass

int main
Base * base pt pointea to base clat
da
Deriveo obj Deived ;
base ptr= objpeí Ved 9 \\ base clas poinupomts to
deived obj
base ptY’ disp gcdls denived class duplag
method due to vitual
fan
WAP n
Mecwrion.
#include <iostsean
wsing name spas std;
int Sum Natwall int n)
(n==o) f
Yetyno;
retun n+ Sum Nbtual (n-);

int main()

COut <<" Cntes a Numbe;

Cout <e Emesa positive on';


ele, Sum Natual (num);
Cout "su is <<sm;
9 WAP in ctt to ind de Bansfose o a mabin.
# include <iostream>
sing namespace Jtd;
int main( )
Înt n, m
Cout <cEnter the No o MoWS column :";

int au Cn][m];
Cout <e Entey elemert: ";
for mt i-03 i<n; itt)
for (int j=D; jemitt
Cin >> au CiO ;
Cot<< Belore t ranspose 1< <endl;
for (int i= 0; i<n; it}f
for (int j=o; j<m ;jt t)f
Cout << au

Co ut <e 7sanspase . )<< endi


for int i >0; i<m; it)f
forl int yj= o; ish ijt*) f
Cout << au Cili ;
Cout << endd;

Ouput
Entea the No. o Roup A colum : 2-2e
Before tanspose
1 2
3 4
Aftes tronose
1 3
2 4
AAP m ctt to
to creat Ptamid patln
# include <iosteam>
using namspace std;
Cout <e "Entes Rows:
Cìn ros ;
fos Cint i= tj iken ; i+)F
forl int j= ! j<njt) F
99
Cout <<
for (int k= ;k<2 Xi-I ; ktt)S (8)
Cout < x";

otput
Entes Rous i 4

WAP to concatena hoo strings in ct +,


t include <iostseam
output
aying sameface
tt include <string
std; CnterAst strng : Harsh
Entersec ond
înt main (U$ Stin:huma
String Sl82 , 7es ; concatenate

cout sc Entex tYst stnng'"; sty:Has Cuns


get line lcin,sL);
Cout <e l Entey second string"';
get line (cin, s2);
Ues = S. + 82
Cout cc iConcatenaed string : c Tes 9

J2 What u fänd function? A riend qunction eant be


used to oveloap thw assignment qpeati().6rplain why?
A friemd unctin in C+t is a function that w hot
member o a class bt hop gecess b te puate
Ond proleted membes Khat cla. It y deolaye
umy fiend keguod irsi he loss deyinition.thu
lalei the funcíon to geak en Zhe Class 's intemal
dota as 4 it wee a enbes , ohile emaininy
menbe funttt
Exomple
#include <iostream
sing namespaee std ;
class Myclas s
priva te :
int value;
public:
Myclass ( int Ve o): value (v)i ?
friend rojd print valuc (Myclass obj) ;

n foiend fun ction defii tion


Void print valae (myclas s obj) 3
Cout << "Value "ce obi Valw <c end

Mycos se);
print Velu e (obj);

Why a fiend function Cant over load the assig


nme
opuator (=)
The assine opaatir l=) in ctt ) a sheci'al ywnbe
lhat hadles copyi one ohjets dh % amother
ohject of dhe same class.
he re son s
aceess tho imblici t Ihis poinles Loto opelat
te object to cwhich it ds assigning Vale. hu
pointea sefeu to invo ny (callig) ohject.
Hocoeves,riend functions donot belong odo a class
amd as Such , thy don't have aees to the
or oves lad
nsuitable ox
this point. thi makes them unsuilable
ing le ass jgnmant yuaar.
for oreuloadng -, always se amemba
(13) Aht us opexaler ovexlo ading ? WAP in ctt to
over lbad onay minus ohexaor
Ansi Opeialon Ovesloading ç a featuse in ctt that
albws redeline the behari
(like t,-, *, 7,5,cte-) for we- defined data
typa (cla se).
This makes t possible to ue qPeralo's wätlh object
yor clases in a kay that's iobuitive and
Similia to how they coork wi th built in data
Igpes. Tt impsores code readability and
flexibility.
ovesbadig ta way minas)opeaa.
Tt à unag opuatii ,it qpeate on syge peond.
when oveloaded , it aloog u t neg ade te vae of
obet.

Ainelude <iogtream >


wig namabaee std;
class Nunbes f
it vale ;
Publie
Number (int v): Yaluelv)t ?
loveloading ney minus
Numbea opudos - OF ((3
ne tsn Numbe (- value) ;

Void duplay ()
Cot <eyalue 3? <<value ;

int main ()f


Num ber msn(io);
Number ney Nume -num; oveload unasym mup
Cout <e 0rgina!";
dulay U:
Cout cc eg aded ';
neg. Num - daplay ();

onginal rahue : l0
Neg ated raue :-lo
( What us inline funclion? Erplain with exampe.
ast An inine uncon in ctt s a
hue thu
fundtion bohee the comle eplaces the funcity
Call oith the aetal funcion code at conmpile.
Lime Tha elimates the oveehead a a function
This
Call, buch as Jemmping b tho funetion's ocaor
an d selaning back, theby impsoring peyorma
-nce for small, (reguenty wed aTctfo.
# ineludes <iastseam>
using. namespace slds
inline . int Squaselint x) f
velusn X* X
int man U
int nu m S;
int Tesult = squage taum)
=

Coat < eslt ;


3
Output
25

what us opeudtos over looding ?Give an ezample laine


triond oass.
Ans 2
Dpesato oa bacng in c1t, alluz to redejne
the .beharious d opesatoY
(t, *, /)for lwej -
delined dd tpe (cosses).
When oPes alors geed to acess ponte os protected
kabmbes of a elass, friend function aue lton
used. T! the Neslaading gunclion i
within a
Friên olass, it can alcess the Privat
membe ot amothes class
Exarple:
nc jode <iostream >
using nqmeshace std;
dass B
class A
nt alue;
publlc :
A(int v): Value (w)?
friend cla ss 8;
void display Of

class s
Pu blic :
int opu etos * (ons t A 2 0bj 6)
return obi A. vauetS;

int main
A obj A410);

int resut = 05j& t objA;


obj A display U;
Cout <e&e Resalt otex ovelaad ing +*

output
Valye o A
Resuir after ovea ladng :5
Ihat acce sS modiier in ctt ?
each
Ans. type. key w
osds that Contsol
Access 9odi4jer
the visibi lity and accessibility o cas
)embexs ) atri bute, and methods). they
letermine
ohich pasto o he progan Can
mity a parti cular mem be.
: ctr provde thsee types of acces modi{iu:
t. Public
privale
3.
Psotecte
Diesenee beto eey Access Molifie
Madyierg
A ccess
Access evel
|Modifies
|Publc Memhess declaed as pusie te
a cessible {stm anywheem the
|Psogam, o tside the class s cwell
Membes declosed as pi yate are
ony acces sible wthin the Same
chss other chssey or
tunetions can't diectly
access thos

Protected | Members declase as profec ted


e acce ss ible, witth y the
Same class.and derive
Cchid) classes.
What
eicehion ? What do yeu mean by ercebtonal
handing.? What ahe dhy Uses o ty, throw a ateh 2
Ctlain cadlh an erambe of crding aa ctt Pragtam,
A excebtien is am event that occuS
exceltion oa pogom , distuping us nomnl fos,
Tt typicals irticales Such as
d file ihet doesn't eist.
Excebtien Hand ling -
Excefion harndJling Dechanisn t detet and
stespond b auntima NON6 in a poglam , enduang
the paogam dhan't Csash os behave
unercep tedly.
Tt poidey a strucwsed manage and
Secover hom acafaly.
i. Uses o ty, thsow and cateh
1. By Block -
’used to encoge he code that ay generali
exceptiong
am etmon ocCusp, he code nside the iy blo ck.
hsow excebtion.
2 thow
Used tae bignal the ocasance of ercepion
Once n ercebtion is dhsoon,
dhe coptol peses
# te coseS jonding catch ock
3. Cadck bock i-
Handle> ile exceftion that wa thso on n he tg
block.
Oelime matable aateh Wbcky to hondle
dill type excetind.
Enam ple
t include iostream>
3)
3 ing namespaes std;
Int main ()
int num l num2;
cout << te Entes to umbes";

+hsbw oisision y z0 is not olai'),

nt se Sut numnum2 ;
Co ut <4ResNt <seslt

cafch lconst chas *ef


Cout ce l'Essar <ee c endl:
Cot <<

a<ter executi on hondlingcendhy


Iwhat us const suclor? Explain
ot Constru cto, diferent ypes
Arny A constsucior in ctt i_ a special merbea function
d a coass that is automatically called ohen
object clas s Cxeated Tt
used to intidize obect and set nd
valw
tnembey.
(3
Key points about constsuctors :
1) Constuctor hove &ame me as the chs
i) 1heg don't have a etrm type.
i. Dilfeent bypes o constuetors
1) Delaut constzuctos i
Constvucto ath 0 patameteA
It initazlies obiect uuith dealult valus
Constsuctyr is de<ined dhe
» Conpilier oudomolicdly
genesales aa de< aut constsucios.
2) Paametesized constructor
> A Constructos that accebi og urme
Luth
to imiaze an
object Sped<íc ales.
SJ Coy constuctog
Tt is used to
tD Coy data em one object d
anothen cbjcf.
Used when an oaect i payed bu Vaue Os
fssm o) houmed
funotion
t) Move constucto
opi mized Ves ion o a copy
constructos that tonsfesy
Owenship o sesou Tces instead of
WAP in ctt tn caloulat dhe cyng
Simple intrest wing
de\autt con ucto and para metesized constutos.
tti include <iostream>
using namespace std ;
clas simple Intevest
Priratu :
double princípal , nalo tme, intest;
pu blic :
SIm ple fnteest ()
P'incipal to0o ;
time =2;
Calculate Inteest ();
Sime Inteiest | do ube P
psincipal =P: double r, deuble t) f
Tat ;
time =t;
3
Calculatu sntest) ;
Void calculale Intrest(i
intaest = lprincipal * Tate tme) /t00;
Void

Cout <e" pnci pal'<e


Cot <K
Rato< sat; princpa ;
Cout ce Eime <
time:
Cout ce Sim ple
2
Interest< Intest:
int main b$
Cout <e 4Sng
Simple Tnteest Delauif Const muctos :
Si.
COt<<
USing paa meteaized colstructbr, ",
Sìmple Dnteest si2 So00,
Si2. display (); ,3);
setun o3
Olput
Vsing De<ault cons tyucjos :
principal : l000
Tme :2 Yeau
Simple Inteest 100
S ng pauametexized constructos:
Pincipal : 5000

Fime : 3y
8yeau
Simple Intrest a (0SD

You might also like