Access to protected members from the outside with this trick, but is it really?

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.

+4
source share
2 answers
 reinterpret_cast<Foo2&>(f2)).GetI() 

Technically, this is Undefined behavior. So it may work, but it is not necessary.

+5
source

You close the Foo object with the Foo2 object.

Drop is a conversion from a base class to a class derived from a base class. Dropping is only safe if the object addressed at run time actually accesses the object of the derived class

To protect your code, you should use dynamic_cast to verify that the downstream value is invalid.

Using reinterpret_cast not recommended for down-casting. Use static_cast or dynamic_cast .

Reading pieces of articles, many of them DO NOT USE DOWNLOAD like you. One dangerous example is to have virtual void GetI() in Foo .

+1
source

All Articles