Passing class object arrays to methods...

When I pass a class object array to a method say


1
2
3
4
5
6
7
8
bookType books[100];

int bookIndex;       //determines what element the object array books is by user input

//books[bookIndex] holds the title, ISBN, price, numOfCopies, authors, and publisher of the book in the object array books in the element that the user inputs

printBookInformation(books, bookIndex);


the data in that object array isn't passed with it. Is there anyway to pass what values are in the object array to a method?
Well, if you want one value to print, and bookType is a struct, you could do this:
1
2
3
4
5
6
7
8
9
10
11
12
13
void printBookInformation(bookType[] Book, int Index)
{
//print the book
};

//then in the main code you would call printBookInformation

int main()
{
printBookInformation(books, bookIndex);

return 0;
};
That's sort of what I'm doing, except bookType is a class. Sorry I wasn't more specific. That's exactly my parameter list for the printBookInformation method, but it doesn't carry the values over. So when I print the book, it prints default values, such as a blank string or 0 for int values.
But when you want to pass an array of a type, this is the syntax:

Sorry, but its actually
 
void printBookInformation(bookType Book[], int Index);

I always confuse the two.

What happens is when you pass the class as bookType but don't specify that its actually an array, the compiler creates code that tells the cpu to create a copy of the object or type being passed. If you have a constructor that initializes default values then a new object is being manipulated within the scope of the function and is destroyed after the function returns. This is why you have default values.

you can avoid this by passing the object as a reference, or a pointer to an object on the free store, or creating a copy constructor.

by specifying that Book is actually an array, the compiler automatically passes by reference. so the syntax:
 
void printBookInformation(bookType Book[], int Index);

tells the compiler that bookType Book[] is an array, and to not make copies.

May the force be with you.
Last edited on
Topic archived. No new replies allowed.