Timothy Baldridge
Timothy Baldridge

Reputation: 10683

objectCast Sideways casting

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.

Upvotes: 1

Views: 622

Answers (1)

Mia Clarke
Mia Clarke

Reputation: 8204

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.

Upvotes: 3

Related Questions