Reputation: 1711
I have a design problem that I am not sure how to handle in the best way. I want my code to be future proof and still not be to messy and complex (the plight of a geek).
Currently my design has the following setup
derived class D derived class E
^ ^
| |
derived abstract class B -> derived class C
^ ^
| |
Abstract Base class A
class B
differs from class A
, class D
and class E
differs from class B
and C
differs from class A
.
As these classes differ I need to use the dynamic_cast
operator.
A* a1 = new class C;
C* c1 = dynamics_cast<C*>(a1);
if(c1){ //Success!!!}
...
As you can see I will be wanting to use dynamic_cast
a lot! I need to try and find a nice way of doing this that is not full of if()
statements extra.
Is there a neat way of doing this? I seem to remember seeing something in a Scott Meyers book, but I am away from home and can not access it for a week or two.
Any references/examples would be much appreciated.
Also if need be I could make class B
into an interface which would be a sort of solution
B* d1 = new D;
B* e1 = new E;
but not ideal.
NOTE: I have added this example to show my current design failure
class A {...};
class B: public A {
public:
virtual std::vector<objectType1*>& getObjectType1();
};
class C: public B {
private:
void newFunction();
};
A* c1 = new C();
std::vector<objectType1*> example = c1->getObjectType1(); // Wrong; need dyanmic_cast :-(
can not access getObjectType1()
without dynamic_cast
as the static type A does not know about this function. I need to rethink my design. Any ideas?
Upvotes: 3
Views: 3321
Reputation: 101456
In a properly designed object hierarchy, the use of dynamic_cast
is a fair rarity. Sure, it exists to cast up & down a polymorphic tree, but that doesn't mean you have to use it.
Think about this. Why would you need to use dynamic_cast
, generally speaking? Because the base pointer you have doesn't provide the facilities you need, right? And what is the point of polymorphism? To provide different behavior for similar operations, where the behavior is chosen at run-time, right?
Aren't those two statements somewhat contradictory? If your object's interface is designed correctly, then you don't really care what kind of behavior is going to be employed when you call ->Foo()
-- you just want to call ->Foo()
.
If you need to make frequent use of dynamic_cast
, it's a code smell that tells you that there's something wrong with your interfaces. Maybe you're trying to shove too much in to one interface?
Upvotes: 12