passing object as argument in c++

Upload: sauravnaruka

Post on 05-Jul-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/16/2019 passing object as argument in c++

    1/5

    Passing and Returning Object from Function in C++ Programming

    In C++ programming, objects can be passed to function in similar way as variablesand structures.

    Procedure to Pass Object to Function

    Example to Pass Object to FunctionC++ program to add two complex numbers by passing objects to function.

    #include iostream!using namespace std"class Comple$

      private%  int real"  int imag"  public%  Comple&'% real&(', imag&(' $ )  void *ead&'  $  coutnter real and imaginary number respectively%endl"  cin!!real!!imag"  )  void -dd&Comple comp,Comple comp/'  $  real0comp.real+comp/.real"

     12 3ere, real represents t4e real data of object c5 because t4is function is calledusing code c5.add&c,c/'" 21  imag0comp.imag+comp/.imag" 12 3ere, imag represents t4e imag data of object c5 because t4is function is calledusing code c5.add&c,c/'" 21  )  void 6isplay&'  $  cout7um0real+imagi"

  • 8/16/2019 passing object as argument in c++

    2/5

      ))"int main&'$  Comple c,c/,c5"  c.*ead&'"

      c/.*ead&'"  c5.-dd&c,c/'"  c5.6isplay&'"  return (")Output

    nter real and imaginary number respectively%/5nter real and imaginary number respectively%/87um09+:i*eturning Object from Function

      ;4e synta and procedure to return object is similar to t4at of returning structurefrom function.

    Example to Return Object from FunctionTis program is te modi!cation of abo"e program displays exactly sameoutput as abo"e. #ut$ in tis program$ object is return from function toperform tis tas%.

    #include iostream!using namespace std"class Comple

  • 8/16/2019 passing object as argument in c++

    3/5

  • 8/16/2019 passing object as argument in c++

    4/5

    $private%  int num"  int dnum"public%  rational&'%num&',dnum&'

      $)  void get &'  $  coutenter numerator"  cin!!num"  coutenter denomenator"  cin!!dnum"  )  void print &'  $  coutnum1dnumendl"  )  void multi&rational r,rational r/'  $  num0r.num2r/.num"  dnum0r.dnum2r/.dnum"  ))"void main &'$  rational r,r/,r5"  r.get&'"  r/.get&'"  r5.multi&r,r/'"

      r5.print&'" )

    ........................................................................................................................................

    ...................................................  amples # /#include iostream!using namespace std"class rational$private%  int num"  int dnum"public%

      rational&'%num&',dnum&'  $)  void get &'  $  coutenter numerator"  cin!!num"  coutenter denomenator"  cin!!dnum"  )

  • 8/16/2019 passing object as argument in c++

    5/5

      void print &'  $  coutnum1dnumendl"  )  void divide&rational r,rational r/'  $

      num0r.num2r/.dnum"  dnum0r.dnum2r/.num"  ))"void main &'$  rational r,r/,r5"  r.get&'"  r/.get&'"  r5.divide&r,r/'"

      r5.print&'" )