3

In C++, if I know a class will satisfy virtual methods, is it possible to modify the below to inherit it directly? Right now the compiler says incomplete types aren't allowed. I could write a wrapper, but is there a direct way?

#include <stack>

template<class T> class MyStack{
public:
    virtual T pop()=0;
};

template<class T> class JobStack : public MyStack<T>, public std::stack<T>;

int main()
{
    JobStack<int> a;
    a.push(1);
    a.pop(a);
}
Carbon
  • 3,828
  • 3
  • 24
  • 51
  • 1
    What do you mean by *inherit it directly*? You never implemented `JobStack` so you can only use it in certain ways. – NathanOliver Apr 25 '17 at 18:44
  • I mean without pointing pop to stack's pop - that the inheritance does that automatically – Carbon Apr 25 '17 at 18:48
  • No. `JobStack` is going to inherit pop from `MyStack` and `std::stack`. You can't stop that. – NathanOliver Apr 25 '17 at 18:50
  • 2
    Add `{}` to the end of the `JobStack` template class definition to fix the compiler error about incomplete types. That's not really what your question is about, and it's a red herring. The actual compiler error you care about is `cannot declare variable 'a' to be of abstract type 'JobStack' ... because the following virtual functions are pure within 'JobStack' ... void MyStack::pop() [with T = int]`. As a side note, the return type of `std::stack::pop()` is actually `void`, not `T` -- so this wouldn't be a suitable implementation anyway. Fix that, too. – cdhowie Apr 25 '17 at 18:53
  • In `MyStack` there's a pure virtual method `pop()`. What do you expect this method to do? If you don't provide an implementation, how the compiler can know how to generate it? – Tarc Apr 25 '17 at 18:56
  • Do the thing std::stack does for pop – Carbon Apr 25 '17 at 18:58

1 Answers1

1

First:

template<class T> class JobStack : public MyStack<T>, public std::stack<T>{};

Second, to answer your question: No. You can't. Because, as pointed to in one of the comments, you inherited two different classes, that means you will have two inherited pop() functions. You are going to have to implement pop() in the derived class. If you still want to use the implementation in std::stack then simply call it in the implementation.

Third, you might still get an error when trying to call pop() from main, since now, your class has a name conflict for two different functions. If this problem occurs, I suggest renaming the function in MyStack to myPop() or something.

RoaaGharra
  • 710
  • 5
  • 19