On 22 Aug 2005 10:37:52 -0700,
ma******@pegasus.cc.ucf.edu wrote:
Prefer composition to inheritance (can't recall which text I stole that
line from) is one of the fundamental tenets thats engrained in my mind.
Having said that inheritance requires careful thought. To compound
things, when dealing with inheritance 'virtuality' can only be
experienced through base pointers to derived.
There are ocassions though that I dont need a (particulay) 'virtual'
function in base. In which case I'll have to used derived directly.
So now:
# include<iostream>
class base {
protected:
base() {}
virtual ~base() = 0 {}
public:
virtual void override_func() {}
// more
};
class derived : public base
{
public:
derived() {}
~derived() {}
void do_start() {}; // I REALLY do need a do_start in base..
void override_func() {
// implementation
}
// more
};
int main() {
derived *d = new (std::no_throw)derived(); // use derived directly
d->do_start();
d->override_func();
delete d;
}
For some reason I'm led to believe that if you're unable to access
derived members through a base pointer, something was amiss about your
design (as in the case above). Am I off on this?
As always thanks in advance.
As others have already pointed out, it doesn't make sense to discuss
whether or not inheritance is the appropriate mechanism for solving
your problem because we don't know what the problem is. I have found
inheritance useful for defining a common interface which can be used
by objects of other classes which don't need to know the derived
type(s). Here are some examples of how inheritance can be used like
this:
(a) A database query. Some queries read, some write, yet there is an
awful lot of functionality shared between the two. For example, the
database connection object need not always know what kind of query it
is just to fetch the data associated with an error the query might
have produced;
(b) You have an application which needs to read different kinds of
barcodes and print the data as output to an XML file. There is an
abstract base class "Barcode" which knows how to print its data. All
the application needs to know how to call is the barcde's virtual
"PrintMe()" function;
(c) You have a collection of different graphic shapes (circles,
squares, triangles, etc.) and all your collection needs to do is to
print out each shape's area. Only the derived shape classes know how
to do that, so there is an abstract class "Shape" which has a virtual
function "CalcArea()" which is overridden by each derived class.
You get the idea?
--
Bob Hairgrove
No**********@Home.com