0% found this document useful (0 votes)
9 views7 pages

Function Overloading Karnataka State Board

The document discusses function overloading in C++, explaining its definition, need, and advantages. It highlights how function overloading allows multiple functions to share the same name but differ in argument types or numbers, simplifying code and enhancing readability. Additionally, it covers inline functions and friend functions, illustrating their roles in optimizing performance and accessing private class members, respectively.

Uploaded by

Nathaniel H
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)
9 views7 pages

Function Overloading Karnataka State Board

The document discusses function overloading in C++, explaining its definition, need, and advantages. It highlights how function overloading allows multiple functions to share the same name but differ in argument types or numbers, simplifying code and enhancing readability. Additionally, it covers inline functions and friend functions, illustrating their roles in optimizing performance and accessing private class members, respectively.

Uploaded by

Nathaniel H
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/ 7

<.!

hrtpter H

F: NCTlON OVI·~RLOADINC ANU iVlf•,Nil:fr,r' F Udr .:I 101 .'__.

bjects:

o Nc➔c•d for functH>ll nvr•r l1wclin~~


o ( onrrpt of poly111nJ pL1~rn
o \pphcnticrn of funrti(ln (J\leilrinrli11R tlur,ugh Mmplr• exHmplc•,
o t <Hl~ t')')t c,f hilm<' f1111c 1i1,rn1
() lhr fnen,! funclinns

- - - - ---- -..... void function_name()


{

r--:---=----._.,., void function_name( fnt a 1


{
al • W I I I • W I I

void func.tion_name{char ch)


{

int main()
{
int i}
char c;

1--====-= function_name(c);
~""==~=---="""""""'== function_narne( i);
...,_,,,,,,,,~,,,,,,_,,=-=~==--.,,-fun c-tic n _name ( ) ;
..... ..... . ,

}
. ov
f' unction
208 erlc¾

8.1 Introduction
· I t • W'·' J , ve learnt about classes and ob·~eets
In t lw previous c wp er, .: 1 c1 • 1
· · · h d t • b"'1·s and mem bet functions is lh
H c1 m< m .. · , : .
·
c Prinl1
J
~•pJ>ltcf1tton ol cl.,sses wit
k,H m c of oh,1cct oriented pt ogramming _to develop a.t:-d ~rmplify prograrnrn.~
18
methods. Another feature to help for eas1_er programming polymorphi~rn. Tl
<lcfi11i11011 of polvmo1 phism has appea1 ed 1n chapter 6._ Let us recall the definitic
otH'<' agmn. Polymorphism re-fcrs to "one ~ame h~ving. m~y forms, differe
behavior of nn instance of an object depending on s1tuat10ns .
C++ implements polymorphism through function overloading and opera,
ov('rloading. Thf' function overloading allows the user to create new absl~·
data types. In this chapter we learn about the need for function overloaclin
definition m1d dcdaration of function overloading and some examples. T
discussion is limited to design of a set of functions that perform essentially
sam<· thing, but with a different argument list. The selection of overloaded functi
fi<·p<'ncls on matching arguments at the time of compilation. The study in t1i
du1ptcr is also extended to inline and friend functions.
8.2 Need for function overloading
Fu net ion overloading means two or more functions have same name, b...
dilkr in the numb~r of arguments or data type of arguments. Therefore it is »a1
that (function nwn<') is overloaded. Function overloading therefore is the proce
ol cldininr, sa1nc function name lo carry out similar types of activities with rnriou
data items. The rnlvm1tages of function overloading arc:
, Wtwu clifl<-rcnl functions are created for different operations, then us~
lws Io c,111 rt•<.;J><'ciivt· fu11c1ion dcpcnding on the situation. Instead, fo
diff<·n·nt !-litwllions if the same runction is called with different argmnen'
using fund i~m ovctloct_ding, 1h<'n the compiler automatically decides abi,.'
IJH' Hppropnatc 1.unct10n by comprning the argument types used in th,
c,tlJ to lhc fu11cl10n ,md calls lhe required funcrion. Thus the cod!' '
exec u I (•d f: ,ski'.

r JI is <•rn-Jier to 111td<'rslawl the tlow of infrlrmatton and tkbug.


, l 'ode urn in I en1-1m·c ts <'.tHy.

,.. Ji,u~i,·1 inti·1•Jf1c<· betwc<·n 1>ro1 1 rn11 1~s ' lt'cl 1-


, • l ( •• ,
l · t s.
\VOi" I ( I () 1lJ(T

8.3 Definition n.nd declnrntlon of overlonded functions


I I -._~


lacto, 111 lu1wt1011 OV( t lo , uli 11g1~.\ ,,. t ltst ~.
.
'J }H n1w11
• 1.u11t·tion~.trguni~ 11 1
, mi <1rnl111g1wil1 ovc1lowlt•d l1t11<·t1on ., h, tit. f ·g u1.1(1 ts., £1
< tHllH l ll'l' ,u1d q pe o HI 1
tlJ• ,c ;11e tw,, 11111, 11011•. lwv11u; N,u 11 ,. 11 lrll<' , 11 1<101 , 1• · t 101,uufnt•,u.111
11 er<"nttvpcso Uc,
dill<i11il111111du1ol.111•,1111h•11(1 1li,nliti1<lt 0
. . I . . · l 11 ,,mDfll,.
11 o\ ('1 ond111g ts 111vnk<'< .it 1rll'
I I V I I 1• • ( I ' I 11 I ' l I ( I • I 11 11 ( • I 1() 11 ( ) " (' I I , ) \ ({ 1 11 /!. 1 ' • 1I :-::o known .,s (' on l J' tl ,~ l
I

pofyu101 p I ll'·Hlt ,
I){)

int sum(int a, tnt b) ;


float sum(fioat p, float q) ,
function sum () that takes two int<-"gc-r ,1rgurncn t~ j.., cliff<'ren1 from the
0 that takes two float arguments. This is fu nc t 1011 over loarli ng.
oad a function, each overloaded function must h<' d<·r hued and
-;-tely.
int product(int p, int q, int r);
float product(float x,float y, float z);
int product(int p, int q, int r)
{
cout<<"product="<<p*q*r<<endl;
}
float product(float x,float y,float z)
{
cout<<product= "<<x*x*y*y*z*z<<endl;
}
ple the function productQ is overloaded two times. First time
values and integer as return value, second time with three
return type being a float. The compiler automatically chooses
function depending on the number of arguments.

• n in a set of overloaded functions must have different argument

sed for naming functions, then the function is not considered

fanctions
ll!Jre>21",amming example shows how overloaded functions can

te volume of cone, cube and cylinder using O\ erioadect

a) / / Volum e of' C'u I><·


on call generally i1n oh ( ' S ! h e- C'OI11 ph A p, cice s of 1nvokH1 t fur C'tlO 1
etersto the function. nllo<'.,t in {~ strn.ig <" ft>i lac u, 1 lbl< 1h r<:h
e and memoty space. lt i~ po s~il >k to the c ovcrhe d of a
.t\ o 1t1
inline function. The inlinc- l unct wn 1s 1 shot t fun<"'t1011 C omp1l r
tion call with the bod) of th P l'u nct 1on .
::mmie 1s used to de-tine· inlin C" fuu c t 10n~ The 111hnC3 function consists
.tong with function code- and t h e p1ocPss 1s kn ov.; n as C"XJ) u1s1on.
ctions definition starts wit h k~:'i ,, ord inline.
functions should be defuwct before all runcli ons t l1at call it.
replaces the function call statem~nt ,, it h t h e function code
_,NN·on) and then compiles the entire code.
e faster than normal fun c t10ns as function c alling overheads

functions
~ember functions are compact function calls.
e size of the object code is considerably reduced .
execution of a program increases.
;t code can be .generated.
·ty of the program increas~s. •

of inline function is substituted in place of a fu nction call,


utable file increases and more memory is n eeded.
ding the square of a nu1nber using inline func tions.
tream.h>
uare (int a)

e(S);
<"Square of 5 • "<<x<<endl;
(10);
<"Square of 10 = "<<, <<cndl;
O;
Fu net ion over1o .
22~12_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ____ d(1l
r
SquHre ol 5 • 25
Squa 1 e of 10 = 100 . !!9'£M..tt ~ . .•
- - - - - ~ - - - - - ~llill!5~.~--.,·:() ·8 •111 .inlinc functwn that hnds the sq~
In the abuV<" t")xamp 1<" sqH<lt < h ' t'
,..}
of a number. ,. (
,. , 1nay not wot·1·\ Horne, times
Note: The inline funct10n · for one of the followinu '
I

I".)

reasons:
, The in.line function definition is too long or too complicated.
,. The inli1w function is rent rsivc.
,. The inlinc function has looping constructs t~~~(
r The inline function has a switch ~r goto. l,e
8.5.2 friend functions ~,r10,
\\' e have seen that private and protected members of a class cannot be \tiflO\
accessed from outside the class in which they are declared. In other words non•
member function does not have access to the private data members of a class. ·•.mtm
But there could be a situation where two classes must share a common function. •·,~nr ·
C-r-r allm.vs the common function to be shared between the 1.wo classes by making ~n·
11
the common function as a friend to both the classes, thereby allowing the function 1
to haYe access to the private data of both of these classes.
A friend function is a non-mem her function that is a friend of a class. The
friend functi?n is declared_within a class with the prefix friend. But it should be ~I.~
defined out~1de the class like ~ normal function without the prefix friend. It can
access public data members like non-member functions.
Syntax: class class_name

public:
fr~end void functionl(void ); · ..
,. fne nd ieturntypt,_spe cifer function_name(arguments):
j,

Example 8.3: class hase

int vall, va.12;


pu bl1c:
void getdHtn()
I
('Olt(<:<"I•'
. ,nler two vul11es:";
<'t11>>vul 1>>vul~;
213
friend float mean(basc ob);
float mcan(base ob)
{
return float(ob.vall +ob.val2)/2;

the above examplt~ mean() is declared ns fri<·nd fttnction that c-omputes


ur of two nu1nbers that are input using getdata() function.
iend function although not a member func1ion, has full access right to
e private and protected members of the class.

friend function cannot be called using the object of that class. It can be
oked like any normal function.
ey are normal external functions that are given special access privileges.
cannot access the member variables directly and has to use an object
e.membername (Here, is a membership operator).
e function is declared with keyword friend. But while defining friend
ction it does not use either keyword friend or : : operator.

To indicate the use of friend function.

elude <iostream.h>
ssmyclass

private:
int a,b;
public:
void set_val(int i, int j)_;_ •
friend int add(myclass obJ);

id myclass::set_val(int i,intj)

add(myclass obj)

return (obj.a+obj.b);
214

int main()

111 , r-ld.RS object;


ob'e('t.sct \ttl(Jf,5(>); . " .
a
c-out "um
, l of 34 ,md 56 1s <<arld (obJect)<<en<U,,
r('tlnn 0;

Su rn of 34 ::lnd 56 is 90

e bO\ e proonun
~ . add() is a friend
seg1nent the function
Su1C'e it is not a rnember of any class, 1t cannot be calle
ce 1t is a non-men1ber function, add() should be _declar
er public or private or protected access specifier.
remember

function name that has several definitions with respect t


arguments and type of arguments is known as function
,.. nct10n overloading implements polymorphism
, n me functions are member functions defined inside a cla
function code is written along with function definition·
nd function is a non member function of a class thii.t
private and protected acc<:"'ss mem hers

You might also like