In the example below I have a base and a derived class, both almost identical but the derived overrides a function. The base class has a large member so I want to conserve memory usage by only creating a derived class object and then cast that to a base object which therefore will call the non-overridden function.
However, as soon as the cast'ed object is passed into InitBuffer() the object appears as it's original class. I suppose this doesn't really surprise me (since it's really just passing a memory pointer to the object) but I can't figure out how to "fully cast" so that it works the way I want. Is this possible?
class BaseClass
{
public:
virtual void InitBuffer(void) { /* ...do base stuff... */ }
private:
char BigBuffer[1024*1024];
};
class DerivedClass : public BaseClass
{
public:
virtual void InitBuffer(void) { /* ...do derived stuff... */ }
};
void DoSomething(BaseClass &MyObject)
{
MyObject.InitBuffer();
}
void NotWorkingFunctionality(void)
{
DerivedClass DerivedObj; /* Reuse this object for both cases */
volatile bool IsFoo = true;
if (IsFoo)
/* I want this to end up calling BaseClass's InitBuffer */
DoSomething(dynamic_cast<BaseClass &>(DerivedObj)); /* Doesn't work :( */
else
/* I want this to end up calling DerivedClass's InitBuffer */
DoSomething(DerivedObj); /* Works great! */
}
void DesiredFunctionality(void)
{
DerivedClass DerivedObj;
BaseClass BaseObj; /* Problem: Twice the memory usage that I want!! */
volatile bool IsFoo = true;
if (IsFoo)
DoSomething(BaseObj); /* Works great! */
else
DoSomething(DerivedObj); /* Works great! */
}