Get iterator for const reference

Viewed 1754

I'm developing a class that must return an iterator with the begin() method. Also, I have to develop a function that receives a const reference of this class and iterates over it.

When I try to get an iterator from this method, I have the following compilation error: "the object has type qualifiers that are not compatible with the member function."I can't understand why this error appears.

Here is the code that I have written:

// ------------ class Neuron -------------
class Neuron { ... };
// ---------------------------------


// ------------ class AbstractLayer -------------
class AbstractLayer {
public:

    class Iterator : public std::iterator<std::input_iterator_tag, Neuron> {
        public:
            Iterator(Neuron *neurons) : _neurons(neurons) {}
        private:
            Neuron *_neurons;
    };

    virtual Iterator begin() = 0;
    virtual const Iterator begin2() = 0;
};
// ----------------------------------------


// ------------ class Layer -------------
class Layer : AbstractLayer {

public:
    Layer(){};
    Iterator begin(){ return Iterator(_neurons); }
    const Iterator begin2(){ return (const Iterator)begin(); }

private:
    Neuron *_neurons;
    int _size;
};
// --------------------------------


// ------------ Method where the problem is -------------------
void method(const AbstractLayer &layer){
    // Error in both methods: 
    // "the object has type qualifiers that are not compatible with the member function."
    layer.begin();
    layer.begin2();
}
// -------------------------------------------------------------
4 Answers
Related