0 ratings 0% found this document useful (0 votes) 28 views 23 pages Unit 3 - Relationships
The document discusses key concepts of Object-Oriented Programming (OOP), focusing on classes, inheritance, and relationships between classes. It explains different types of inheritance, such as single, multiple, and hierarchical inheritance, and their advantages like code reusability and maintainability. Additionally, it covers relationships like association, aggregation, and composition, emphasizing the importance of understanding these relationships in designing robust software.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save Unit 3 - Relationships For Later “ clas 1
inst ve.
—Sh_1s_#hé fundamental concept in OOPM, trat
Class . db atorive Properties of, % behaviours of ave
Shit promotes code acitsability kk eshtablishes
| O&O vnatyal ivoar.chy betrocen
£
— palate. eat. ye
St _aftowss ubuoss to Anve attess tp only yw hat —
mectisasy Simm. parent class Paivale mesibelt
4
ase hidden -ee
iwieedvige
s_snheritecl func sooth slower: than en
‘
Simp Apes Use Of Inhetitance wma ters cto chomp,
Olt i on -
soften» data members in, ene base Class re Ube
unis which wo tsadl £o memory wastage -
Snmeyitanke inueases the toupling between base
Png
lass & olexived class A charac. in base class |
wit Affect art tne child. classes
Z One oh main ddisadvantazes of inhert tances in
Save (6 the increased tinre & efforts it
TARY the progam to JuLonp “through att the Jevels
o4 ovesloaoied, classes
A derived class Inherits atl base class methods
wei _pellnsoiny. caret
~ CconsuUUct ors clestrctors te sop. comstumckors of the
base class
= _overtoaded operator a, tre base class
- the fotencl dune” of Ane Hast class «= ITH:
Typ
we
1. Single Imheritamce
F e be ie
Sn this Lnere jo only. one L1AS6.
Atiivedh clase, Simplest form 24 im seen
[etacs A] <— Base clase : y=
|
clase B) +—~ Derived elass
©
cout <«"Zts A” << endl s.
t Public a
Pabloe .
void. pxinte co
eout<<" St Bee 1)" ecendls
4
ys
int mained
b. Print 05
b. PrintBods
vretwnos2. Muttiple Imteritance :
Sn. this type ef inheritance a imgle
derived. class nay inherit $0 bo0 es maw
base clas
class clase B)...-- ciasen] | Sase,
|
+
class Derive] } periwed clase.
gx
class Person {
Public:
voicl Ingo 4 a
cout <<" This ig Pewsen’
Public:
void wheels OF
‘ cout <<" €ay has Wheels xc enals
¥e
Class Sparte cat ? Pubuecatg
Pubes
Volt Speed OT
coud <2 7S e 5
. PELs CAL EAS Tena
ye
imt main 04 S
Sportscar sei
Se, speedo:
SC. Move >
sores
yC20
es :
MabecaxehicaD fpneritan ce
Se
Sm this type of inheritance , rauttiple derived clasees
tb Inheritel prem ingle parc class »
A
Ioyd
sf] fo oJ
example:
class eynimak4
Prrblic!
votd Sound Ot.
cout <<” animal makes a sound” << enadls
kt
class cot! Public animat{ Z
Prrbeic *
votd meowert
cout «" cat Mews” << endl:
wt
class Dog: Public Animal i
Public:
void Bhow- bhowerd
eoubs< “ Bhow- Blew %<< encll 3
ks $
int main 4
eat cs ‘
Dog ai i
e-Sound a+ Sound
©. Menws d- bnow-bhowo.sbx
class vehiclet *
Public t
void move OL
cout <<” venicle moves” <« enal>
be
¥
class Bikey Public vehicle t
Pub Ucé
Void wheels Od
: COUR <<” JEM Bved ON BOO WHEEL” & Cra
ee
©
lass €ans t Public venice t
Public
void CwWheelS OL
cout «< SE mover on fontwneele & ena
¥Gz==O
Cass engimé : PubWe Bike . Public cor}
Paxblic t
void Staxtor
cout <« " Engine starts” << endl:
nn &
int Moin org
engne £3
£. start 05
&. Bike ods
& » care C3
wetwin 03
St occurs when a class is derivecl lrem tr00 ot
move ciasses that taave a tommen base class
Shis creates a sce narlo thee the derived
Class have multipie path to qceess base
classs Members
EX' class Persend.
Public!
void olieplay 4.
coute< "This is & Person” »
retin Os
jy:
8
ee
apCz—=O
OD ODI
36-A_ Relationsnép +
dnae ts
‘$-a" relationship te & _pundam ental
concept in 00PM.s primarily weed in the context
of, Imherizane . St siguities that ome class ig a
pocialxl form 0) onthe clase
concept
+ She "W-O" velationsnia ~ present heragehiat -
relationships between classes
shen G& subclass tnherits jrom a tupuclass- |
ig goin aut the attwipute 4 behaviows of
the supeteass |
* Sh ubclass «Is considtred +a moie specific
type of supeselas
Example +
2 dmimal is a genesat elas.
2 Dog i a mere specific class that fovherb ds pron
animal
a A Dog As animal.
Gla: Animal qd
Prb Lic +
otd colouit)4.
cout <« " This 18 & colors of antl’ e< endl}
e1aSs Dog ; Public Animal jf,
Public:
void Mutticolomor
tout<< "She gy multi oo << endlsint main 04,
animal ant
animal, &olout 02
animal . Muttieplows (2s
bog cigs ; oe
=
veto.
&
Bemepits of is a" ~xelationshirp 3
a bode weusabiliby
4. _r1aint ainability
extensibility -
y Poly moaphis 7
caveats :
4. overuse
+ overusing may cause a Aigia ks tright code
- Suche
2 dIncorvret Hiertarenies’
WYVORES cence .
+ Ensure prat “is a". relation ship togicalg. ——jfassoctettony
Il esecindton feos Ktlationthip berwttn 2108 clase
thal" esntabrish O. CONNECTION Siw tree objec
Pp woccurs wWhena single
instance of a class & vetated toa ingle
instance ‘of another class .
&
‘6X: A Person ciass witr a Passport class .
£ach Peason, hos exactly ene Passport
& each passpart i issued to exactly ene
Person -
&x?
class Pass Part?
Pub ie!
String Pass Porb Numbers .
Pass Pert Cetring number) | passPat Number (numbit
ys
elas, Person
Publics
String names
na Passpeit* porsperl 3\b. One bo Many * - ;
once instance of a class te related tO muttip) 7
imaban. ef another class -
£x: A company can have muttiple Employ ees
class Employee 4
Public § |
oon |
i
elas’ tompanyd
Pra Lit
string somnpany Name:
vector< Emplayee* > employers. I) Association
|
company C string name ) :companymame (name)t 4, |
vot ada Employ ee. Employee * employeeoL
___ employees - push. back Cemployee)s
t
cS |
eM to Many Association Lo
Scematio: students enrou ima muttiple enwistst
eoth, COUrse has multiple students»Ex: class comet
class Studentsy
Public +
suing name $
Vector studentss |/ Assocat ley
COUASE (string course) + comme neme ( conse) LE
void Add student. (student* stud ened}
Student ». Proh- back otudent);
5
us
int mainod 2.
students s ("Sohn")!
Student 62 C"Tane’)s
coumeel C" coding PSA):
cowge 2 C" ‘Nelo devs") >Xi am _employet may belong 2 multiple Ae partment |
im ovganisation . if the department get d be oyed
bubemployee will adso exist Inde pemdenty . |
TO ee
@ whole can contaim a part bul veveue ss nob tue
+ Bb vepresents Has-A -reldtienship -
fGts an. ene-way velation ship - |
Sn. _aggeegation | both sha’ entaies can auive
Indiv fdualty ." 2hith neans ercbing one + entiby
wil mot Sct —onottes entity
Ex: tnivnabs Room 5, ;
.__tomn pos tion, 2 ADA 5
llindow " & doays ebo.
{van} |Ftoor| [mindoal [oor]
[Roores eae
[fot =
i ;CaO
gat
class student 4
Publics '
String aes ; .
student t String studentName) ¢ mame (studentNamt)
oH
Ft
class School td
Rube
stimy schoolName '
Vector < student® > students 3 1) Aggregation
school (Serger name) i: school name (namedd }
a
void addstudent ( student™ student) dL
students - Push -back (student >
5
jmt maint}
School Sehool(" earmel convent);
Student $4 (" Isha")
Student 62 6" Riyanshi") $
school. addstudent (Sid
Schoor« adalstudent (KS2s
ool” & School, sthoolNeme
Latasilhs
peciatiged orm ab aggvegation j
clestroys -the chuld
|
* St ts an
ahi if Parent obyect
poi not exist
ki
r St is an Strong type of assoclakto rohine the
Poat cannot exist without the whole.
2x i Jhink of a Car and 1£6 Engine . ay ine
cox te clestroved + the engine in destroyed.
i Eoo +
Xi class Engine? .
¢
Publue +
H tiny type 2.
I Engin (teypre string engtupe > type (eng type) }}
Il ve}
]
| class card
| Public t oO
l atring models.
: Envine* engines ‘) tompo sition
i
| cok (String caamodel string ey THD model Cah)
| 4
| engine > _neus Engint Cengime Type ds —
Sake = |
delete engine:
Tr y
we ‘
Oe we su eel| =o
Aggregation
Corn position
De, 2. $b “has-@" relationship
A “has -e" + elationship
contains whet ene Class contaby
anothy ass, but the - anotir Class but the
where ene class
wntained class canexnut contained lass
tond ependently can not exist indep-
-endently ,
DependenyizZ- Ihe tifecycle of the class 2. The cifeeyde of theclow
Indepéndent of container. ¥s_clepenclent ef contain
ownevhifi 5, She whole.cloes not own 3 She whole owns the
eee Part.
Lifetime) 4 She Part can exist
i. She - Part cannot.
voitho ut -clesbroyed extiat
if Port 3
Reser oyed
Ex am ple|| 5 -s || eoncteD
ae
Yb pantap aco & (Absmract ase
cor VT
4. Interfaces: +
Fe
a
a ol, lass
con
sf. interport depines a
noithout dietatiry hor it oloes LO - gh
can d? o
tual func? .
imcuuides pwre yi
bsttacti” : an intipare provicles meinnpe: \
=MentatiM Low jts methods ,enaui
t thab rhe cleived class must
: Provide “tmuete implementation ,
[rose
7 No member variables : svterfans cannot nove cata
MEMbEAS 2 !
PY mMurtipie inhaitance -A ease can i ple ment
v
muttiple inheritance -
__+_
Teleat when you ware multiple unseiatd |
implement the seb af methods’
ust case :
classes to1 &X ampie >
class Flyable £
Public:
wirtuel voila fly Oro 3
ys
elass siwimmable {,
Pubtict
viv tual void swim c>+as
ys
class Bud 3 Pwolie Flyable s PubLC Sioimmable 2.
Pubic:
votd Fly o> evvertde }
coub << Braid Fs Fly try tec ends
y.
void Swim) overntidey.
cout. <<" Birds SvOlMmirg “<< ends
int main Od?
Bid bs
by Fly Os
b+ swim)
retunedAbstract c1aes *
|
viv Ga
. Gat]
mm Abstract can Inetudé both absiart m Yeoh
methods wiih tong lementations « Itiix if ended
ae elas pom which other clarses,
derive ® shore
com men fain ctionalily .
4
eo charactestice |
wp Paabial abstraction © Abstiacl classes can have a
mis ef pure virtual ¢
on & mowm al. sung
+ member yoriables apsact elasseds cA haw ee
member Variables bk methods with full impleraent
single oy Multiple inheritance ¢
- A tlass can imhertit enna one oy mote
abstrast piaases In Crt, thowh multiple inheritant,
ie tess eom-rnon +
Use cases wuitable when vou wank to share
tommnen_eode Gemoeng Aclated. classes while
ensusiy some methods ate, ovveridd en “
im. _clerived classes +ex:
©1066 born at
Public.
virtual voich makesowed t)=0!
Ne 3)
x" dhe animat cats jood” ¢< endls
flass poy: Public Animal
ies
ovvearirale
Y é< enol s