[comp.lang.c++] Restricting Type of Member in Subclass possible?

kramer@tpwest.enet.dec.com (06/07/90)

Hi there!
Here is a beginners question:

Assume I have a class Node and a class Tree.  Tree has a protected
member: Node * p.
Now I like to add some functionality without changing Nodes and Trees.  
I like to add some marking stuff to Node, so I create a DerivedNode
class with a function mark().  And I want to be able to mark Trees which
consist entirely of DerivedNode instances, so I create a DerivedTree
with function mark().

Inside DerivedTree:mark() I call p->mark()

Sure enough, the compiler complains because *p is of type Node, and I
did not want to define
Node::mark().

What I would like to do is to state that for DerivedTrees *p is of type
DerivedNode.  Which is alright
since DerivedNode is a subclass of Node (so all stuff defined in Tree
would still work).

Is there any way of doing that?
Should I restructure my abstractions? (if so, how? (What if Node and
Tree are library classes?))

Thanks a lot!!!!
	axel

pkturner@cup.portal.com (Prescott K Turner) (06/13/90)

axel (kramer@tpwest.enet.dec.com) asks whether, in deriving a 
DerivedTree class from a Tree class, it is possible to redeclare
a member p, which had type Node*, to be a DerivedNode*.  The idea
is that p would still be the same member, but it would point to a
more specific type whenever the containing object was DerivedTree.

This is an excellent question.  Unfortunately, the capability you're
looking for is not what you get from the natural way of redeclaring p.
What C++ gives you is a different pointer p, and any functions operating
on the Tree part of the DerivedTree would have access to the original
Node * p, and not to the redeclared pointer p.

I ran into this kind of thing a year or two ago while using cfront 1.2,
and did not find any clean workaround.  

--
Prescott K. Turner, Jr.
Language Processors, Inc.
959 Concord St., Framingham, MA 01701 USA    (508) 626-0006 x232
UUCP: ...sun!cup.portal.com!pkturner    Internet: pkturner@cup.portal.com