Joe,
There are four problems with the code as shown - see below.
<snip explanation and start of code>
Quote
>void TTrolley::Purchase ( TItem *item ) {
> printf ("\n Purchased Item amount = %2.1f", item->amount );
You haven't yet set the value of "item" or initialised the variables
in the TItem structure to which item points, so printing it out will
give garbage.
This merely sets the value of the pointer variable on the stack, not
the one in the calling routine (main).
Quote
>} ;
>//-------------
>main () {
> TItem *Item_ptr = new TItem;
Using new here is unnecessary (and leaks memory!) as the pointer will
(should!) be set in the call to Cart.Purchase.
Quote
> TTrolley Cart ;
> Cart.cereal.amount = 24.0 ;
> Cart.cereal.position = 6 ;
> Cart.Purchase(&item) ; // expecting for *item to point to Cart.cereal
>data area ....
> printf ("\n item->amount = %2.1f", item->amount) ; // I get garbage
>value printed here ...
"item" is not declared here (will not compile!) - did you mean
Item_ptr?
<snip rest of code>
Here is a modified version which should work better!
class TItem {
public :
double amount ;
int position ;
class TTrolley {
public :
TItem cereal ;
void Purchase ( TItem **item ) ; // Note: TItem **item
void TTrolley::Purchase ( TItem **item ) {
*item = &cereal;
printf ("\n Purchased Item amount = %2.1f", cereal.amount );
//-------------
main () {
TItem *Item_ptr = NULL;
TTrolley Cart ;
Cart.cereal.amount = 24.0 ;
Cart.cereal.position = 6 ;
Cart.Purchase(&Item_ptr) ;
printf ("\n item->amount = %2.1f", Item_ptr->amount) ;
One other point: It is not good practice to make variables inside an
class "public" or to access them directly. It is better to add methods
to the class to get/set the values of internal variables and make
those variables private (or, in certain circumstances, protected).
HTH
Regards,
Andrew.
ajpaterson-compuse...@invalid.com
[To e-mail me, remove '@invalid' and replace the hyphen (-) with @. However, reply via the newsgroup, not by direct e-mail, please.]