I am trying to make my own stack class as a beginning exercise, but so far I am stuck as to why mu IDE 'doesn't like' what code? If I put the functions in with the declarations in the .hpp file all is good, but if I try put them into a separate .cpp file I get several errors.
but if I try put them into a separate .cpp file I get several errors.
Templates need to be put in the header files so that the compiler can see the full definition of class/function templates in order to generate the correct classes/functions.
Ok. Thanks. So that means I can’t split my class up as I have previously into two files ie stack.hpp then stack.cpp. Everything must go into the stack.hpp file.
I found out through trial and error that it was the only way to get m6 code to compile.
This is what I have so far for my stack class. Part of the exercise is to add exceptions when trying to access over or under the stack. The size of my stack is default 2 to test my exceptions
An exception happens under exceptional circumstances. I believe you have the logic backwards in your pop() and push() functions.
If you try to push() to the stack when you don't have enough room to do so, that's the place to throw an exception.
Likewise, if you try to pop off the stack when the stack is empty, that's another place to throw an exception.
Did you have more specific concerns? I didn't actually run your code since it's only an excerpt.
my isFull() returns true as long as it is less my variable top, therefore it 'should' only push to the stack when there is room.
my isEmpty() is true as long as top > 0, that's why I have used if(!isEmpty) so I can return a value from pop().
I was wondering if there is a 'better' way or more elegant way to go about this? As is my code does work. You don't think I should throw an exception when either over or under the stack?
To anyone reading code, "is full" means "there is no more room left, you can't push more", so I think your naming scheme is unnecessarily confusing, regardless of if the underlying implementation of the function is correct.
Your code seems fine from what I can tell, aside from what I said above.
- peeking into empty stack makes no sense --> exception is thrown
- pushing to a full stack is not allowed --> exception is thrown
- popping off an empty stack is not allowed --> exception is thrown
My next project is to build on my stack experience and implement a circular buffer class. Where as the the stack is last in first out, it is my understanding that a circular buffer is first in first out.
I will need an index for the push function to put data in the buffer then make sure the index flips over to the start of the buffer.
If I make a 10 element buffer and write 11 pieces of data then the next first out is not at position 0 but position 1.
I will have a think and see what I can come up with...