Best was to model type cast

Started by
1 comment, last by Desperado 16 years, 2 months ago
Hello folks, currently, I'm coding a program that has a scenegraph-structure, which means that you have one node class and several subclasses. Each of thos classes may even implement a couple of interfaces, for serialization for example. Example: class DerivedNode : Node, InterfaceA,InterfaceB { void MethodFromNodeClass() {} void MethodFromInterfaceAImplementation() {} void MethodFromINterfaceBImplementatino() {} }; You get the idea. My question now is, is there a common and robust pattern for handling type testing and type conversion when it comes to polymorphy? My first idea was to simply use a dynamic cast: //Node* someNode; DerivedNode *derivNode = dynamic_cast<DerivedNode*>(someNode); if (derivNode) derivNode->methodSFromDerivedNodeClass(); else std::cout << "This isn't a DeriveNode object" << std::endl; } , but this of course leaves testing, casting and error handling completely in the hands of the implementing person. Besides, it might be possible that I need the "InterfaceA" and "InterfaceB" parts of the class as standalone objects so I would rather use a "has-a" relationship class DerivedNode : Node { InterfaceA* subobjectOfTypeA; InterfaceB* subobjectOfTypeB; } however, then I couldn't just typecast the DeriveNode-object to InterfaceA and InterfaceB. Some class implementations I have seen carry an inheritance list with them and handle the type conversion manually by implementing a "cast" method that returns the approprate data. So which design methods exist there and which would you recommend for my case? Thanks in advance
Advertisement
struct Node {  template < class T >  T * get() {    return dynamic_cast<T*>(data);  };  SomeCompoundObject * data;};...Node n;MyInterface * mi = n.get<MyInterface>();if (mi != NULL) {  // do stuff};
Thanks for the suggestion, it didn't fully answer my question, so I will state it more detailed:

I have seen sourcecode where the type conversion between a class and it's implemented interfaces wasn't done directly via a cast operator but by implementing a cast table inside the class that listed all the interfaces and several "castToInterfaceWhatever()" instance method that handled the conversion.

What might be the sense of that?

This topic is closed to new replies.

Advertisement