jeudi 2 juillet 2015

returning reference to class

I have code like this:

#include <stdio.h>

class AbstractIterator{
    virtual void do_something() = 0;
};

class AbstractList{};

class Iterator : public AbstractIterator{
public:
   Iterator(const AbstractList & list) : list(list){};

   virtual void do_something() override{
       printf("hello\n");
   };

   const AbstractList & list;
};

class List : public AbstractList{
public:
  Iterator getIterator(){
     return Iterator(*this);
  }
};

int main(int argc, char** argv){
    List list;
    Iterator it = list.getIterator();

    it.do_something();

    return 0;
}

This works, but I want to "push" getIterator() method to AbstractList class. To do so, need to be able to do following:

/* non const */
AbstractIterator &it = list.getIterator();
it.do_something();

Is this possible to be done somehow without dynamic allocation?

Aucun commentaire:

Enregistrer un commentaire