I'm trying to pass an array of pointer objects into a function
My base class is an Account. The derived classes are checking, savings, and credit.
code snippet
Account* a[100]; // array of pointer objects
void buildAccounts( Account%26amp; a ); // function call
{
switch( type )
case: ('c')
a[i] = new Checking;
case: ('s')
a[i] = new Saving;
case: ('r')
a[i] = new Credit;
}
I understand that I can not pass the array like this in the function... Anyone know the workaround?
Passing Array of Objects in a function [C++]?
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:Because buildAccounts doesn't know that a is really an array, you can't use subscript notation to assign to it. I think you have to use pointer notation (a + i).
Reply:void myfunction( - ) {
\\stuff is here
Account** a = new Account*[100];
\\stuff is here
\\I have assumed type is an array of all the account types
\\You can adjust accordingly
buildAccounts( a, type );
\\stuff is here
}
void buildAccounts( Account** a, char* type) {
for(int i=0; i%26lt;100; i++) {
switch( type[i] ) {
case 'c':
a[i] = new -;
break;
case 's':
a[i] = new -;
break;
case 'r':
a[i] = new -;
break;
}
}
}
\\Adjust this function as required
Reply:Hi Whiteshooze,
I think you can find your answer here:
http://www.onlinehowto.net/Tutorials/C++...
garland flower
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment