-1

Hi guys I did not know how to title this properly. The query I have is with the implementation of a stack I made. In the code I would assume we could use this->push() or this->pop() but the scope operator is needed(stack::push).. I do not understand Why?

#include <iostream>
#include <stack>


template <class T >
class SpecialStack : std::stack<T>
{

public:

    SpecialStack() : isEmpty(true) {};

    void push(T element)
    {
        if (!isEmpty)
        {
            T LastMin = min_stack.top();

            if (element < LastMin)
            {
                min_stack.push(element);
            }
            else
            {
                min_stack.push(LastMin);
            }
        }else
        {
            min_stack.push(element);

        }
        stack::push(element); // works
        //this->push(element); // Unhandled Exception
    }

    T pop()
    {
        min_stack.pop();
        T out = stack::top();
        stack::pop();
        return out;

    }

    T getMin()
    {
        return min_stack.top();

    }
private:

    std::stack<T> min_stack;

    bool isEmpty;

};


int main()
{
    SpecialStack<int> s;
    s.push(3);
    s.push(2);
    s.push(1);
    s.push(5);
    s.push(6);
    //cout << s.getMin() << endl;

    s.pop();
    s.pop();
    s.pop();

    std::cout << s.getMin() << std::endl;

    system("pause");




}
Phil15
  • 515
  • 5
  • 14
  • 4
    Your class "is-a" or "has-a" stack? I don't think you want to both inherit from std::stack and have a member of type std::stack. – Maxim Chetrusca Oct 29 '16 at 20:23
  • what is the error message? by the way your `isEmpty` never updates to false. – yd1 Oct 29 '16 at 20:25
  • 1
    The code you posted does not compile. – Galik Oct 29 '16 at 20:29
  • Is it intended that you have default inheritance specifier? Since std::stack is a template class, I guess it's private inheritance. – Maxim Chetrusca Oct 29 '16 at 20:31
  • so please add below the error message/s. by the way i have added a note in my last comment. – yd1 Oct 29 '16 at 20:31
  • 4
    `this->push(element); // Unhandled Exception`. Think on the effects of calling `push` inside `push` without termination condition to halt recursion. – user4581301 Oct 29 '16 at 20:32

1 Answers1

4
void push(T element) {
   ...
   this->push(element);
}

The last line calls your push function recursively. Since the process never terminates, you are getting your stack overflow exception.

stack::push is the correct way to tell the compiler you want to call an implementation from the parent class.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
  • Yes you are right, for some reason I assumed this will refer to the parent class. Thank you! – Phil15 Oct 29 '16 at 20:45