I discover this compiler trick and I cannot find a name for. Have you any idea?
On an Intel processor, I can cast a variable from its base class to an inherited class. It works with MSVC, gcc and clang and I am very confused.
#include <string>
#include <iostream>
class A
{
public:
virtual std::string print() const { return "A"; }
};
class B : public A
{
public:
std::string print() const override { return "B"; }
std::string printOther() const { return "other"; }
};
int main()
{
A a;
std::cout << a.print() << std::endl; // print A
std::cout << static_cast<const B&>(a).print() << std::endl; // print A
std::cout << static_cast<const B&>(a).B::print() << std::endl; // print B
std::cout << static_cast<const B&>(a).printOther() << std::endl; // print other
try
{
std::cout << dynamic_cast<const B&>(a).printOther() << std::endl; // throw std::bad_cast
}
catch (const std::bad_cast& e)
{
std::cout << e.what() << std::endl; // print std::bad_cast
}
std::cout << ((const B&)a).print() << std::endl; // print A
std::cout << ((const B&)a).B::print() << std::endl; // print B
std::cout << ((const B&)a).printOther() << std::endl; // print other
std::cout << reinterpret_cast<const B&>(a).print() << std::endl; // print A
std::cout << reinterpret_cast<const B&>(a).B::print() << std::endl; // print B
std::cout << reinterpret_cast<const B&>(a).printOther() << std::endl; // print other
// error: invalid 'const_cast' from type 'A*' to type 'const B*'
//std::cout << const_cast<const B&>(a).print() << std::endl; // print A
//std::cout << const_cast<const B&>(a).printOther() << std::endl; // print other
return 0;
}