C++ (Unit-3) No Operator Overloading

You might also like

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

Aneesh

3/Jo OOP USing Ctt.


Hulkani

Unit-Constguctos. Destouctoss Operotog ouegloading


-

90 ta, we 0so dolining mame unctienua Auch a cet Rocüusd)


setletails) to initialíze he data membesTs ot aN ohiect.
O
c9- Cicle cL: Employee e cE 30)
C1. setRodius C4-6); ei.setDetoils L'O1, 'GRI1.

9 Can we iniitialine the ntate s Hhe e j o Ci:e vaiue

anel hon Ulno iho


ika, inatoncl o, 900tig the sljoc
mamubesu Hunrtion to initialige . Ciecle c C4-5)5
he answel in Yen e ton do it Jning Lon IDU

*. Constouctors:
A danA Lont9uctot id Apocinl, Jmomkesr unction
HOnte
O cdana that J orotutocl Juhoneuet we

na oljoctao Hhat claaa


A Jonotouucto uill have XDctAano O Me. a d tho

Uot 0uen void.


Sonntutteol Tan Je uesy ueu fo Dotting Jnitial
Oluen t co9tnin Jnomben Jaiallas

h e UoNAtsuctse oaluon a n ojgct t o initialiae


itaol whon i t i TAonctoct. Thin in Jknouun n
utomotit initioli^ntion o oljarbo.
CH alao foouilen onothes inonibes unction tollacl
ho dontsurto hat doptououD tha oljocka whon hay
o s JG longon HOniiOc. means delocates memooy
assigned to the otject.
inaido
Conatsuuctrgsa can Je dahingd oitho
o utalda claa dokinntion
ho dlaon dolinattion
uaing claan name and nCope ODgution
9peatL.(::)
claes A

inti
Poblic
AC/constductor declarecl

A:: AC Il constuctor defi nation

iL

Eocample: #include <iosteom .

using namespace Std;.


class Cigcle

iflocitradius.aea
Publid y
ciocle C onstovctor
fadli us = 5-0;1

void computearea C)

asec -14Gadius " adius;

void eho wC) .

cout &" Radiun in: *<Tadius end;


CO mpute agea;
cout "A den in : kaseoendl;

J
e cannot cail a constvuctor cause cconStoLCtors age
Callecl automaticalls uwhenever we coeate an ohje,t.

ciclee Ci.c2;
ahoulel Jbe initiolinerk usi th
we connot nny that elieut c
Jue initiolpecl wih angtdo
one value and CQ louldl
valuo. ule sannot Je Jolerkire
Sw AUEunt dijesant
DU
aliuas o diestand ojnt
than, cicle C)

Enter qTaclius <<end ;


coU+
cin adlius;

c i o c l e ci.c2;
ciscle co C4-)
hi l ahQUr AN O A D Jernuaa h a CoAtoudo
uollA
whith hap JeQaN dorUagAsl dnarrtoke Dny
i-e ciocle C).
S we houe t fLOUica a snntsurtgl h a t takan A

A9amcteL aNd hen indtialipen he Nalua conainacl in

ho n9AMatO tha dnta mambe.Lhia Janitaly


i t in DSUN
unctien euolsadingj Aut in sotsurto

unction oeusacing 1. a only dihanco in uncion


unction
ueugacing
SUloacling hod no HOtuun tyRe
include <iostr ecum)
Dsing narnespoce std;
class Ciscle

floqt Raclius, aMecLj


public:
Void show C);
'Void compute Aecc);
class C '

class Cfloat);

with cL
citcle cívcle C)/ratches

cout Enter aaclius.:


cin ocius;
uith c2.;
Ciccle: cigcle Cfloat cad) / matches

gadius= a c ; ,

cir cle s: voic Comp ute AreaC)

cea 142radiu *racliud;

civcle; void show C

cout "Raclius is: <<Taclius <«end;


compute Area C);
Cout <s" Area is "kadee ee endl;

int main ()

class CL;
class C2C4;
C1.ehow C)
c9.show C):
Tetuon O;
Hhat d 2 D o t tara auy prgLOmTO
A coNtuLrts
NAisucto,
ib Lalao nowun , a dolou

JUonotsuctou
he e n e which mautches
uith c
E
Ccird)é c);
Je bBu
9natsuuclo hat tahap a-moiMhtoe
A
ACotamatOAiaAbl Londd9uucbuL

ho ono uhich mautthaA Juith C2.


ciTcle CFloatD

unenevel e p9isiro a BasLaMat9uinop L o n t I Y c o ,

alno
honOLesl Wderddaline LoNotguuct ,
dodut Auomatimlly psDuislad
S o N a t o r t l in

by the compilam. he jo o nuch a o N n d u o


allocoto Memosy anuisadt He d o i n
i n to

mombeo.
8/JUl
Chaecacteristics of ConstIUctor:
tho public saction
hay
Jhay hould be doclasud in

hoy a a iUoboc cutonaticolly uhan the oljOrta

otuoun JJHAOA, NNot oven Joid.


dhoy do Not haue

He9LahtoLa, hoy toNot wtugun vaues.


Cund
hoy CanNot be jnhouitoo.Howevesu, tho dlosiver
aaa tlaAD LoAtouurto
Lonntsuurtgua Canngt e JUioutual
w e do not ofoci}H TOnodsuuurb0L, C++ KomAilo
ghe oOAton Adalnult contsuuctgo JoL oljort
C ocaordtA No Ao9uaMetogr and haA an rphy brocdy).
wkis ule can daclasto o o han eno sonatouutou
in a s h . Jhaba tonetuurto dbHes in +hai9t
paamator Jat.

lypes ot ConstoUCto
cors.
-Default Constouctog, arameteless o 2evo Axgument
Parametes ized Constuctor
Copy ConstoUCtor
-Defaut Constouctor:
Ho Conaturton Juhich
Uolault conotsuuctg ' J
deand takos aniy 0olgumonta.
the
h o 9Uogsunmél doon ho+ spacijy
Lonatuuctaou in the piusg9iam than"Compilas
conatsuctol autonatirnly
A

9LOULdoa the dolaut


whan
loault conaourtou got colled auttoneticoly

oliocta -goe contoc


cash
to cal dolaul ConAtouto9u
tulo dont naoe
ond dot epoabea
ocplcity .iko Juning eljort
nasmo.

i in mandadsy * ROuiele dajau Conaourkep


+ a a t e on oioct Juitho
RDAAiNQ ny AoOMOAa
Phoametesized Constovctor:
Thore Conntuuctn tako p09LAMOto9LD. UAinq thin
diyjanont unluas
fonotutm JoL t a n pRouida
ko dataMombeuo O dioort eljorto. by paain
ho appsopsicuto Jsaluan ad Douumont
hin toNaoctgt casot Je calod JLAing oliort
Nane n d dlot opnts.
ulo haue o t o l thio Conatsuudol uwhon ljor ia
Csoatoe , by DRoriying appsspsuinte -proaMato9a.
class nune> obj-name Cpa®ameters);
Rectangle 1C3.40; //Implrclt Call
OR
class.Dame ohj-name- <clags. name> CpoBasnete rs);
Rectangle i Rectongle C4), /Eoeplicit cal
Important note:

ypo occapt that t h a , clasa to which itJelong.

Howeues a csnatsuutt0conccopt c ooNo


t it oun clad a a n m t o o l . An auch taban
he -conatsurtg i copy Conatouutoe.
claseA classA
Referefnce o
PUblic:value of Public: he oect
ACAD h,ghiet
ACAS)
.
Not allowecl Alloweol

D
couunotas te a conatoucton.

f
Copy constructo v/s Assigoment Opeutor:
Rectangle i,2,
Rectangle 79 »vi; ||copy constouctor
.2 L; ( / assiqnment opevator, 1
-Jhe copy cenetosuctgl and tho aAaignnont
oposLtosin asto Jinod to inibinlig onc objoct to
anetho oljord.
- Dho Jmnin ditpswnca betweon thom i o that the copy

dut o DAnignnontt spouatol d o ND make nou

MomLou apato.. t uAOA he soonarnco Jasuiaile


t poit to tha 9QUi oUA MomGPy Jlod

Copy Constouctor Assignment Opesrartor

h e ceAy tonodouuctou Aadignment ORONAIgI


i n Janically an OUAL
Jsadodl tonatsucto
hin itinligea tho naw Ihin adAigno tho value
oljoct with an aloandy one one sljoct to
aciatin olioct anotho oujoct b oth et
which nsta allandy eeist

4 io JuDocl whon noU | when we


iD Junoc
to AAnign acinting9
oioct Jn stocosl with w
ASme ocinting oljact ljoct to now olyart.
One memoay loccetion, but
oth the ohjekts Uses
geference
sepagate memory locations(dif fevent
Uagiables ade pointing
Hothe Same location
Copy Constructor Assigoment operaito

4 ne Copy onatsuctei 1tho nAaignment


|Jdainacd in Ehd claaD,po9ntoeu in no
the ompilesu psSUidosSuesunadac, tho bitui.
one COPy uiu Je mada.

99

Jrahna

1de,

it
0Jul

.Constouctor Oveg loading.;


Ct* Rasunita Ju to ubo muultipla onatsuuctooa inha

when JMEPa than one tonatoucto unction is dajino


n tho daan it in DUn AN conatsucton oUIULDadinq
henouesL we doina one L MGO JNen dolult
conat9uctgoua Cwith sasavotosua) Jol a daon, o.dolault
Tnatsuctoue Cwithout pasaMOl09LA) sheuld. alao Je
plictily doinado n tha tamailas uuill, no

goDUido a dolault conatsucts in hia caaD

class Rectangle.
int len. wid
Public:
Rectangle C); /Oefault constouc to
RectangleC int a) :/Pasameterized constructor
Rectang le Cinta. int b);/Paa.meterize constUetor
RectangleC Rectangle 5)i//copy constouctom.
3
* Dynamic Constouctogs:

tha todsucteub can a l a e usod to allBCate


momey whilo conting oljorta
Aloationo mom.uy to olujorta at the tina.
hais onatsuurtion io RNSUn cD dunamic conatuuction
oljarta
Dha menguy in aloutoel unin9 the rou gReIato.
new" is a dynamic menhooy Neywod
allocat ion OpeTato
at CEmfik Aiyu
Haa, rhaMGPu qeto llgutecl
int alio o A w tih
auoe calacl Jatatit inem
which in
allotuiod
obytes C4xio) Mergou
nhe nveve casa
c a l s L r l , Hhdt
clont ura a l ha rMemsy
hat it we

Jverume inolicont utiliution s memA

nt n;
elements:"
cout <" How many
cin > :
int *p:
new int[hJ; //Here, menoty gets ollocated at -ne
allocation
This is knowrn as unamic memo

/n is 6 1900]

int p l o o 24 DytesS
1012
JO16
o20
Cout" Enter element";
tor Cint i=O; ikn ; i++)

cin >p[;

and
h e "new" opasatol ia Jnoc t o alocate mQMay
he "clelete" oposuatol io Uocl to donllocate Mortoy.

SyntacC
Rontevasiable =newr olatatype
Eccanple:
- tntP: p Dew int; '-)f
1 0*P1 new int C20;
-flaat q, new float C17-26);

SyntaL
-

delete Pointervawiable;
£cample:
-delete P
-detete [ip;

include < iostroeam>

Using namespace stel


int mai nC)

int *p-new i
COUt " Enter a numbar:

in s*p i
p end l;
"
*
cout < You enterec s

Tetuon0
iD delloco2
As a Tesponsible prooqmamme,it is out. joD
IF
memoTy hatis allocatecl manualy dynamically.
ue

Fatl to do so, it esuts in "mermory lesks


#include <iostueamd
USing namespace stel;
int mainc) . i

Tt * new inti, l/Dynarmic menoTy allocation


int *oy= neur inti / Oynasnic menoy allocation
COut <e "Enter two OO."
t .
CiD>p *ayi

cout "Sum is" <sUm<end;.


delete p 1Deallocate memory
delete a; #Dealbcate memory
Getuon 0;

alotntocl 'dyriamircully is 8byBes


HosA, do momgoy
id
Lnew 10t , new intJ and MaMgou clonta atcutitally

12 bytes [ n t "p. i n t , , n t sum]


TERM WOR- .
4Ca).Cseate an
aocay using
agscay
Woite
tunctions to using
per
dynamic memory
memosy allocation.
allocotion.
Find he min Fosm
peo Foomn the
he
Followingg
follouing:
-

elemenb in he aTVay
Find he ayaay
-

mabc element in the


-

Find the mean o+ he aG Vay


aTay
. *include 2iostream>
he
Hhe elements in the
he aOCy
acy
vsing namespace std
void oeacd
Values (int oC1. intn)

Cout"Ente no. o
elements:
fo C4o intt i
=O; i<n; it+)
cin aLiJ;

void find MinC int aC], intn)


int min a [®J;
=

foo Cint i - i izn: it+).


f CaLi]< min)
min oLi);
Cout " Minimum value ís: "<min <endl;

void find Mar Cint aLJ. intn)


int mabc a[e];
fo Cint i - 1 , i<n; i++)
F CaLiJ> mac)
Mac = aCiJ;
Cout 2" Maocimum valve is: "mac end :
Void F ind Mean Cint oCl, int n)

int sunm O
for Cint i=o; í2n; i+t).
SUM SUM+aLiJ;
float, mean - Float Csum/n;
cout Meamn of the elements is:" mean zencd l;

int main C)

int n
cout"Enter no. of elements"
cin>n
inta New int aLnJ;
Cead Values Ca.n)
find Min Ca.d;
find Mau Ca.);
ind Mean Can);
e t u n O; deletell a.;
.
4Cb). Deuelop a C++
pIoggm to illustwate dy namic
allo cation
S dellocation of memovy Using new and
delete
opesatoS Fo an agay of nintegeos.
Include Functions to
-Teacl he elemertss
find 5 odd
-

even
iotegers in he aoray
dis play elements. t

#include <iostmecm.
USing namespace std
void gead Values Cint al], intn)

Gout Enterr the elements:";


forCint i=0: i<n;Í++)
Cin>>aCiJ;

void find EvenOdd CintaC1, intn).

int CountEven ,count Oddl


count Even countOdd O;
foT Cint i-O; in; it+).
iF CaLiJ72
countEven t+;
else
CoUnt Odd t+;

cout Asony han CoUnt Even even numberKEndl;


has
"

4 CountOdd e<
"

odd number endl;


cout" Aaray

3
void dispValue Cint atl, int n)

Cout " Jha a9i9Hny 0lomontta CA... 1


Tu fo Cint i =O; i<nj i++)
Cout alil<e "

cout e end l;

int Main C)

cout " Enter no. of elesnents,: ";


cin >n
int*a new int EnJ;
GeadUalues (a,d;
fndEvenOdd. Ca,n;
dis p Value Ca,nd;
delete I a
etuon O;
3.
C). CWeate a C++ hat geceives test
pooggam n
sCOes Fsom he User.1lha progm computes
average of he test scoves . also dis plays he
ScoTes in ascencding osdet. Jhe progoorm does
dynamic allocotion ot memory forsorting the rmrks.
#include ziostrøeam>
Using namespace std; r
Cint marksLI. int n).
void sead Masks

Cout Ente he marks:";


for Cint i-0; i<0 ; Í++))
Cin >maR LU;t

masks L1, int n),


Void compute Auerage Cint
) -

fnt sum-0;
ForCinb i-O; izn itt)
SUM = SUM + Maoks LiJ.3

Floa mean = float Csum/n;


is;'<< Mean <endl;
Cout <K"Jhe avetage

void disp Magks C int Marksl1, int n)

inb ten
i+)
fo Cint i-o; ian:
forCint j-0; jn-i-1s j+H)
LjJ > marks Lj+U)
F Cmarks

temp Marks Ljl;


maoks Lj) marksLj+u;
maksLijHJPtemps +
9

Cout " Masks in ascending are: ;


for Cint i -O; i n i+t).
Cout R mark L J "
Cout end;

int main&)

cout " How many tests 1


cin n ; Te>it
int *marhs new int Ln
ead Marks C manhs.n)s
ComputeAveage C maks, nd;
disp Marks Cmaks, n:
delete [CI maas
eturn O;
4Cd). Develop a Ctt progoum to ead recods of
n items as pe he followjng StouctvGe:

St0Uct item .

int itenCode;
stoing name;
float poice

Ceate he agay of stoucl ures Using dynamic


memoy allocation.ugite Functions to,
-to Tead the oecovds
-

display item having highest psice.


#includle <iostreaim
USing namespace std;
Stoct Item

int itemCecde
string name;
float price

void eadItems ( Item itemC, int o)

"vencll;
Cout" he details of«nee"
the
Ente items:

fo Cint i=0; in; i+t)

cout Enter item code:";


cin 1tenLil. itemCode;
cout "Bntes item nane:"
cin tem LiJ. name;
coutx<" Enter item poice:";
cin > item LiJ. poice;

Noid Find HighestPoice Citem temc, 1nt n)

int highest item[ol.poice;


int itemNlum = O;

fo Cint í-O; izn; it).

1fCitemCi). paice> highest).


highest itemLiJ. Pice

ten NuMFS 03y .


cout * Ihe itom iten [ttenNumJ.name"haa
19-N
ho highont puitó a n 'hiphaat 4<endl;

int main C

int n
cout " How many items ?";
cin>n;
Item *p new ItemLnJ;
Tead Items Cp.od
Find Highest rice Cp.nd
delete CIp
getuTn O

You might also like