Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello all

I was studying C++ , ADT Stack , and there are two functions which I confused about.
I wrote the codes above , my question is:
we use & while using bool pop function b/c we change the stack but
why we use & for getTop function ? we just retrieve the top of a stack, we don't change it right ?

What I have tried:

bool pop(StackItemType& stackTop);

// Retrieves and removes the top of a stack

// Precondition: None.

// Postcondition: If the stack is not empty,
// stackTop contains the item that was added
// most recently and the item is removed.
// However, if the stack is empty, deletion
// is impossible and stackTop is unchanged.

----------------------------------------------------

bool getTop(StackItemType& stackTop) const;

// Retrieves the top of a stack.

// Precondition: None.

// Postcondition: If the stack is not empty,
// stackTop contains the item that was added
// most recently. However, if the stack is
// empty, the operation fails and stackTop
// is unchanged. The stack is unchanged.
Posted
Updated 6-Jan-17 11:29am

The better source of information would be the documentation on the library you're using.

But, you're passing in the pointer to a stack of items, basically, the address in memory of where your stack is. That's what the & symbol is for, to use the address of an object instead of the content of an object.
 
Share this answer
 
Comments
Midi_Mick 6-Jan-17 21:47pm    
Actually Dave, the "&" in this case is n "reference to" operator, not an "address of" operator. If an address was being passed, the declaration would have used an "*" operator for its parameter. Subtle, but important difference.
Dave Kreskowiak 6-Jan-17 21:50pm    
Yeah, it's been a long time since I've been in the C/C++ world.
The function getTop retrieves the top item of the stack and delivers its value via the argument stackTop. Hence, stackTop must be passed either by reference (that's done here and that's what the & is for) or by pointer (which was not chosen by the designer of that function). Would stackTop be passed by value it could only pass a value into the function, but not a return value.

So the & is not there to change the stack (which it couldn't), but to return a value via the parameter stackTop.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900