Dominik T.
Dominik T.

Reputation: 55

How to pass my class template into function? (C++)

I have a "stack" class template, where I simply choose type of my items in the stack and the size of it.

Here are my main:
EDIT:
1. in addItems/removeItems, there are stack variables, not intStack
2. corrected -> to . (I copied it without looking and I forgot to change these operators)
http://pastebin.com/89M56ET6
..and my stack header:
http://pastebin.com/xKfQVD88

What I want to do, is to take two "while" loops in main and put their content into separate functions outside main. I want to make (actually, they're ready) functions called "addItems" and "removeItems".
Problem is, that my "add/remove-Items" functions actually don't do anything (I mean, my objects in main remains empty?). When these "while" loops are making what they have to, everything is ok (items pushing into stack, then popping correctly). When I'm using my "addItems" and "removeItems" instead of loops in main, only adding works (after returning from function, everything disappears).
I was trying to make dynamically my Stack objects as pointers, but I got errors like

undefined reference to void addItems(Stack -int-)

or

no matching function for call to addItems(Stack -int- *&)

And the question is, how do I have to pass my Stack object into these functions?
Or is it mistake in my stack header?

Thank you for help.

Upvotes: 2

Views: 238

Answers (2)

Emanuele Paolini
Emanuele Paolini

Reputation: 10172

void addItems(Stack stack);

Your are passing your stack by value, which means that the function addItems receives a copy of your stack object. Pass it by reference.

Also your Stack object does not have a proper copy-constructor, so you also would have some memory issue if you try to copy it.

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227548

The problem is that your functions take Stack<Type> by value, meaning they get their own copy. So the objects in main do not get modified.:

template <class Type>
void addItems(Stack<Type> stack);

You need to pass by reference:

template <class Type>
void addItems(Stack<Type>& stack);

Upvotes: 2

Related Questions