Why this code is valid in C++:
class Base
{
public:
Base() = default;
// base class stuff...
};
template<typename NumericType>
class Numeric : public Base
{
public:
Numeric() : m_value() {}
void setValue(NumericType value) { m_value = value; }
NumericType value() const { return m_value; }
private:
NumericType m_value;
};
int main()
{
auto integerPtr = new Numeric<int>();
Base *basePtr = integerPtr;
if (auto doublePtr = static_cast<Numeric<double>*>(basePtr)) {
doublePtr->setValue(6543423.634234);
std::cout << "Wow: " << doublePtr->value() << std::endl;
}
return 0;
}
To be honest, I was expecting compilation errors or at least that static_cast will fail but, this code example compiles, runs, and even works correctly.
Compiled with MCVS2019 32bit.