C
Code4u
My colleagues and I have been discussing techniques for implementing
interfaces in C++. We're looking for a mechanism similar to COM's
QueryInterface, in which a certain types of objects can be queried, at
run-time, for a particular interface and if it is supported, a pointer
or reference to that interface passed to the caller. Two possible
implementations came up, multiple inheritance and composition. Using
MI the class multiply inherits from all the classes it needs to
implement interfaces for. With composition a class contains a
collection of pointers to objects implementing the required
interfaces.
Both solutions have a little ugliness. With MI the interfaces the
class supports is fixed at compile time, to test whether an object
supports the interface dynamic_cast<T>, where T is the class
implementing the interface, would be executed. Using composition, each
of the objects in the container implements an interface, which
contains a back pointer to the parent object. To get a specific
interface the parent object would implement a method which would scan
the interface collection for a particular interface and return it to
the caller.
What do you think is the better approach? Is there a better pattern?
TIA
interfaces in C++. We're looking for a mechanism similar to COM's
QueryInterface, in which a certain types of objects can be queried, at
run-time, for a particular interface and if it is supported, a pointer
or reference to that interface passed to the caller. Two possible
implementations came up, multiple inheritance and composition. Using
MI the class multiply inherits from all the classes it needs to
implement interfaces for. With composition a class contains a
collection of pointers to objects implementing the required
interfaces.
Both solutions have a little ugliness. With MI the interfaces the
class supports is fixed at compile time, to test whether an object
supports the interface dynamic_cast<T>, where T is the class
implementing the interface, would be executed. Using composition, each
of the objects in the container implements an interface, which
contains a back pointer to the parent object. To get a specific
interface the parent object would implement a method which would scan
the interface collection for a particular interface and return it to
the caller.
What do you think is the better approach? Is there a better pattern?
TIA