1

I am trying to design something that doesn't rely on casting. I asked a question here and I believe ultimately there is a better way, so I'm asking for advice.

I have a generic Object of which there will be subclasses.

I have generic Node objects which contain as a member a pointer to an Object. Nodes can be subclassed to offer more specific behaviour about how to handle their Object as well as to set what type of subclassed Object that particular node is using.

The problem is that my base class requires as a member Object * myObject so that my app can traverse all the Nodes and call a draw function on all the myObjects.

But how to handle the situation of a subclassed Node calling custom functions on a subclassed Object? These functions could be truly unique and have no place in a base class.

One option I considered is for the subclass to store its pointer member as MyObjectSubclass * myObject but a subclass cannot override a base class member, right? So that doesn't really work.

I'd appreciate a more experienced advice for this type of design.

Community
  • 1
  • 1
johnbakers
  • 24,158
  • 24
  • 130
  • 258
  • 1
    I have found a 5 year old question with a rather confident answer suggesting that downcasting is perfectly acceptable in this case. The question is quite similar to mine above: http://stackoverflow.com/a/298590/768472 – johnbakers May 16 '13 at 03:43

1 Answers1

0

Work with interfaces. Have each Object child inherit from interfaces appropriate for that class, and give the base Object class a method that can retrieve the interfaces.

This is the way Microsoft's COM works.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • @Fellowshee, dual or even more. As many interfaces as are required. – Mark Ransom May 16 '13 at 01:48
  • @Fellowshee, in fact your base class could be an interface too, IDrawable for example. – Mark Ransom May 16 '13 at 01:49
  • 1
    Why is it considered better then using `dynamic_cast`? By making Object provide those interfaces you violate `classes should be opened to extensions but closed to modifications` because in case you add more subclasses you'll have to alter base class. At the same time quering subclass interface from base class also may return you `nullptr` - the same way as `dynamic_cast`, though `dynamic_cast` does not violate `extension/modification` principle – Andrew May 16 '13 at 08:32
  • @Andrew I agree that this is a confusing proposition and without a concrete example I am unable to fully understand its relevance or power in this case. I suspect there are better solutions for my use case. – johnbakers May 16 '13 at 11:28