invalid covariant return type, nested class c++

314 Views Asked by At

I have a first class A that contain an iterator nested class with virtual methods:

template <typename T >
class A {
  public:
      class iterator {
      public:
          virtual ~iterator() {};
          virtual T& operator++();
       };

      virtual iterator begin() const = 0;
};

I have a second class B, that override virtuals methods:

template <typename T >
class B : public A<T> {
   public:
      class iterator : A<T>::iterator {
          T& operator++() override { 
              iterator p(*this);
              return p; //for exemple
          }
      };

   iterator begin() const override {
       return iterator(this);// for exemple 
   } 
};

But when i use B class :

B<int> test;

I have something like this, compilation error:

error: invalid covariant return type for 'B<T>::iterator B<T>::begin() const [with T = int]'
error:  overriding 'B<T>::iterator V<T>::begin() const [with T = int]'

How to implements iterator in B class ?

1

There are 1 best solutions below

0
StoryTeller - Unslander Monica On

Co-variant return types have a couple of constraints they need to satisfy according to [class.virtual]/8.

The return type of an overriding function shall be either identical to the return type of the overridden function or covariant with the classes of the functions. If a function D​::​f overrides a function B​::​f, the return types of the functions are covariant if they satisfy the following criteria:

  • both are pointers to classes, both are lvalue references to classes, or both are rvalue references to classes
  • the class in the return type of B​::​f is the same class as the class in the return type of D​::​f, or is an unambiguous and accessible direct or indirect base class of the class in the return type of D​::​f

  • [...]

Yours doesn't inherit publicly, so the base isn't accessible. And you aren't returning a pointer or a reference.

Returning a type with value semantics is good! You should not give up on that. You can substitute the attempt at a co-variant return type with the pimpl idiom. Have iterator manage a polymorphic "iterator implementation" class via pointer.