Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

OOPs Notes in C++ by Arpit Singh

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

O0Ps n C++

aim Of OoP i8to. bind oqe ther the data


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

iexceptthi3 function

Ciass is er defin ed dato types which hoi dz


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

ofthot class.

Object When a class is defined mo memor is allocated


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

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

Abstraction Abstraction means display tng


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

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

Conptructois A conStru ctorr iS a member function of


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

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

Constuctor don't have a etum pe

Default Constouctor No Porameter Possed)


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

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


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

elass (?naccesfble outside the Clasa). A

rotected i3 aSo na ccessible ouTSide the


elass bu gub claCS ot

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

Inhe ritancE
Class SubclasS 3 acess m ode bose class

Sinq e heritance
A

2. Multi Ple Gnhertance 3 Mulieve

Heera rchical fnheritance 5 Hbrid


A Combination ot oe
or more tyPe.

Polymorphism aOperator overloadinq


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

3 membes functi on Ond Varlablee While lass

seuse and canhide t 3 P o s a mming 2

desiqrin detai3.

in C+* A cla9s declared. inside a


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

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

inside the ctoss only

Virtual function and


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

base aos3

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

Tnline Fun etion

mine 3 aa reque 8 t Mot Commdn d .


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

n ne
etunntype fun

Function Overloading a eature


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

Void Pr+nt ( înt 1)


Cout e" Heres fn+ <<î e endl

Void print (flo7t i)


Cout " Here 8 foat" ce i
-

<c endl,

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

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

3 SUbset of CtT C t i s svperset of C

C Co tainS 32 keywordg Con tain 52


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

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

*
Static Members n

Static variable în a function When a variable

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

ietime of the PTogrom (detaut fntialized


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

Static Variable in aclasS


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

They must be defined Outside he class

Static VOr iable doesn'+ belong any object bUt to


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

Ex elass
Accov
prtvate
balance;
Static TO

publie
Void setBalance Cimt b)
baonce =bj

l intialised outsi de doss


tloat Account Yo1 =
3.Sf;
Void main

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

Statie function in a lass


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

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

iS created.

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

Constrvctor

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

updateC) S

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

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

fonction overloqding

Delav+ (Compiler' 8) Constructor Can done Only


Copy
shallow CoPy

CPoint3 o Same
memory o ation)

ob) obj 2

Deep Copy Possble only Witm vser define d Construtoa


USer defined Copy constrUCtor we mare SoYe NF

pointess ot Copied object Points to mew memory lotion

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

to Constructor which becomes mon-termingti

PO

Deep CopP
Desructor

DesthUCtds a

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

ODjecF Kesource

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


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

Operatoor Overlo ading


+* have the ability topovide specal meanig
he operotor.

Class omple2X
'

omplex operatar + (Complex lei)


amplex reB 3
seg. C
eB b c2b

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

need write operator Keyword beore


So w e ' Use a operatoS r e this

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

Ex ClaCs Box

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

Vold Box SetWidh (Box double Wid)


Wdth Wid,
old PritWidHth Box
box)
Cout box width

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

Ciass Base cla ss elass der.closs

VisibiiryMode

EX class Car ClossSport3ar hipblie;j a r

of Tnneñtance
ypes
Q).
Single Tnheritance :

class B Public A

Inherl-ance :
b). Multilevej

public A
Class 8

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

eloss B publie Al, publie Az

d). HeirarehialTnher Itance

Clo ss B1:Public A

61-i
282
cloSS 82 Public A

9enic

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

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

then Pdblie member., WN bee and protete


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

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

Constructor and Destructor n Thheritonce

First child elass ConstTU Ctor wil TUn during cretton


of object Of Ohi d el08S bot Soon

ereated Chi ld Class ConstruCtor YUn and twi al


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

BC) AC)
ConstruCtos exer,

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

Complete pora

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

Friend function doezn + nave poimte, ble


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

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

thisab b
this hn h

i t mgin C)
Box

beet (S ,\0, H);

Method Over Riding


(achleved at run Me)

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

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

Closs Spor13 a r Public Car

void Change qear n + qear


gear > 5D

enr+

main
S p o r t s Car

BC Cha nae qear(4),

Class will be Call ed.


uncton of spors ar
-

Change-qear ) fArat + Cheek if any fon


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

A virtua function i3 a member tunction Whi ch iB


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

Version ot me fonction

They are used to achieve Ron time foly mor phism


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

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

e osS base

Sublic
vfrtval void print C)
"

Coutee This s bo8e print ec


Endl

Void Show
Coutcc Bose Show fon ee
endlG

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

Cot e - derived3Showfon e dl; )


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

Dp rintC) /Ron ime


bptr Show Compi le ime

ODtpUt derived Prin .' h Late ind iny

Base Show tun Early binding


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

and twn bose etas wil)


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

Workinq of Virtual Function Table


fonction then Compiler tself
T a closss
chtalnss virtual

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

obect CYEate2 not, statie


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

deriNcd Ca sg
Class an d
durnng Eorny binding

VTABLEG for baBe clas


PTR
kate bigdino

VTABLE forr derives dlas

Pore Vivtual function


and 3 bsract Closs

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

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

ApUTe virtual Fn ction n C+*


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

ABStroct Cla ss

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

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

2. We Can have Pointer or reference o - abstrac


closs

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

Templete in C +

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


X-

Ca>b)
TErvrn aj
ei8e TerUT n b,

ín data tpe. So tha e Can


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

maln ()

geers
new aeeks)

You might also like