Phil15 Phil15 - 1 month ago 16
C++ Question

Inheriting from the stack class

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");




}

Answer
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.

Comments