jeudi 22 octobre 2020

Why this isEmpty() from "stack" class of template type is not inheriting into derived class "specialStack" of template type in C++?

I have a class template "Stack" which is used to make a stack data structure . Another class template "specialStack" (inheriting "stack" class publicly) it is used to get minimum element from stack in O(1) time complexity - getMin() does this work .

I have error in inheriting isEmpty() form base class .It's showing isEmpty() un-decleared identifier (as you can see in below screenshot) .I have found that to resolve this issue we have to again override the fucntion in derived class but if we have lots of functions in base class then it is not possible to override all the functions . I have also tried second method to solve this issue by using stack< T >::isEmpty() in derived class but now it's giving me another bunch of errors.

Here is my code :-

#include<iostream>
using namespace std;
template<class T>
class stack {
    static const int max = 100;
    int arr[max];
    int top = -1, size = max;
public:
    void push(T x);
    T pop();
    int isEmpty();
    T topElement();
};
template<class T>
int stack<T>::isEmpty() {
    if (top == -1) return 1;
    return 0;
}
template<class T>
void stack<T>::push(T x) {
    if (top!=size) arr[++top] = x;
}
template<class T>
T stack<T>::pop() {
    if (top != -1)
    {
        return arr[top--];
    }
}
template<class T>
T stack<T>::topElement() {
    if (top != -1) return arr[top];
}
template<class T>
class specialStack : public stack<T> {
    stack<T>min;
public:
    void push(T x);
    T pop();
    T getMin();
};
template<class T>
void specialStack<T>::push(T x) {
    if (isEmpty()) {
        min.push(x);
        stack::push(x);
    }
    else {
        T y = min.topElement();
        if (x < y)
        {
            stack::push(x);
            min.push(x);
        }
        else {
            stack::push(x);
            min.push(y);
        }
    }
}
template<class T>
T specialStack<T>::pop() {
    if (true)
    {
        min.pop();
        stack::pop();
    }
}
template<class T>
T specialStack<T>::getMin() {
    return min.topElement();
}
int main() {
    specialStack<int>st;
    st.push(1);
    st.push(2);
    st.push(3);
    st.push(4);
    st.push(5);
    st.push(6);
    cout << st.getMin();

}

Here is the error screenshot : https://i.stack.imgur.com/gidi5.jpg

Aucun commentaire:

Enregistrer un commentaire