Search code examples
c++templatesstackcalling-convention

Overriding C++ template function in derived class


I am trying to write a stack that returns the minimum element of the stack in O(1), for that I am using a derived class but not getting successful. I am getting an error when trying to call the base class's function from derived class. Would appreciate if you can review the code and provide any input on how to fix it. SCREENSHOT OF ERROR : https://i.sstatic.net/MBGjG.jpg

#include<iostream>
#include<cstdlib>
#include<stack>

using namespace std;

#define MAX 999999

int findmin(int a, int b)
{
    if (a < b)
        return a;
    return b;
}
class nodeWithMin
{
public:
    int val, min;
    nodeWithMin(int x, int y)
    {
        val = x;
        min = y;
    }
};
class myStack : public stack<nodeWithMin>
{
public:
    void push(int dat) 
    {
        int newMin = findmin(dat, stackMin());
        stack<nodeWithMin>::push(new nodeWithMin(dat, newMin));
    }
    int stackMin()
    {
        if (this->empty())
            return MAX;
        else
            return this->top().min;
    }
};

Solution

  • You need change this:

    stack<nodeWithMin>::push(new nodeWithMin(dat, newMin));
    

    to:

    stack<nodeWithMin>::push(nodeWithMin(dat, newMin));