4

I have an inner class, myIterator, of my template class linearLinkedList<T>, and I'd like to override inherited virtual methods from simpleIterator<T>, but the compiler is rejecting them as "templates may not be virtual." Based on this question, though, it seems like this should be possible, as it only depends on the class's type. For example method foo in my code below is legal. How can I implement the virtual functions of the inner class?

template <class T>
class linearLinkedList
{
public:
...
virtual void foo(T data); //OK
simpleIterator<T> * iterator();
private:
...
class myIterator : public simpleIterator<T>
{
  public:
    myIterator(node<T> ** head);
    virtual ~myIterator(); //inherited from simpleIterator; error when implemented
  private:
    node<T> ** prev;
    node<T> ** next;
    //functions inherited from simpleIterator<T>:
    virtual bool hasNext_impl(); //error when implemented
    virtual T next_impl();
    virtual void remove_impl();
};
...
template<class T>
virtual linearLinkedList<T>::myIterator::~myIterator() { ... }
->
linearLinkedList.h:213:1: error: templates may not be âvirtualâ
virtual linearLinkedList<T>::myIterator::~myIterator()
Community
  • 1
  • 1
Vitruvie
  • 2,327
  • 18
  • 25

1 Answers1

3

A member function that is not a function template itself can be marked as virtual, even if it's part of a class template, however:

§ 7.1.2 [dcl.fct.spec]/p1:

Function-specifiers can be used only in function declarations.

function-specifier:
    inline
    virtual
    explicit

The virtual specifier shall be used only in the initial declaration of a non-static class member function; see 10.3.

That is, you should remove a virtual keyword from the out-of-class definition:

template<class T>
virtual linearLinkedList<T>::myIterator::~myIterator() { ... }
~~~~~~^ to be removed
Community
  • 1
  • 1
Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160