Monday, May 24, 2010

How do i pass an array of classes to a function in c++?????

i have a class declared:


class Restaurant


{ char restname[30];


/*Too many other variables and functions to list with yahoo's character limit of 1000 words*/ }





in my main function, i declared the class as an array:


Restaurant restdata[50];





now, HOW do i pass this array into a function, such as:


void InputFromFile( ??????);


which will read data from a file,


and then in each array element (which holds a copy of the class), store data in the variables and run certain 'set' functions





Any help will be GREATLY appreciated since this is a project for my final and my professor ran out of time and only gave us a 2 day crash course on c++


[By the way, I know C and know how to do this with structures, but im stumped now since c++ refuses to work when I try that process, but with this class instead]

How do i pass an array of classes to a function in c++?????
Example :


First of all, anytime you pass an array to any function, the syntax is as follows:





typeOfElementsInArray arrayName[ ]





So, let's apply this to your function:





void buildAccounts(Account* a[ ])


{


}





That's it. Don't make it harder than it really is. Another thing, remove the semicolon after the header of your function and the comment you have there "// function call" is incorrect because this is not a function call it's a function definition.





Now, where is "type" stored and how are you retrieving it? The thing is, you have not created your objects yet!! What you can do is something like the following (assuming the array contains a single person's accounts):





a[0] = new Checking;


a[1] = new Saving;


a[2] = new Credit;





We actually need to understand this better. Is this array of accounts just for a particular customer or it contains everyone's accounts? Please, try to clarify what you are doing with the array and the nature of your program so I can help you better.
Reply:void InputFromFile(Restaurant[50]%26amp; restdata)


{...}





That's passing the array by reference...there are a few other ways to do it but that's probably the best given the exact situation.

spring flowers

No comments:

Post a Comment