Understanding the use of GetObject() method

Let’s say I have a root file called “example.root” where I have a tree called “t”. The tree has three branches for three different variables, but other than that, there is nothing more important.

Now, let’s say I want to write a .cpp file where I want to read the “example.root” file using the TFile method. So first I simply do:

TFile* f = new TFile(“example.root”);

Now, based on the information given in this link suggests that in regular code, one should use TFile::GetObject() method, for example,

root [3] TTree* t1; //could just simply be TTree* t;
root [4] f->GetObject(“t”, t1);

Then, if I want to scan the tree “t”, I can do:


Could someone help me understand why we need to create a pointer “t1” and then use GetObject() method? I am confused cause the file “f” already has the tree “t” inside it.
What advantage does it have compared to simply doing, let’s say the following?

TFile* f = new TFile(“example.root”);
t-> Scan();

ROOT Version: 5.18/34
Platform: Ubuntu 18.04

Think about this: what if you have two files, each with a tree called “t”, and you need to read both “at the same time”? If by just creating “file” pointers you got “automatic” access to the things inside, how would ROOT know which “t” you want if you only say t->Scan()? and what if one of those files has a histogram or something else called “t”, instead of a tree?.. and so on.

1 Like

Oh yes ok, that makes sense now. Thank you.