Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 602071
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T16:46:59+00:00 2026-05-13T16:46:59+00:00

As I’m learning C++ I started implementing some common datastructures as a form of

  • 0

As I’m learning C++ I started implementing some common datastructures as a form of practice.
The first one being a Stack (this was the first to spring in mind).
I’ve done some programming and it’s working, but now I need some input as to what I should do otherwise. Like deleting certain stuff or other pro tips. What should I do different and why?

template <class T>
class Stack
{
private:
    int* values;
    int capacity;
    int itemsOnStack;

public:

    /////////////////// 
    Stack()
    {
        Stack(32);
    }

    /////////////////// 
    Stack(const int sz)
    {
        values = new T[sz];
        capacity = sz;
        itemsOnStack = 0;
    }

    ~Stack()
    {
        values = 0;
               // delete?
    }

    ////////////////////
    void Push(const T& item)
    {   
        *(values + itemsOnStack) = item;

        itemsOnStack++;

        if(itemsOnStack > capacity)
        {
            capacity *= 2;

            T* temp = new T[capacity];
            temp = values;
            values = new T[capacity]; 
            values = temp;          
        }
    }

    /////////////////// 
    T Pop()
    {
        if(itemsOnStack > 0)
        {
            int current = --itemsOnStack;
            return *(values + current);
        }
        return NULL; // ? good?
    }

    /////////////////// 
    T Peek()
    {
        if(itemsOnStack > 0)
        {
            int current = itemsOnStack - 1;
            return *(values + current);
        }
        return NULL; // find something better here or shouldnt?
    }

    /////////////////// 
    int Count()
    {
        return itemsOnStack;
    }

    /////////////////// 
    int Capacity()
    {
        return capacity;
    }

    /////////////////// 
    bool IsEmpty()
    {
        return itemsOnStack == 0;
    }
};
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T16:46:59+00:00Added an answer on May 13, 2026 at 4:46 pm

    Did a first pass of fixes on your code:

    template <class T>
    class Stack
    {
    private:
        int* values;
        int capacity;
        int itemsOnStack;
    
    public:
    
        //Stack() : 
        //{
        //   Stack(32); // doesn't do what you expect. This would create an unnamed temporary stack object
        //}
    
        Stack(const int sz = 32) // C++ doesn't yet have delegating constructors. You can't call one ctor from another. But in this case, a simple default parameter can be used instead
       : values(new T[sz]), capacity(sz), itemsOnStack() {} // use the initializer list for initializing members
    
        ~Stack()
        {
            delete[] values; // you allocated it, so you delete it as well
        }
    
        ////////////////////
        void Push(const T& item)
        {   
            values[itemsOnStack] = item; // cleaner syntactically than your version
         //   *(values + itemsOnStack) = item;
    
            ++itemsOnStack; // prefer pre-increment by default.
    
            if(itemsOnStack > capacity) // you need to check this before writing the element. Move this to the top of the function
            {
                int newCapacity = capacity * 2;
    
                // what's this supposed to do? You're just copying pointers around, not the contents of the array
                T* temp = new T[newCapacity ];
                std::copy(values, values+capacity, temp); // copy the contents from the old array to the new one
                delete[] values; // delete the old array
                values = temp; // store a pointer to the new array
                capacity = newCapacity;
            }
        }
    
        /////////////////// 
        T Pop()
        {
            T result = Peek(); // you've already got a peek function. Why not use that?
            --itemsOnStack;
            return result;
        }
    
        /////////////////// 
        T Peek()
        {
            if(itemsOnStack > 0)
            {
                int current = itemsOnStack - 1;
                return values[current]; // again, array syntax is clearer than pointer arithmetics in this case.
            }
    //        return NULL; // Only pointers can be null. There is no universal "nil" value in C++. Throw an exception would be my suggestion
              throw StackEmptyException();
        }
    
        /////////////////// 
        int Count()
        {
            return itemsOnStack;
        }
    
        /////////////////// 
        int Capacity()
        {
            return capacity;
        }
    
        /////////////////// 
        bool IsEmpty()
        {
            return itemsOnStack == 0;
        }
    };
    

    Things left to fix:

    Copy constructor and assignment operator. At the moment, if I try to do this, it’ll break horribly:

    Stack<int> s;
    Stack<int> t = s; // no copy constructor defined, so it'll just copy the pointer. Then both stacks will share the same internal array, and both will try to delete it when they're destroyed.
    Stack<int> u;
    u = s; // no assignment operator, so much like above, it'll blow up
    

    Const correctness:
    Shouldn’t I be able to call Peek() or Count() on a const Stack<T>?

    Object lifetime:
    Popping an element off the stack doesn’t call the element’s destructor. Pushing an element doesn’t call the element’s constructor. Simply expanding the array calls the default constructor immediately for all new elements. The constructor should be called when the user inserts an element and not befre, and the destructor immediately when an element is removed.

    And, uh, proper testing:
    I haven’t compiled, run, tested or debugged this in any way. So I’ve most likely missed some bugs, and introduced a few new ones. 😉

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 301k
  • Answers 301k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer There are two issues. First, the child process is buffering… May 13, 2026 at 8:08 pm
  • Editorial Team
    Editorial Team added an answer This is a simple O(n * m) algorithm: any(a[i:i +… May 13, 2026 at 8:08 pm
  • Editorial Team
    Editorial Team added an answer 100 is a lot of colours, but you might be… May 13, 2026 at 8:08 pm

Related Questions

I want use html5's new tag to play a wav file (currently only supported
In order to apply a triggered animation to all ToolTip s in my app,
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
I've got a string that has curly quotes in it. I'd like to replace
I have a JSP page retrieving data and when single or double quotes are

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.