mardi 14 avril 2020

Is there a design pattern to achieve runtime polymorphism without using dynamic cast for this scenario?

Let's say I have a class structure where parent class P stores a vector of pointers to child objects of class C.

class P {

public:

P()
{

}

private :

vector<C*> children;

}

Also, child class C is a base class and D,E are derived classes of C.
D and E have some unique member variables.

class C {

public:

C() {

}

virtual ~C() {

}

virtual initialize() = 0;

}

class D : public C {

public:

initialize() override;

//Member variable unique to D
int value;

}

class E: public C {

public:

initialize() override;

//Member variable unique to E
vector<int> vector_value;

}

At runtime, objects of C and D are created and added to parent P's children vector.

At a later time I want to iterate over this vector, determine the object type and use the child's unique member variable.

I know I can achieve this by using a dynamic cast :

for( C* child : children)
{
   D* d_child = dynamic_cast<D*>(child);
   if( d_child != nullptr)
   {
      // This object is of type D 
      do something with  d_child->value ...
   }
   else
   {
      // This object is of type E
       do something with  d_child->vector_value...
   }
}

However, it is a bad design when we have to check types as iterated by many answers here Check for derived type (C++)

So I want to know if there is a standard way or a design pattern that will help me achieve this functionality in a better manner ?

Aucun commentaire:

Enregistrer un commentaire