This Seems to be pattern I run into a Lot an I don't know how to fix it
without a lot of "else if" statements.
I have several Classes, that look something like this
Class CBase : public CObject{
virtual void CopyFrom(CBase* other);
}
Class CDerived1 : public CBase {
virtual void CopyFrom(CDerived1* other);
}
Class CDerived2 : public CBase {
virtual void CopyFrom(CDerived2* other);
}
Copy From Makes a Copy of All the data in the "other" Object to this Object.
Class CHelper
{
public:
void SetObj(CBase* newVal);
private:
CBase* m_obj;
}
///////////////////////////////
// newVal could be anything
// CBase, CDerived1 , CDerived2....etc
void CHelper::SetObj(CBase* newVal)
{
CRuntimeClass* newClass = newVal->GetRuntimeClass();
CBase* newObj = (CBase*)dragClass->CreateObject();
newObj->CopyFrom(newObj);
}
//this does not work as one might expect
//because the last line Always calls
//CBase::CopyFrom(CBase* other);
//regardless of the runtime class of "newVal".
I can alway change the last line to something like this this
if (newVal->IsKindOf(RUNTIME_CLASS(CDerived1)))
newObj->CopyFrom((CDerived1*) newObj);
if (newVal->IsKindOf(RUNTIME_CLASS(CDerived2)))
newObj->CopyFrom((CDerived2*) newObj);
if (newVal->IsKindOf(RUNTIME_CLASS(CBase)))
newObj->CopyFrom((CBase*) newObj);
Or I could Over ride CopyFrom(CBase* other);
for all the Derived Classes.
but what I REALY would like to do is cast "newVal" to its runtime class
at runtime, without knowing what it will be at compile time.
So how do I case a class to a class at runtime, when I don't know the
class at compile time?
is this possible?
if not is what is the logic behind it?
why is what I want to do a bad idea?
thanks
how