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:
class Car{
staticint 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
}