I stumbled across this pattern today. It compiles fine but does not work correctly at runtime. ("Der1" is printed twice)
I can sort of see why, given that the address dereferenced is always the same, but I don't fully understand.
I am not looking for a solution or workaround, I have already restructured this code. Just interested to understand what happens under the hood in this scenario.
#include <iostream>
struct Base
{
virtual void Func() = 0;
};
struct Der1 : public Base
{
virtual void Func() override
{
std::cout << "Der1" <<std::endl;
}
};
struct Der2 : public Base
{
virtual void Func() override
{
std::cout << "Der2" <<std::endl;
}
};
static union Ders
{
Der1 D1;
Der2 D2;
Ders() : D1() {}
} theDers;
static Base * b = &theDers.D1;
int main()
{
b->Func();
b = &theDers.D2;
b->Func();
return 0;
}