home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!rational.com!thor!rmartin
- From: rmartin@thor.Rational.COM (Bob Martin)
- Subject: Re: Casting to an object of a derived class
- Message-ID: <rmartin.721099675@thor>
- Sender: news@rational.com
- Organization: Rational
- References: <VANDER.92Nov2153247@vancouver.stars.flab.Fujitsu.co.jp>
- Date: Sat, 7 Nov 1992 01:27:55 GMT
- Lines: 69
-
- vander@flab.fujitsu.co.jp (Mike van der Velden) writes:
-
- |I've got:
-
- | class GenericList {
- | public:
- | void* next ();
- | //...
- | };
-
-
- |I'd like to do this:
- | class MyObject : public GenericList {
- | public:
- | int i;
- | };
-
- | MyObject obj;
-
- |Then I'd like to be able to refer to obj.next().i. Unfortunately, the
- |next() returns a reference to an object of type void (or GenericList,
- |if I want), and of course i is not a member of that class. I need
- |next() to return a reference of type MyObject in this case (and other
- |objects in other cases).
-
- This is one of the difficulties with contravariant return types. It
- would sometimes be very nice if a member function could return a
- pointer or reference to the most derived object, rather than to the
- base. However, the language does not support this feature.
-
- It will, soon, support covariant return types, but these will require
- that each derived class repeat the function declaration with the new
- return type.
-
- So, in general, there is no way to achieve all your goals. You are
- most likely going to have to put extra member function in each
- derivateive of GenericList, which casts the output of next to the
- derived type.
-
- However, I would like to make another kind of observation. The
- practice of inheriting the "ability to be put on a list" has the
- weakness that it precludes your objects from being on more than one
- list at a time. Since each object has only one link, it can be in
- only one linked list at a time. But this is not enforced by your
- class, so if you try to put the object on more than one list at the
- same time, you will wind up corrupting lists in odd ways.
-
- A better approach is to use "carriers" in the linked list. A carrier
- is an object of the form:
-
- class Carrier
- {
- public:
- Carrier* link;
- void* object;
- };
-
- When you add an element to a linked list, the list creates a new
- carrier, links the carrier into the list, and points the 'object'
- pointer to the object you are adding to the list.
-
- If you combine this technique with templates, you end up with a very
- powerful, general purpose linked list class.
-
- --
- Robert Martin Training courses offered in:
- R. C. M. Consulting Object Oriented Analysis
- 2080 Cranbrook Rd. Object Oriented Design
- Green Oaks, Il 60048 (708) 918-1004 C++
-