Why using pointer of classes

Dear Experts

I’m new to c++, I saw many people using pointer to define ROOT class member like:

TTree* t = //some Get function
TH2D* h = new TH2D();
TCanvas* c = new Canvas();

instead of

TTree t = //some Get function
TH2D h;

What’s the difference and what advantage will I have if I use pointer to define them?

file canvas1.C

void canvas1() {
   TCanvas c;
   TText t (.5,.5,"Hello");

file canvas2.C

void canvas2() {
   auto c = new TCanvas();
   auto t = new TText(.5,.5,"Hello");

Then try:

root[0] .x canvas1.C


root[0] .x canvas2.C

and you will see the difference.

The first one doesn’t give anything on the screen, where the 2nd one gives canvas and text on the canvas…Why?

Because with the 1st one, the object is local: created in the macro and deleted when the macro exits. In the 2nd one, the pointer stays alive.

The same question was asked 10 years ago: Why do so many use pointers to ROOT objects?

Thank you for the explanation, understood that pointer will stay alive after macro exits. What if I write a c++ program and compile with root? Will it be any difference between pointer and object? Like:

int main(){
   TTree* t =


int main(){
   TTree t;

Then that’s a C++ question. Normal objects vanish automatically when they are out of scope (basically when exiting { } ) and pointers must be deleted otherwise you get a memory leak.