Basics
De-referencing
add * before a pointer to expose the object’s value it’s pointing
varN
, varN’s valueptrN
, varN’s address*ptrN
, de-reference ptrN, varN’s value- (
&ptrN
, ptrN’s address, which has little meaning)
Symbol to access a member of a class or class object (instance)
a->b
: b is the member of the object that pointer a refers toa.b
: b is the member of the object, or the reference of an object aa::b
: b is the member of the class, or namespace a
Declaration
Pointer Declaration
Syntax: varType* varName
Declaration
1 | //declare a c++ pointer to an integer |
Initialization
1 | // a pointer pointing to address of varN, varN type should be int |
short-hand:
1 | int* ptrN = &varN; |
Reference Declaration
Syntax: varType& varName
1 | int main() |
When a reference is initialized with an object (or function), we say it is bound to that object (or function). The process by which such a reference is bound is called reference binding
references must be bound to a modifiable variable
Function Pass Argument
Both of these methods are prevented copying the variable, and capable of modifying the variable value that is passed in; if a variable is expensive to copy, e.g. struct, class
By Reference
-
Modify the variable, can’t pass in an un-modifiable variable like
const
Syntax
varType& varName
1
2
3
4void printValue(int& y)
{
std::cout << y << '\n';
} -
Prevent modifying the variable, while having the benefit of not making a copy
Syntax
const varType& varName
1
2
3
4void printValue(const int& y)
{
std::cout << y << '\n';
}
By Address (via pointer)
Syntax varType* varName
, to access the variable, de-reference using *varName
1 | void printByAddress(const std::string* ptr) // The function parameter is a pointer that holds the address of str |
Function Return Argument
Variable Pointer
works almost identically to return by reference, except a pointer to an object is returned instead of a reference to an object
The major advantage of return by address over return by reference is that we can have the function return nullptr
if there is no valid object to return
Variable Reference
Never return a reference to a local variable or some such, because it won’t be there to be referenced.
Syntax varType& funName(args)
References
Stack Overflow - When do I use a dot, arrow, or double colon to refer to members of a class in C++?
Learn C++ - Return by reference and return by address