Can I use private variable by shifting address?

Dear experts

For debugging purpose, Can I call a private member in a Class by shifting the address of the Object pointer? Where the class is inherited from TObject:

class SomeClass : public TObject
{
    private:
        typedef std::map<std::string, int> A;
        typedef std::vector<std::string> B;
        TFile* fFile;
        TTree* fTree;
...
};

Is there a way to access fFile by shifting the address of pointer of theobject of SomeClass?

Hi,

Yes. This is also the way ROOT manages to serialise objects internally. However, this is something I would not advise to do if not forced to: it is always better to design well the classes rather than resorting to these measures. Below you find an example of how this can be achieved using ROOT’s type system (for the sake of the example, I used public data members to show their addresses):

class SomeClass : public TObject {
public:
   typedef std::map<std::string, int> A;
   typedef std::vector<std::string>   B;
   TFile *fFile = new TFile("a.root", "recreate");
   TTree *fTree;
};

void a()
{

   auto cSomeClass  = TClass::GetClass("SomeClass");
   const auto fFileOffset = cSomeClass->GetDataMemberOffset("fFile");
   auto c = new SomeClass;
   cout << c << endl << &(c->fFile) << endl;

   cout << fFileOffset << endl;
   auto fp = (TFile **)(fFileOffset + (Longptr_t)c);
   auto f  = *fp;
   cout << fp << endl << f->GetName() << endl;
}

Best,
D

Thank you for the answer, but I want to access a private variable in such class structure, which means I can’t use GetDataMemberOffset(), is there a way to do that…?

Hi,

I do not understand what is exactly the reason why you cannot use ROOT’s type system. The example above shows how to access a private variable in such class structure (I use public for the sake of the example, the memory layout is the same if you replace it with public).
You can of course not use ROOT to do such a thing. That would mean following the procedure above but figuring out or hardcoding the offsets by yourself in bare C++.

Cheers,
Danilo

Oh sorry I misunderstood your answer, yes you are right!

Perfect, no problem. Let us know how this goes!

D