Compile time error

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • shrew83
    New Member
    • Mar 2008
    • 2

    Compile time error

    Hi, could anyone please tell me what is the problem with the following code :

    const int MAX = 100;

    class Stack{
    protected:
    int stk[MAX];
    int top;
    public:
    Stack()
    { top = 0; }
    void push(int var)
    { cout<<"Top = "<<top<<end l;
    stk[++top] = var;
    cout<<"Top after = "<<top<<end l;
    }
    int pop()
    { cout<<"Top POP = "<<top<<end l;
    return stk[top--]; }
    };
    class Stack2: public Stack
    {
    public:
    void push(int var)
    {
    //Stack s;
    if (top != MAX){
    cout<<"Stack2 push"<<endl;
    void Stack::push(int var);
    }
    else
    cout<<"Stack is full"<<endl;
    }
    int pop()
    {
    if ( top > 1)
    return Stack::pop();
    else
    cout<<"Nothing to pop"<<endl;
    }
    };

    int main(int argc, char *argv[])
    {
    Stack2 s1;
    cout<<"In the Program"<<endl;
    s1.push(11);
    s1.push(22);
    s1.push(33);

    cout<<"S 1 = "<<s1.pop()<<en dl;
    cout<<"S 2 = "<<s1.pop()<<en dl;
    cout<<"S 3 = "<<s1.pop()<<en dl;
    cout<<"S 4 = "<<s1.pop()<<en dl;

    getchar();
    return 0;
    }

    The error is :
    cannot declare member function 'Stack::push' within Stack2

    Thanks
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    quote=shrew83]
    class Stack2: public Stack
    {
    public:
    void push(int var)
    {
    //Stack s;
    if (top != MAX){
    cout<<"Stack2 push"<<endl;
    void Stack::push(int var); <<<<<<<<<<<<<<< <<<<<<<<
    }
    etc...
    [/code]

    The <<<<<<< line is a function prototype. It redefines the one in the Stack class. Redefinitions are not allowed in C++.

    Comment

    • shrew83
      New Member
      • Mar 2008
      • 2

      #3
      Ok then how do I implement the scenario wherein I want to call the the push function of Stack from the push function of Stack2.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Stack2 inherits from Stack. That means it inherits the push function. Just call push() using your Stack2 object and the call will be made to Stack::push().

        Remember, a derived object, like a Stack2 object, has an embedded base object (Stack) inside. In reality, the Stack2 call to the Stack::push() will push the data that's inside the base portioin of the Stack2 object.

        There is no need for a push method in Stack2.

        Comment

        Working...