Reading TTree with a class

Hi ROOT users,

I have a problem reading TTree that contains a class. In the macro below I’ve built the tree with the class point (function write_tree()) and want to read it (read_tree()), but there’s a problem with SetBranchAddress - it returns error code -2, so the class pointer does not match the expected one to the branch.
Do you have any idea how to make this macro work?

// Class to be contained in the tree
class point { public: Double_t x, y; };


void mytree_class() {
    write_tree();
    read_tree();
}


void write_tree() {
// Output file
TFile f("myTreeOutput.root", "RECREATE");

// Output tree
TTree* tr = new TTree("tr", "exemplary tree");

point p1;

// Build branch "point" connected to p1 of fields: Double_t, Double_t 
tr->Branch("point", &p1, "x/D:y/D");

// Exemplary x and y data
double* xarr[5] = {1., 2., 3., 4., 5.};
double* yarr[5] = {2., 4., 6., 8., 10.};

// filling the tree
for (int i=0; i<5; i++) {
  p1.x = xarr[i];
  p1.y = yarr[i];
  tr->Fill();
}

//tr->Print();
tr->Write();
f.Close();
}


void read_tree() {
// Input file
TFile f("myTreeOutput.root");
// Input tree
TTree* tr = f.Get("tr");
tr->Print();
//point * p;  // pointer to class
point * p = new point;

cout << "Setting branch address returns error code: ";
// 0 -- OK, -2 -- bad class (but good branch), -5 -- bad branch
cout << tr -> SetBranchAddress("point", &p) << endl;  // -2
//cout << tr -> SetBranchAddress("point", p) << endl;  // -2 
}

Cheers,
Dawid

mytree_class.C (1.04 KB)

tr->Branch(“point”, &(p1.x), “x/D:y”);
// …
double xarr[5] = {1., 2., 3., 4., 5.};
double yarr[5] = {2., 4., 6., 8., 10.};
// …
std::cout << tr->SetBranchAddress(“point”, &(p->x)) << std::endl;

Thanks, that works.

Cheers,
Dawid