Re: Deriving from concrete types
todma <toddmarshall2002@yahoo.com> wrote:
clarify???
so one person says:
..."Inheriting from a large concrete class like
std::vector is a gratuitous violation of design rules, which has only
problems
and no real advantages. "...
and just before that someone else says:
..."To answer your question there is nothing wrong with deriving from
std::vector<T,A> as long as it is not used as an OOD inheritance."...
Since the compiler allows it supposedly, how can i disallow OOD
inheritance when I want to use it?
He probably means that is not used where theere is an attempt to
delete a Derived * using a Base * [see DontDo This below as a BAD
EXAMPLE]
I like the C/C++ principle 'Just because you can commit suicide with
this doesn't make it illegal' :)
There is no general method to strictly enforece this with a compiler
seeing only part of the total source code at a time.
If your class is to be used as a library component Document it is not
classical OOP. If the user drives off a bridge that is out and it is
clearly marked, its not your fault....
Also, this seems like a natural thing for programmers to want or need
to do.... the OOD restriction seems unnatural unless there's a facility
for it specifically on or off. If someone does it then it can't be
mis-used, is that what's needed?
But wait, do vector<> etc. have any virtual functions? if not then they
can be derived from, they don't need virtual destructors, and can't be
destroyed through pointers to base classes, right?
Todd.
void foo(std::vector<int> *p) {delete p;}
class DontDoThis:public std::vector<int>
{
double *foo;
public:
DontDoThis():foo(new double[500]){}
~DontDoThis() {delete [] foo;}
];
int main
{
DontDoThis p(new DontDoThis);
foo(p);
}
should produce a memory leak [DontDoThis's dtor not called]
That is the type of problem that all thees inheritance only for OOD
crowd is complaining about. not deleteing a base class of vector. The
standard provide none but if it has any base classes they are
implementation details not OOD inheritance.
I see very few problems if the derived class has a 'trivial dtor', such
as the compiler generqted defaults and it is not created on the heap.
There are alot of useful and legal uses of public inheritance beside
classical OOP, one is CRTP which uses a templated base class instabced
with the name of the Derived tyoe as a template parameter, See boost
for lots of examples of this. One that comss to mind is iteratpr_facade.
which does all the grunt work of producing a valid STL interator if you
provide a few non virtual functions that describe the behavior of your
iterator. Nost of the boost provided iterators are derived from
iterator_facde, via iterator_adaptor.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]