[LC++]STL Iterators and integers

Mark Phillips mark at austrics.com.au
Fri Aug 10 10:27:04 UTC 2001


Grzegorz Mazur wrote:

> Well, I'm not really convinced. The methods you've suggested are either
> error-prone or tedious. Relying only on documentation is not the best way.
> And I can't really understand what's the reason behind a container with
> std::vector interface, but with all member functions virtual. Would you
> care to give an example?

The only reason you would convert member functions over to virtual is
if you wished to derive a new class from this base class for which
some of the member functions needed to be reinterpreted.  Making them
virtual would guard against base class pointer problems.  One simple
example off the top of my head is the following.

Suppose you want to define an "offset vector" class.  Ie it is a vector
of integers, but has an "offset" value associated with it.  The value
of the "offset vector" at position i, is equal to the value stored in
an associated STL vector at position i, plus the offset value.

class offsetVectorTy: public vector<int> {
private:
  int offsetPrv;
public:
  int offset() const {return offsetPrv;}
  void setOffset(int offsetArg) {offsetPrv=offsetArg;}
  int operator[](int i) const {return vector<int>::operator[](i)+offset();}
  offsetVectorTy(): vector<int>() {}
}

By inheriting from vector<int>, it is very easy to set up what we
want.  offsetVectorTy _is_ a vector, so it has all the behaviour
and properties of vector<int>, except those which we have 
redefined.  It's advantages:

1. It is very easy to set up.

2. With the possible exception of base class pointer problems, it
is exactly what we want.

3. We can use STL algorithms on it.

4. For large vectors, we can very quickly and easily change the
offset value, so it is an efficient implementation.


The one (and only one I can think of) disadvantage:

1. If we had some kind of general algorithm, taking a pointer to
vector<int> as a parameter, there would be problems.  In 
particular, the wrong "operator[]" would be used if a pointer
to offsetVectorTy were passed in.  Ie, the values of the vector
would not be offset as required!!!


Possible solutions:

1. Disallow the use of such algorithms with offsetVectorTy.

2. Write a wrapper class for vector, call it "baseVectorTy"
for example, and make everything virtual.  Then with your
general algorithm, let it take a pointer to baseVectorTy
as its parameter.

3. Rewrite the c++ standard so that the "virtual" keyword
is "clever", so that it only adds the virtual runtime overheads
when they are needed.  (And implement compliant compilers.)  This
way, the STL could define things as virtual without worrying about
efficiency.  (For that matter, get rid of the virtual keyword
all together.)  From what I have read, this option is not done
because it would be very tricky to write compilers which do this.
(But not impossible it would seem.)



More information about the tuxCPProgramming mailing list