Is there a way to "convert" a reference to pointer in c++? In example below, func2
has already defined prototype and I can't change it, but func
is my API, and I'd like to either pass both parameters, or one (and second set to NULL) or neither (both set to NULL):
void func2(some1 *p1, some2 *p2); func(some1& obj, some2& obj2) { func2(..); }
Once a reference is established to a variable, you cannot change the reference to reference another variable. To get the value pointed to by a pointer, you need to use the dereferencing operator * (e.g., if pNumber is a int pointer, *pNumber returns the value pointed to by pNumber .
Note: It is allowed to use “pointer to pointer” in both C and C++, but we can use “Reference to pointer” only in C++.
References are used to refer an existing variable in another name whereas pointers are used to store address of variable. References cannot have a null value assigned but pointer can. A reference variable can be referenced by pass by value whereas a pointer can be referenced but pass by reference.
A pointer in C++ is a variable that holds the memory address of another variable. A reference is an alias for an already existing variable. Once a reference is initialized to a variable, it cannot be changed to refer to another variable. Hence, a reference is similar to a const pointer.
func2(&obj, &obj2);
Use reference parameters like normal variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With