Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get iterator for const reference

Tags:

c++

stl

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();
}
// -------------------------------------------------------------
like image 309
Dan Avatar asked Mar 06 '26 20:03

Dan


1 Answers

In the method function, layer references a constant object. That means you can only call functions marked as const. Like e.g.

class AbstractLayer {
public:
    ...
    virtual const Iterator begin() const = 0;  // <- Note use of `const` here
    ...
};
like image 84
Some programmer dude Avatar answered Mar 09 '26 09:03

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!