views:

39

answers:

1

I'm trying to replace all dynamicCasts in my code with QT's objectCast. But I've run into a bit of a snag. Here's the hierarchy of my objects:

class ABase : public QObject

class IAbility; // Registered as Qt Interface
class ISize; // Registered as Qt Interface

class Derived : public ABase, public IAbility, public ISize; // Uses Q_INTERFACES

Using objectCast I can convert a Derived to a ISize or IAbility. However, in one point of my code I want to perform the following conversion: Derived->ISize->IAbility. That last cast is where I get an error. Since IAbility does not relate to ISize in any way, that could cause a problem. I could do a dynamic cast at this point, but I'd rather not.

+2  A: 

As I see it you have three options:

  1. You relate the two interfaces to each other by putting them in an inheritance hierarchy, letting one inherit the other. This will let you cast from one to the other, in one direction, but will also be clonky and wonky if there is no real realtion between the two.
  2. You create a super interface that the two others inherit from, and use that as a common casting ground, if you will. This will let you cast the object two ways, using the super interface, but will also create an unnessecary abstraction.
  3. You cast your Derived object to an ISize, do what you want, and then cast that same derived reference to an IAbility. Hence: Derived -> ISize, Derived -> IAbility.

I would go for option 3, simply because it's the least forced solution, abstraction-wise.

Banang
Unfortunately, the way the classes are laid out in the actual application. The casting is happening in a class that doesn't know about Derived, so I'm not sure that that would work. But option 2 would work. I do have a top level Object class so creating a top level IObject interface that all interfaces/objects must virtually inherit may not be that bad of an option. Thanks.
Timothy Baldridge
Glad I could help. Best of luck to you!
Banang