Write Objects to a File

Dear experts,
I’m trying to write an object inherited from TObject following instructions here: https://root.cern.ch/root/HowtoWrite.html.
The problem is that I can not read back the values… and I have no idea if the problem is in writing or reading.

The code I used to do the test is:

#include <iostream>
#include <TChain.h>
#include <TFile.h>
#include <TBuffer.h>

class Test1:public TObject{
  Test1(float _a, float _b):a(_a),b(_b){std::cout << "a=" << a << " b=" << b << std::endl;}
  float a{-999};
  float b{-999};

  void Streamer(TBuffer &bf)
     if (bf.IsReading()) {
        Version_t v = bf.ReadVersion();
        bf >> a;
        bf >> b;
     } else {
        bf << a;
        bf << b;
        std::cout << "Writing: a=" << a << " b=" << b << std::endl;

//   ClassDef(Test1,1)  //The class title

int write(float x=-1, float y=1){
  TFile f1("x1.root","recreate");
  Test1 t1(x,y);

  return 0;

int read(){
  TFile f1("x1.root","read");
  Test1* t1 = (Test1*)f1.Get("t1");
  std::cout << "read a=" << t1->a << " b=" << t1->b << std::endl;

  return 0;

int main(){
  write(-4, 9);  
  return read();

There is no error/warning message in compilation. But the output of this test code is:

a=-4 b=9
Writing: a=-4 b=9
read a=4.48416e-44 b=0

The last line is expected to be

read a=-4 b=9

Anything wrong in this test code? Thanks!



If you use ClassDef to generate the streamer it works.
Why do you want to define your own streamer?

G Ganis

Thanks for the reply. I tried to make it simple by keeping everything in a single file…
Now I find ClassDef is even simpler. I will go with it.

Note that when inheriting from TObject, the ClassDef macro is compulsory.

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