7. Static members, this, references, const
23/02/23
this & static methods
this
- An object is a collection of data (its state)
- For functions to actually do something to an object, they need to know which object to affect.
- (Non-static) member functions have an implicit extra parameter saying which object to act on.
- Parameter type is a pointer to object
- And the parameter name is
this
Static methods
static
members are shared between all objects of that class- NOT associated with a specific object
- Static member functions do not have a
this
pointer
References
- References give a new name to an existing item
- Look like normal variables
- Act like pointers.
- References are labelled with an
&
Passing Parameters
- When a function is called, the values of the parameters are copied into the stack frame for the new function
- Functions get a copy of the variable
References vs pointers
- Pointers can be made to point to something else
- References always bind to a single object at creation, cannot be bounded to a new object
- References always have to refer to something, must give them a thing to refer to on initialisation. No such thing as
NULL
reference - Pointers need
*
or->
to deference them, to access the thing pointed to - Java object references act like C/C++ pointers, NOT C++ references
Uses
- Need to keep same syntax.
- Useful as return values, to chain functions together.
- References are necessary for operator overloading
const
const
cannot be changed- The thing pointer at through a pointer to const cannot be changed using the pointer. (
const
before*
) - Can also prevent the pointer itself from being changed (
const
after*
)