Reputation: 14108
Suppose that I have the following class:
class iterator {
private:
Node<KeyType, DataType>* current;
Map<KeyType, DataType>* map;
public:
//C'tor
iterator() :
current(NULL), map(NULL) {}
iterator(Map<KeyType, DataType>* mapPtr, Node<KeyType, DataType>* nodePtr):
current(nodePtr), map(mapPtr) {}
iterator(Map<KeyType, DataType>::const_iterator& sIterator):
current(sIterator.current), map(sIterator.map) {
}
iterator& operator=(const iterator& sIterator);
iterator& operator++();
iterator operator++(int);
bool operator==(const iterator& sIterator) const;
bool operator!=(const iterator& sIterator) const;
const Pair<KeyType,DataType> operator*() const;
const KeyType& getKey() const;
DataType& getData();
friend class Map;
};
I want to implement a constant_iterator using inheritance. I know that base member overriding is impossible in c++. How can I inherit the iterator.map but make it constant within the const_iterator?
Upvotes: 1
Views: 104
Reputation: 8056
Ezra's comment is correct. Public inheritance should mean the is-a
relationship, but in this case, a constant_iterator is not an iterator.
This is easy once you think about it: an iterator, for example, allows modifying it's pointed-to data, but a constant_iterator does not, therefore you can't pass a constant_iterator anywhere you can pass an iterator.
So you should not use public inheritance.
If you want to reuse code (a great goal), you can achieve that with private inheritance or composition. However, you should note, you can never inherit iterator::map
, because it is a private variable! You can't inherit private variables ever. You could include a protected getter-function for the map if you want.
Upvotes: 1
Reputation: 4929
Posting Ezra comment:
you can use private inheritance, that should mask the inheritance from anyone who is using the class, and you can provide access to the base members through const member functions
Upvotes: 0