Since it's incorrectly understood, I have to clarify. All the following solutions do not require you to recompile the object. To use a class in your code, if it's compiled into an object file, you should include header file with the declaration of that class.
#include <class.h>
ObjectFoo instance;
It is possible (but dangerous unless you're careful) to change the header (a) or copy the header to another place and include that header (b), without recompiling the class itself.
#include <class_fixed.h>
ObjectFoo instance;
Your code, where you included the new header will just think that within the object file (which you haven't recompiled!) he will find implementation of the class declared as in class_fixed.h
. While there persists the class declared as in class.h
. If you change offsets of members (add new members for example) in your new header, you're dead and the code will not work properly. But just changing the access works fine. Compiled code doesn't know about access, this matters only at the compilation strange.
This is not always harmful. In everyday life you encounter such a change when you install new version of a library into your system and do not recompile all programs that depend on it. But it should be handled with care
There are several solutions.
memcpy()
Don't! Do not memcpy as object copying sometimes undergoes specific policy imposed by the class designer. For example, auto_ptr
s can't be just memcopied: if you memcopy the auto_ptr
and then destructor is ran for both, you'll attempt to free the same memory two times and the program will crash.
Change private:
to public:
in header or with macro
If your license permits it, you may solve your problem by editing the header file that comes with the implementation of the class. Whether the source code of the implementation (i.e. cpp-file of the class) is under your control doesn't matter: changing private to public for data members (in header) suffices and works just fine even if you're given a binary-only library that contains class definition. (For member functions changing access sometimes changes its internal name, but for MSVS and GCC it's ok.)
Adding a new getter function
While changing private
to public
is nearly always ok (unless you rely on specific compile-time checks that should break the compilation if class has certain member accessible), adding new getter function should be performed carefully. The getter function should be inline (and therefore defined in the header file of the class).
reinterpret_cast
The cast works just fine if you're NOT casting a pointer to dynamic base class (dynamic means "with virtual functions or bases") whose actual instance at the moment of casting can be derived from the class at the particular piece of code.
protected:
And just in case you forgot. C++ can declare members protected:
, i.e. accessible only to the classes derived from the given. This may fulfill your needs.