Re: Deriving from concrete types
Alan McKenney wrote:
Kirit S?lensminde wrote:
Alan McKenney wrote:
On another note: some posters have indicated that
one should use "private" inheritance.
Now, I've never used private inheritance, but it
seems to me that if you derive privately from std::vector,
then all the std::vector functions are inaccessible
to the user of the class, which sort of defeats the
purpose.
Read up on the 'using' syntax.
class MyVector : private std::vector< int > {
public:
using operator [];
using resize;
// etc.
};
Now you can control exactly the members that you wish to include and
you cannot use a MyVector as a substitute for any std::vector< int >
either.
True.
But if you want all the std::vector<> member functions, how is this
better than just using public inheritance?
There are three things here:
* OO inclusional polymorphism - that a sub-class can be substituted for
a super-class. Where we pass pointers & references and use virtual
functions.
* Operational polymorphism - where we define the interface. As used by
templates.
* Convenience - where a class does most of what we want, but we want to
change it a litle.
Deriving from std::vector for the first reason is misguided at best, a
severe bug at worst. You may be lucky in exactly what you're doing...
but...
For the other two reasons you should be thinking about which members of
std::vector you are using and how you are using them. You may not want
all of them and they may not all be relevant.
In any case you *do* want to stop your derived class being used for
inclusional polymorphism and deriving privately neatly does that.
A disadvantage of putting in "using" declarations for every
std::vector function is that it's an opportunity for errors and
omissions.
It is inconvenient for the person defining the class, but means that it
cannot be misused later. If you believe that the contract of intent of
the software is described in the source then you should make the point
that your class is *not* a substitute for the super-class explicit in
the code. The C++ compiler is generally more effective at enforcing
design trade-offs then external documentation.
Kirit
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]