[...] but I am not entirely sure how these two arguments differ from
pass by reference or how they differ from each other.
In the first function
int function3(int* ptr);
// ^^^^
you pass the pointer to an int by value. Meaning int* by value.
In second one,
int function4(int*& ptr);
// ^^ --> here
you pass the pointer to the int by reference. Meaning you are passing the reference to the int* type.
But how does passing the pointer by value and by reference differ in
usage from passing a regular variable type such as an integer by value
or reference?
Same. When you pass the pointer by value, the changes that you do the passed pointer(ex: assiging another pointer) will be only valid in the function scop. On the otherside, pointer pass by reference case, you can directly make changes to the pointer in the main(). For example, see the folloiwng demonstration.
#include <iostream>
// some integer
int valueGlobal{ 200 };
void ptrByValue(int* ptrInt)
{
std::cout << "ptrByValue()\n";
ptrInt = &valueGlobal;
std::cout << "Inside function pointee: " << *ptrInt << "\n";
}
void ptrByRef(int *& ptrInt)
{
std::cout << "ptrByRef()\n";
ptrInt = &valueGlobal;
std::cout << "Inside function pointee: " << *ptrInt << "\n";
}
int main()
{
{
std::cout << "Pointer pass by value\n";
int value{ 1 };
int* ptrInt{ &value };
std::cout << "In main() pointee before function call: " << *ptrInt << "\n";
ptrByValue(ptrInt);
std::cout << "In main() pointee after function call: " << *ptrInt << "\n\n";
}
{
std::cout << "Pointer pass by reference\n";
int value{ 1 };
int* ptrInt{ &value };
std::cout << "In main() pointee before function call: " << *ptrInt << "\n";
ptrByRef(ptrInt);
std::cout << "In main() pointee after function call: " << *ptrInt << "\n\n";
}
}
Output:
Pointer pass by value
In main() pointee before function call: 1
ptrByValue()
Inside function pointee: 200
In main() pointee after function call: 1
Pointer pass by reference
In main() pointee before function call: 1
ptrByRef()
Inside function pointee: 200
In main() pointee after function call: 200