HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Stack Implementation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
implementationstackstackoverflow

Problem

I would like comments on my implementation of a stack:

template 
class Stack {
 public:
        void pop(T& element);
        void push(const T& element); 
 Stack();

 private:
         int elementCount_;
         int stackTop_;
  static const int  MAX_ELEMS = 10;
  T elementArray_[MAX_ELEMS]; 
};

template 
Stack::Stack() :
elementCount_(0),stackTop_(-1)
{
}

template 
void Stack::push(const T& element)
{
 if (stackTop_ == MAX_ELEMS-1){
            std::cout 
void Stack::pop(T& element)
{
    if (stackTop_ == -1){
     std::cout << "Stack is empty" << "\n";
     return;
    }
    elementCount_--;
    element =  elementArray_[stackTop_--];
}

Solution

Here are some things that may help you improve your code.

Throw errors rather than printing error messages

The user of your code may be creating a GUI with no command line available and will not appreciate having your code printing instead of indicating an error to the calling code. The two ways that C++ programs generally signal an error are either by throwing an exception (if the circumstance really is exceptional) or by returning a value that indicates an error.

Use consistent formatting

The code as posted has inconsistent indentation which makes it hard to read and understand. Pick a style and apply it consistently.

Consider adding functionality

Since this is a fixed-size rather than a dynamically sized stack, it would make sense to either allow the user to specify that size (as perhaps with a default parameter for the constructor) and to query it. Also, consider adding functions such as isFull() and isEmpty().

Context

StackExchange Code Review Q#77983, answer score: 7

Revisions (0)

No revisions yet.