#include "TRandom.h" #include "TClonesArray.h" #include "TTree.h" #include "TFile.h" #include "iostream" class A; //----------------------------------------------------------------- class B : public TObject { public: B():pA(0) {} protected: B& operator=(const B& in) {return *this;} B(const B& in) {} public: void SetParent(A* in) {pA=in;} A* GetParent() {return pA;} void Clear(const char *opt="") {pA=0;} private: A * pA; ClassDef(B,1); }; //----------------------------------------------------------------- class A : public TObject { public: A():fB("B") {} protected: A& operator=(const A& in) {return *this;} A(const A& in) {} public: B* GetB(long idx) {return reinterpret_cast(fB[idx]);} B* AddB() {return new (fB[fB.GetEntries()]) B;} size_t GetNbrB() {return fB.GetEntries();} void Clear(const char *opt="") {fB.Clear(opt);} private: TClonesArray fB; ClassDef(A,1); }; //_________________________________________________________________ //----------------------------------------------------------------- void create(A *a) { size_t nB = gRandom->Uniform(1,10); for (size_t iB=0; iB < nB; ++iB) { B *b = a->AddB(); b->SetParent(a); //comment this line and the error will disappear } } //----------------------------------------------------------------- void draw(A *a) { std::cout << "A("<GetNbrB()<<" B's"<GetNbrB(); ++iB) { std::cout << " B("<GetB(iB)->GetParent()<Branch("a","A",&a); //size_t nA = gRandom->Uniform(1,10); size_t nA=2; std::cout <<"Creating "<Clear(); create(a); draw(a); t->Fill(); } o->Write(); delete o; } //----------------------------------------------------------------- void ReadRootFile() { TFile *f = new TFile("Test.root"); TTree *t = reinterpret_cast (f->Get("tree")); A *a = 0; t->SetBranchAddress("a", &a); size_t nA = static_cast(t->GetEntries()); std::cout <<"The tree has "<GetEntry(i); draw(a); } delete f; } //----------------------------------------------------------------- void testTClonesArray() { gRandom->SetSeed(0); WriteRootFile(); std::cout<< "reading root file"<