This question has already been answered:
How can I access the private fields of a class? It does not use accessors and friend classes.
This question has already been answered:
How can I access the private fields of a class? It does not use accessors and friend classes.
A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .
Only through the addresses of these fields.
#include <iostream> class A { private: int a; virtual int b () { return a; } }; class B { public: int a; virtual int b (); }; int main() { A obj; B* ptr = static_cast<B*>(static_cast<void*>((&obj))); ptr->a = 42; std::cout<<ptr->b()<<std::endl; return 0; } There are 3 ways to do what you ask for.
#define private public and connect the appropriate header file (of course, meaningless in the case of PIMPL -like schemes).vfptr and vcbl in the class, the relative displacement may change, that is, the method is non-portable.template . The most beautiful and even in some ways elegant solution.You can like this:
class A { public: A(int _a) : a(_a) {} private: int a; }; class B { public: B(int _b) : b(_b) {} public: int b; }; int main(int argc, char *argv[]) { A a(0); ((B*)(&a))->b = 1; // Aa = 1 return 0; } That is, writing in parallel a complete copy of this class, making the required fields public.
Recently, I myself had a similar problem. Invented a new way. I do not know whether it will suit you or not. If this class has at least one friend (no matter what, available to you in the code or not), then you can declare your class with the name, which is the name of a friend. Example:
In the Graphics.h file:
class Material; class Graphics { public: Material* CreateMaterial(Color color) { Material* material=new Material; material->color=color; return material; } }; In the Material.h file:
class Material { friend class Graphics; private: Color color; }; Suppose you had such a code and you don’t touch it. And then suddenly we in the main.cpp file declare an imposter Graphics:
#include "Material.h" class Graphics { static void ChangeMaterialColor(Material* material, Color newcolor) { material->color=newcolor; } }; Now we can change the color of the material with the help of such an impostor-friend. The only point is that two Graphics definitions should not be declared connected to one cpp file, otherwise they will conflict. In my example, this is observed: Material does not connect Graphics, but is content with its declaration.
Source: https://ru.stackoverflow.com/questions/66233/
All Articles