I have a class A, as below:
struct MY_DATA
{
int m_nType;
union
{
DWORD m_dwBData;
double m_dCData;
} u;
};
class CClassA
{
public:
CClassA(BYTE* lpData, UINT uSize);
virtual ~CClassA(void);
MY_DATA m_Data;
};
CClassA::CClassA(BYTE* lpData, UINT uSize)
{
::memcpy(&m_Data, lpData, uSize);
}
CClassA::~CClassA(void)
{
}
and a class B derived from class A, as below:
class CClassB : public CClassA
{
public:
CClassB(BYTE* lpData, UINT uSize);
virtual ~CClassB(void);
void ProcessBData()
{
m_Data.u.m_dwBData ++;
}
};
CClassB::CClassB(BYTE* lpData, UINT uSize)
: CClassA(lpData, uSize)
{
}
CClassB::~CClassB(void)
{
}
Then I recieve a memory block lpData with size of uSize. uSize is same as the size of MY_DATA. But I don't know m_nType in advance.
My purpose is to determine the type of the memory block and invoke the corresponding processing function to process the data follows the type.
So I do that in the following code snippet:
CClassA a(lpData, uSize);
if (a.m_Data.m_nType == 0)
{
CClassB& b = (CClassB&)a;
b.ProcessBData();
}
I will create an instance of Class A by using a memory block, then if the type of the data is 0, then we will know the data is of class B, then I will promote the oriignal instance to its child class ClassB so that we can invoke ProcessBData to process the data specific to class B.
However, I doubt if this will work, since class B is a child class of A, so it will contain more entries than class A, by prmoting a base class to its child class, will that cause problem?
Another solution is create a new instance of Class B after knowing the type is 0, with the same memory block. However, this will decrease the performance, since we copy the memory block twice, once to class A and once to class B.
So how to solve such a delimma?
Thanks