Sreyas Adury
Sreyas Adury

Reputation: 136

Undefined reference error in overriding virtual functions in c++

I'm actually new to c++. I mostly worked with Java. I tried to build my own iterator, and after a bit of reading, came up with this method.

template<class T> class Iterable
    {
        T start,stop;
    public:
        explicit Iterable(T s,T e) {start=s; stop=e;}


    public:
        virtual void next(T& i);
    public:
        class iterator: public std::iterator<
        std::input_iterator_tag,   // iterator_category
        T,                      // value_type
        long,                      // difference_type
        const T*,               // pointer
        T                       // reference
        >{
            T current;
            Iterable<T>& obj;
        public:
            explicit iterator(T t,Iterable<T>& o) : obj(o) {current=t;}
            iterator& operator++() {obj.next(current); return *this;}
            iterator operator++(int) {iterator retval = *this; ++(*this); return retval;}
            bool operator==(iterator other) const {return current == other.current;}
            bool operator!=(iterator other) const {return !(*this == other);}
            T operator*() const {return current;}
        };
        iterator begin() {return iterator(start,*this);}
        iterator end() {return iterator(stop,*this);}
    };
    class Range : public Iterable<long>
    {
        long START,STOP;
    public:
        void next(long& cur) override
        {
            if(START>=STOP)
                cur++;
            else
                cur--;
        }
    public:
        Range(long st,long en) : Iterable(st,en) {START=st; STOP=en;}

    };

This is my "flex.h" header file. The header compiles OK. However, when I try to use this Range class, I get the error:

undefined reference to `flex::Iterable<long>::next(long&)'
collect2: error: ld returned 1 exit status

in my compiler (I use g++) My Test1.cpp file is as follows:

(After includes)
int main()
{
    Range range=Range(15,10);
    for(auto r : range)
        cout << r << "\n";
}

Could someone explain where I went wrong, and how this can be fixed? Thanks.

Upvotes: 1

Views: 2268

Answers (1)

You declare a virtual function in next, and don't define it.

A virtual member function has to be defined, be pure virtual, or both. So if you declare

virtual void next(T& i);

It must be defined either inline or outside the class definition because it is not pure virtual. If you intended to make Iterable a template for abstract classes, then adding the pure virtual specifier to next will absolve the error.

virtual void next(T& i) = 0;

Upvotes: 6

Related Questions