Pointers: A too-short explanation (for those who don’t know C++ or C)

(5 minutes)

On the previous page we used the pointer symbol “->” (a dash followed by a greater-than sign) instead of the period “.” to issue the commands to the TTree. This is because the variable tree1 isn’t really the TTree itself; it’s a “pointer” to the TTree.

The detailed difference between an object and a pointer in C++ (and ROOT) is beyond the scope of this tutorial. I strongly suggest that you look this up in any introductory text on C++. For now, I hope it’s enough to show a couple of examples:

[] TH1D hist1("h1","a histogram",100,-3,3)

This creates a new histogram in ROOT, and the name of the histogram “object” is hist1. I must use a period to issue commands to the histogram:

[] hist1.Draw()

Here’s the same thing, but using a pointer instead:

[] TH1D *hist1 = new TH1D("h1","a histogram",100,-3,3)

Note the use of the asterisk “*” when I define the variable, and the use of the C++ keyword new. In this example, hist1 is not a ‘object,’ it’s a ‘pointer’ to the location in computer memory where the object hist1 is stored. I must use the pointer syntax to issue commands:

[] hist1->Draw()

Take another look at the file c1.C that you created in a previous example. ROOT uses pointers for almost all the code it creates. As I mentioned previously, ROOT automatically creates variables when it opens files in interactive mode; these variables are always pointers.

It’s a little harder to think in terms of pointers than in terms of objects. But you have to use pointers if you want to use the C++ code that ROOT creates for you

You also have to use pointers to take advantage of object inheritance and polymorphism in C++. ROOT relies heavily on object inheritance (some would say too heavily), and this is often reflected in the code it generates.

xkcd pointers

Figure 29: https://xkcd.com/138/ by Randall Munroe