I am in the process of learning c++. So i know a method by which you send something to function and then work as if it was call by value but actually it is call by reference
Arrays are by default converted to pointers, which are then passed as reference. So, there is no provision for explicitly passing arrays by reference. That is,
void list_cities(int number, City &p[])
is not p[]
being passed as reference, but makes p[]
an array of references.
Code:
void list_cities(int number, City p[])
{
for(int i=0; i<number; i++)
{
cout<<p[i].get_name()<<endl;
}
}
int main()
{
City *p = new City[number];
list_cities(number,p);
delete[] p;
}
Confusingly, a function parameter that looks like an array City p[]
is actually a pointer, equivalent to City * p
. So you can just pass a pointer to your dynamic array:
list_cities(number, p);
That said, prefer friendly types like std::vector<City>
so you don't have to juggle pointers and carefully avoid memory leaks and worse.
Using std::vector
you can also do the following:
void list_cities(std::vector<City> &cities)
{
for (size_t iCity = 0; iCity < cities.size(); iCity++){
cout << cities[iCity].get_name() << endl;
}
}
std::vector<City> cities;
// fill list here
list_cities(cities);