I came up with a class that uses a protected nested struct, intending for derived classes to augment the struct. To that end, I declared a virtual method for allocating the struct.
Now, the base class does some not-trivial amount of work in processSomeData
and I would like the derived class to reuse it.
Which leads to the following:
class A
{
public:
virtual void doProcessing(); // uses processSomeData()
protected:
struct someData
{
virtual ~someData() {};
// data members
};
virtual someData* processSomeData(); // uses allocateSomeData()
virtual someData* allocateSomeData();
};
class B : public A
{
public:
virtual void doProcessing()
{
derivedData* myData =
static_cast<derivedData*>(A::processSomeData()); // *** seems a little suspect
// do work on the additional data members in myData
}
protected:
struct derivedData : public someData
{
// more data members
};
virtual derivedData* allocateSomeData();
};
Because allocateSomeData
is overridden, I know A::processSomeData
is returning a someData*
pointing to a derivedData
, so static_cast is definitely safe.
That said, it feels a little off that I should have to cast from a base to derived at all, when everything else seems pretty kosher.
Is there a better/proper way to do this, without using a cast? Or do I have to re-design my classes/structs?