Unhandled Exception

Oct 29, 2016 at 8:09pm
Hi guys, any clue why do I get an error here on this->push?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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);
		
		}
		this->push(element);
	}

	T pop()
	{
		min_stack.pop();
		T out = this->top();
		this->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");
}
Oct 29, 2016 at 8:33pm
You're getting an exception because of a stack overflow. This is because of how by first calling the function push, the function will then proceed to recursively call itself over and over because of line 28. To which, the function will never return and voila a stack overflow. Also as a side note, you shouldn't be inheriting from stdlib containers because of how they weren't made to be inherited from(no virtual destructor).
Topic archived. No new replies allowed.