Lecture 7
References Continued
Things you cannot do without references: ACRYNOM: UVPRA
leave uninitialized X
int &x;
Must be initialized to lvalue (left value)
values can occur on left side of assignment
data with a permanent address (on stack or heap)
variables:
int &x = y; (works)
int &x = 3; (does not work)
3 in itself does not have a memory address, when it is x=3 however, then x is stored in a place in memory and it has 3 in it
int &x = y + z; (does not work)
create pointer to a reference
int &*x; (does not work)
create a reference to a reference
eg. int &&a=z; (does not work)
&& means something else which you will see later
create an array of references
eg. int &r[3]={y, y, y}; (does not work)
What are references useful for?
Passing parameters to functions
in general, better to pass by reference
then, decide if const based on use of parameter
Example:
Dynamic Memory Allocation
Example in C:
C++:
use new/delete -> type-aware, less error prone
Example in C++:
New returns an address on the heap
initializes if we give it information
Array Forms
Returning by Value/Pointer/Reference
copies node in function into the stack of the calling function
could be expensuve due to making a copy
Return by pointer/reference
Not a good idea
Return address in stack frame of the function
var goes out of scope and is deallocated -> dangling pointer
np is in the stack of the function
np is pointing at heap data
np goes out of scope but doesn't allocate the memory it is pointing at
calling function needs to delete Node
Operator Overloading
Overloading <<
and >>
<<
and >>
The Preprocessor
Transforms program before compiler sees it
preprocessor directive - #________
eg. #include
eg. #define VAR VALUE
Last updated