Let's say that I have a class Derived which is a child from Base class.
And in the Base class I have a function that is virtual and will be overridden in Derived. In Base it's like this:
virtual std::string someString() { return "not defined"; }
Then it's being overridden in Derived to return something else:
std::string someString() override { return "hello from derived"; }
It's working when I slice an instance of Derived, passing it to a function accepting a Base as an argument. Although, this time I need to cast Derived to Base to void* and then from void* to Base and call someString function.
Casting inside the derived looks like:
void* BaseFactory()
{
Derived derived;
// Do some other stuff
auto base = static_cast<const Base&>(derived); // Acted the same with or without const
return &base;
}
The factory function is called, and the class is recovered like this:
void* hBase = BaseFactory();
Base* pBase = static_cast<Base*>(hBase);
Although, during the pBase->someString() call, it still returns "not defined".
Now I don't know what might have gone wrong. Are my casts just not the right ones? I see that somehow the passed class is not persisting overloads, I don't know why though. Can you please point me in the right direction for this to work? The whole idea is that my Base (with overrides) made out of Derived has to be cast to void* and then back to Base.
Edit: This should look like:
void* BaseFactory()
{
static Derived derived;
return &derived;
}
Base* base = static_cast<Base*>(BaseFactory());