CIS05 Comparative Languages Objects as function parameters - PowerPoint PPT Presentation

About This Presentation
Title:

CIS05 Comparative Languages Objects as function parameters

Description:

... of the athlete is defined by: name. fitness. Behaviour: jump. display fitness. The athlete becomes fitter when he jumps. 8/8/09. Marc Conrad - University of Luton ... – PowerPoint PPT presentation

Number of Views:39
Avg rating:3.0/5.0
Slides: 7
Provided by: MarcC71
Category:

less

Transcript and Presenter's Notes

Title: CIS05 Comparative Languages Objects as function parameters


1
CIS05 Comparative LanguagesObjects as function
parameters
  • Marc Conrad
  • D104a (Park Square Building)
  • Marc.Conrad_at_luton.ac.uk
  • These slides
  • Three ways to pass a parameter in C.

2
Example The Athlete class.
  • include ltiostreamgt
  • class Athlete
  • private
  • char lastName20
  • int fitness
  • public
  • Athlete(char theName)
  • sprintf(lastName, theName)
  • fitness 0
  • void jump()
  • fitness fitness 1
  • stdcout ltlt lastName ltlt
  • " jumps" ltlt stdendl
  • void displayFitness()
  • stdcout ltlt "Fitness of " ltlt lastName
  • ltlt " is " ltlt fitness ltlt
    stdendl
  • The state of the athlete is defined by
  • name
  • fitness
  • Behaviour
  • jump
  • display fitness.
  • The athlete becomes fitter when he jumps.

3
Call by Value Copying
  • include "Athlete.h"
  •  
  • void doExercise(Athlete who, int howMuch)
  • for( int i 0 i lt howMuch i )
  • who.jump()
  •  
  • int main()
  • Athlete fabian("Fabian")
  • doExercise(fabian, 5)
  • fabian.displayFitness()
  • return 0
  • The object fabian is copied.
  • Not fabian jumps but a copy of fabian.

4
Call by Value but Pointer!
  • include "Athlete.h"
  •  
  • void doExercise(Athlete who, int howMuch)
  • for( int i 0 i lt howMuch i )
  • who-gtjump()
  •  
  • int main()
  • Athlete fabian("Fabian")
  • doExercise(fabian, 5)
  • fabian.displayFitness()
  • return 0

fabian
  • A pointer to the object fabian is copied.
  • Via the pointer we can access the fabian object
    and make it jump.

5
Call by Reference
Output
  • include "Athlete.h"
  •  
  • void doExercise(Athlete who, int howMuch)
  • for( int i 0 i lt howMuch i )
  • who.jump()
  •  
  • int main()
  • Athlete fabian("Fabian")
  • doExercise(fabian, 5)
  • fabian.displayFitness()
  • return 0

O.k
who
  • The fabian object is passed by reference.
  • The object is not copied and can be accessed
    without using pointers.

6
Passing ParametersSummary
  • Basically C has three ways to pass objects as
    function parameters
  • Pass by value The object is copied.
  • Pass a pointer A pointer to the object is
    copied.
  • Pass by reference A reference to the object
    allows to access the object directly.
  • Question How does it compare to C and Java?

Write a Comment
User Comments (0)
About PowerShow.com