Passing array of object as a parameter

I'm getting quite confused with all this pointers, objects and arrays.
Let's say I want to create a car array with 6 cars inside and then get those cars "painted", I could have the following 3 classes:

1
2
3
4
5
class Car{
int car_number;
bool available;
string color;
}

1
2
3
4
main(){
Car* car_list;
car_list=get_car_list();
}


1
2
3
4
5
6
class Car_Jobs{

Car* get_car_list(){
//some code to load info from external source like a txt file
}
}


What I want is to call "get_car_list" function which is in another class and get in return an array of cars containing the information. I dont know how to use pointers here because I think maybe i should just pass a pointer instead of the whole array
You can return a pointer to the beginning of the array.
However, you also need to inform the caller about the array size.
You can either do that by passing an additional parameter or by returning a pair:
std::pair<Car*,uint> get_car_list()
You need to take care that the array still exists after the function call. In particular, you may not return a pointer to a local array. You can assure that by using an array that is preserved between function calls or by allocating a new one with new[] every time.
Of course, both of those are bad ideas. Instead you should return a vector, which handles both storage/memory allocation and remembering its size:

std::vector<Car> get_car_list()
You mean like this ? Cause it doesnt work either

1
2
3
4
main(){
Car* car_list;
car_list=get_car_list();
}


class Car_Jobs{
1
2
3
4
5
std::vector <Car> get_car_list(){
//some code to load info from external source like a txt file
return Car*;
}
}




I'm still stuck with this ... do you think it is better to handle this data with structs instead of these ?
1
2
3
4
5
6
7
8
9
10
11
class Car{
       static int car_number;
       bool available;
       string color;
public: //create public constructor and get functions
       Car () : available (true) {++car_number;} //make it static and ++ will cout how many cars have u made
       void setColor (char* col) {  //u need this func to set color which is private
              color = col;
       }
//do same with available and other
}


int Car::car_number = 0 //static member must be initialized befor main and outside class

1
2
3
4
main(){
Car* car_list [6]; //ARRAY OF 6 CARS
car_list [0].setColor ("red"); //now u use your func like this or in while loop
}
Last edited on
I solved this returning the whole array as a parameter like this:

1
2
3
4
5
6
7
Car* Car_Jobs::get_car_list()
{

Car* my_cars()=new Car[size]

return mi_cars();
{


And inside the main()

1
2
Car_Jobs c;
Car* my_cars=c.get_car_list();


This stuff is quite messy when you are starting and dont have much experience inn c++

But thanks i finally worked it out
Topic archived. No new replies allowed.