Monday, May 24, 2010

C++ Function Implementation Data Type Question?

I have a class named Book_Inventory that has a class called BookRecord *searchByStockNumber(long stockNum). BookRecord is another class in another function that has various public and private variables.





How would I implement that function? What would that functions return type be? If it is BookRecord as the return type, should it return a pointer or not?





I can post the source somewhere else if it would help.





Any suggestions are welcome! Thank you!

C++ Function Implementation Data Type Question?
searchByStockNumber() returns a pointer to a BookRecord object. There are a couple of important things to think about when implementing this function.





First, you might be tempted to allocate a static BookRecord object in searchByStockNumber() and return a pointer to it each time. The problem with that is that if there are two callers, the first might stash the pointer away to refer to later, then after the second call, the data the first caller has a pointer to will be changed.





Second, if you allocate a new BookRecord in searchByStockNumber() and return that pointer, then somebody else is responsible for freeing it. You need to be careful not to just lose track of that pointer. Consider the following function:





foo(N)


{


BookRecord * pBook = searchByStockNumber(N);


// do more stuff...


}





In the example above, pBook goes out of scope when you exit from foo() so the memory allocated by searchByStockNumber() is lost.





I would consider writing searchByStockNumber() this way:





BOOL searchByStockNumber(long stockNum, BookRecord * pBook)


{


// do your look up here. Put the results in pBook.


// return TRUE if you found a book; FALSE if you did not.


}





(I don't remember if "BOOL" is the type name for a boolean in C++... I work in a cross-platform system that defines a type called "Boolean" that is what I use.)





This way, the caller is responsible for the pointer. The caller could do one of two things (or more, these are the obvious ones):





BookRecord * pBR = new BookRecord;


if (searchByStockNumber(number, pBR))


...


delete pBR;





or





BookRecord BR;


if (searchByStockNumber(number, %26amp;BR))


...





The suggestion to use an STL map is probably a bad one. You could have memory issues depending on the size of your inventory, and searching based on various attributes would be complex and error prone. I'm sure you're using some kind of database, which makes way more sense.





Hope this helps.
Reply:I would use an STL map. The reason is that each stockNum should be unique.





I would change your design. You need a class that represents the books (is that BookRecord?). It has methods for stockNumber, title, etc. Book_Inventory has a member attribute that is the map.





Search yahoo! or Google for C++ STL map to find the implementation.


No comments:

Post a Comment