Accessing protected members from outside with this trick, but is this valid?

c++

Solution

reinterpret_cast<Foo2&>(f2)).GetI()

Technically, this is Undefined behavior. So it might work but it does not have to.

Problem

If I have the following class: ``` class Foo { protected: int i; public: Foo() : i(42) {} }; ``` Naturally, I don't have access to protected members from the outside, but I can do this little trick: first I create a new class which inherits Foo: ``` class Foo2 : public Foo { public: int GetI() { return i; } }; ``` Now, whenever I have an instance of Foo or a pointer to such instance, I can access protected member via casting (since I don't use any additional members): ``` Foo *f = new Foo(); Foo f2; std::cout << ((Foo2*)f)->GetI() << std::endl; std::cout << (reinterpret_cast<Foo2&>(f2)).GetI() << std::endl; ``` I understand why this works, but will there ever be any bad consequences? Compiler doesn't mind, there aren't any run time checks.

Original source