I’ve never had problems with references as in Python (implicit) or PHP (explicit &). In PHP you write $p = &$myvar; and you have $p as a reference pointing to $myVar.
So I know in C++ you can do this:
void setToSomething( int& var )
{
var = 123;
}
int myInt;
setToSomething( myInt );
- myInt is now 123, why?
Doesn’t & mean “memory address of” x in C++? What do I do then if var is only the address to myInt and not a pointer?
void setToSomething( int* var )
{
*var = 123;
}
int myInt;
int* myIntPtr = &myInt;
setToSomething( myIntPtr );
- Does the above work as expected?
I don’t understand the difference between * and & in C++ fully. They tell you & is used to get the address of a variable, but why does that help you in functions etc. Like in the first example?
In the first example,
&is used to declare a reference type.It’s not the same thing as the
&operator which is used to get an object’s address.You can view a reference type as a type which uses under the covers a pointer which can never be
NULL.