0

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());
Kwhjsvo
  • 11
  • 3
  • 2
    Almost all of that stuff inside `BaseFactory` doesn't matter. In essence it does `Derived derived; return &derived;`. And since `derived` is a local variable inside `BaseFactory`, it goes away when `BaseFactory` returns, so the behavior of the program is undefined. – Pete Becker Dec 28 '21 at 14:22
  • `auto base` isn't a reference so your object gets copied into an instance of `Base`, use `auto& base` instead – Alan Birtles Dec 28 '21 at 14:26
  • Got it to work by changing `void*` return type to `Base`. Also in the speed of posting I've removed `static` before `Derived` inside the factory function, so the whole question was just stupid from the beginning. I think I may rewrite it later, I'm curious what's happening when casting from and to `void*` and why is it breaking stuff. – Kwhjsvo Dec 28 '21 at 16:17
  • The missing `static` and `auto base` were causing the problem, I'm guessing in removing the `void*` you fixed those issues as a side effect – Alan Birtles Dec 28 '21 at 16:19
  • You are returning pointer to a local. :( – Tanveer Badar Dec 29 '21 at 11:00
  • @TanveerBadar Notice the `static` though. Suits my situation since the factory is going to be called only once. Or did you mean the pointer in the second block? – Kwhjsvo Dec 29 '21 at 11:06

0 Answers0