CSCI261
Lecture 23: Passing by Reference, Objects and Memory
troll batul How might you model a battle between two trolls? How - - PowerPoint PPT Presentation
CSCI261 Lecture 23: Passing by Reference, Objects and Memory troll batul How might you model a battle between two trolls? How might you model a battle between two trolls? Define and describe trolls (attributes, behavior) Describe the battle
Lecture 23: Passing by Reference, Objects and Memory
How might you model a battle between two trolls?
How might you model a battle between two trolls? Define and describe trolls (attributes, behavior) Describe the battle process (to the death!) Define who wins (who is left standing)
Declaring functions in external files
#include <cstdlib> #include <iostream> #include <string> using namespace std; int main() { // ... cout << "The volume is " << volume(20, 30, 40); return 0; } #include “volume.h” #pragma once int volume(int h, int w, int d); #include “volume.h” int volume(int h, int w, int d) { return h * w * d; }
volume.h volume.cpp
Header file (.h) contains the function prototypes. Implementation file (.cpp) contains the definitions.
#include “ships.h” int main() { // cool stuff }
int speed(int thrust);
main.cpp ship.h
int speed(int thrust) { return thrust * 10; }
ship.cpp (compile)
1010 0010 0010 1010
coolgame.exe
main
(compile)
(link)
Passing arguments by reference
int free_beer(int beers); int main() { int beers(10); cout << beers; cout << free_beer(beers); cout << beers; // ... } int free_beer(int beers) { cout << beers; beers = 0; cout << beers; return beers; }
Arguments are passed by value...
main()’s beers
f()’s beers
10 10 10 10 10
a copy is made f()’s beers is 10 passed to f()
int free_beer(int& beers); int main() { int beers(10); cout << beers; cout << free_beer(beers); // ... } int free_beer(int& beers) { cout << beers; beers = 0; cout << beers; return beers; }
main()’s beers
f()’s beers
10 10 10
Your new friend: &
makeZero
void makeZero(int n) { n = 0; } void makeZero(int &n) { n = 0; }
3
x
makeZero(x); the value of x is “copied” and passed to makeZero as n
3
x
3
n n makeZero
3
x
makeZero(x); a reference to x itself is passed to makeZero as n
x
3
n n
Troll fred(“Fur-red”); fred
name => “Fur-red” height => 20 weight =>376
fred
MEMORY
In general, always pass objects by reference.