I am learning C++ and was reading a book on it where I came across this:
struct Vector{
int size;
double* elem;
}
void vector_init(Vector& v, int s){
v.size = s;
v.elem = new double[s];
}
So here, would void vector_init(Vector v, int s), without the reference operator, be wrong? Do I have to manually pass by reference using & while passing objects, structs, arrays or anything else as parameters? Also are there any alternate ways to do this? like say void vector_init(Vector *v, int s)?
Any help is appreciated.
If you don’t pass
vby reference, a copy ofvwill be made when enters functionvector_initand you operate on that copy. Aftervector_initreturns that temporary copy will be destroyed, sovector_inithas no effect to your originalv. To manipulate on originalv, you need to passvby reference(same to other type).Pass by reference is better choice compare to pass by pointer.