I am trying to find an efficient way (using polymorphism) to copy specific attributes between two derived classes externally. I have a set of data classes that derive from a base class DataClassA
. I want to operate on these data classes in a separate filter class that takes DataClassA
references as input and output parameters. The filter will perform the necessary operations common to DataClassA
, but I also want to propagate class-specific attributes from my input to output class. Consider:
class DataClassA
{
public:
virtual void copyAttributes( DataClassA& copyFrom );
}
class DataClassB : public DataClassA
{
public:
virtual void copyAttributes( DataClassA& copyFrom );
};
class DataFilter
{
void run( DataClassA& input, DataClassB& output )
{
//do some calculations here
...
//then copy over attributes
output.copyAttributes( input );
}
};
My problem is obviously that the copyAttributes()
depends on needing to know the types of both the input and output derived classes (which need not necessarily be the same). However, the filter will only handle references to the base class DataClassA
. My reflex is to simply institute a dynamic_cast
, though I risk getting my hand slapped (and other possible negative consequences). If I did this, I would simply create a copyAttributes
method for each derived class that called the copyAttributes
of the parent class, and then use dynamic_cast
to see if the copyFrom
object is of the same type:
void DataClassB::copyAttributes( DataClassA& copyFrom )
{
//copy attributes from parent class
DataClassA::copyAttributes( copyFrom );
//test if the class being copied from is of type DataClassB
DataClassB* copyPtr = dynamic_cast<DataClassB*>©From;
if( copyPtr != NULL )
{
//copy DataClassB-specific attributes from copyFrom to this
...
}
}
The most similar post I could find on the problem was here Virtual functions and polymorphism. My primary questions are: 1) is my proposed use of dynamic_cast inappropriate?; and 2) if so, how might I implement this copyAttributes
another way? There were references to using a visitor design pattern though I'm not sure how that would look.
This is kind of a simpler version of what the Visualization Toolkit (VTK) does in the sense that I'm using classes of filters that operate on a number of different data classes. Interestingly, they handle RTTI by including macros that include the string name of classes and parent classes that can be compared directly for correct downcasting of datatypes.