Delegating and Inheriting Constructors

Summary

In this post, I will show delegating constructors introduced in C++ 11.

Details

I come across the codes below, and get confused about the systax.

class Iterator {
    struct Data;
    Data* data;
public:
    Iterator(const vector<int>& nums);
    Iterator(const Iterator& iter);
    virtual ~Iterator();
    int next();
    bool hasNext() const;
};

class PeekingIterator : public Iterator {
private:
    int m_next;
    bool m_hasnext;
public:
    PeekingIterator(const vector<int>& nums) : Iterator(nums) {
        m_hasnext = Iterator::hasNext();
        if (m_hasnext) m_next = Iterator::next();
    }

    int peek() {
            return m_next;
    }

    int next() {
        int t = m_next;
        m_hasnext = Iterator::hasNext();
        if (m_hasnext) m_next = Iterator::next();
        return t;
    }

    bool hasNext() const {
        return m_hasnext;
    }
};

After some research, I fully understand the codes.

1.What does PeekingIterator(const vector<int>& nums) : Iterator(nums) {...} do?

Actually in the past versions of C++, it is not allowed to inherit constructors. Howerver, in C++ 11, we can use delegating constructors, which use the father’s constructor to initialize inherited member variables.

There is another method using using, see the highest voted answer here.

2.What does Iterator::hasNext() do?

Since we have overided the hasNext() function in child class, if we want use the parent’s member function, we should use Iterator::.

Leave a Reply

Your email address will not be published. Required fields are marked *