Pass a dynamic array of objects to function
Solution 1
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;
}
Solution 2
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.
Solution 3
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);
Fahad Rana
Updated on June 25, 2022Comments
-
Fahad Rana almost 2 years
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. For example
void myFUNC(string& x)
Now, I have a dynamically created array of objects. I want to pass the array to function like a method above. Here's the code snippets
City *p = new City[number]; // pointer to dynamic array of class objects //function prototype void list_cities(int number, City p[]){ for(int i=0; i<number; i++){ cout<<p[i].get_name()<<endl; } }