If I have the following class:
class Foo { protected: int i; public: Foo() : i(42) {} };
Naturally, I do not have access to protected members from the outside, but I can do this little trick: first I create a new class that inherits Foo:
class Foo2 : public Foo { public: int GetI() { return i; } };
Now that I have a Foo instance or a pointer to such an instance, I can access the protected member through casting (since I am not using any additional elements):
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 be any bad consequences? The compiler does not mind, there are no runtime checks.
source share