Set name of new tree

Hi all, sorry this is definitely a stupid question! So I’ve got a piece of code that produces a tree and does everything I want, but the tree has the wrong name. I want it to be called ‘newTree’ and instead when I run it on a file it adds a tree called outTree;2 and I changed some stuff to try and get the name right, ran it again and it added outTree;3 and so on. Here’s my code:

void reweight_function(const char* inputName){

   TString input = inputName;
   TFile *oldFile = new TFile(inputName, "read");
   TTree *oldTree = (TTree*)oldFile->Get("outTree");

  TFile *newFile = new TFile(inputName,"update");
  TTree *newTree = (TTree*)newFile->Get("outTree");
    Long64_t nentries = oldTree->GetEntries();

    double eff;
    double xs;

    if (input.Contains("JZ9")){ xs = 1.9639E-05;  eff = 0.012057; }
    if (input.Contains("JZ10")){ xs =1.1962E-06;  eff = 0.005894; }
    if (input.Contains("JZ11")){ xs = 4.2263E-08;  eff = 0.0026734; }
    if (input.Contains("JZ12")){ xs = 1.0367E-09;  eff = 0.00042898; }

    double reweight = xs*eff/nentries;
    float_t mcEventWeight;   double JZ_weight;

    newTree->SetBranchAddress("mcEventWeight",&mcEventWeight);
    TBranch *New_JZ_weight = newTree->Branch("JZ_weight",&JZ_weight,"JZ_weight/D");
    for(Long64_t i=0; i<nentries; i++){
        newTree->GetEntry(i);
        JZ_weight = reweight;
        New_JZ_weight->Fill();
}
newTree->Write();
//delete newFile;

}

If it isn’t the TTree *newTree bit that sets the name, which is the bit I actually need to change? Thanks for any help, I really appreciate it!

TTree *newTree = new TTree("newTree", "my new tree");
or TTree::CloneTree and TTree::SetName

Thank you! So if I do

TTree *newTree = new TTree("newTree", "my new tree");
*newTree = (TTree*)newFile->Get("outTree");

Will that still add the new tree and call it newTree, which has all the same variables as outTree?

TTree *newTree = new TTree("newTree", "my new tree");
*newTree = (TTree*)newFile->Get("outTree");

Will that still add the new tree and call it newTree, which has all the same variables as outTree?

No. The code above creates an empty TTree and proceed to ‘forget’ about it … well actually it won’t compile as it tries to assign a pointer to an object. See the details of CloneTree for more information on how to accomplish your goal :slight_smile:

But this compiles and runs:

TTree *newTree = (TTree*)newFile->Get("outTree");

Why is it different (question by someone totally hopeless at and inexperienced with coding)? I’ll look at CloneTree, thank you :slight_smile:

TTree *newTree = ...

this declares a new variable whose type is pointer to a TTree object

TTree *newTree = ..
*newTree = ...

Since newTree is a pointer to a TTree object then *newTree asks the compiler to de-reference this pointer and thus the type of ```*newTree`` is “TTree Object”.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.