Probing class of an object

Hello,

I would like to probe for the class of an object stored as TObject in a ROOT file. Would the following work:

if (f.Get(inputfile)->Class() == TH1F::Class()) ?

It seems to match in a simple test:

TH1F obj(“obj”,"",10,0,1)
obj.Class()
(class TClass*)0xbcc270
TH1F::Class()
(class TClass*)0xbcc270

If not, what is the ‘correct’ way to do this test?

Regards,

– Gregory

You can use dynamic_cast or typeid builtin C++ operators, you can also use ROOT’s own RTTI (and I think, with CINT it’s even better, since, for example, dynamic_cast is incorrect in CINT). But when defining class of object
(obj->Class) you in fact call static member function! This means, for TObject * ptr = file.Get(“name”), prt->Class() you’ll get TClass * from TObject, and this is not what you want. Call IsA() instead, this is the virtual function and it’ll give you the TClass pointer you need.

Small examples to demonstrate:

Now

thanks

Is it also possible to test if a class is a Histogram in general?

root [0] TH1F h
root [1] h.IsA()
(const class TClass*)0x28f1e80
root [2] TH1::Class()
(class TClass*)0x29723a8

[quote=“timodoll”]Is it also possible to test if a class is a Histogram in general?

root [0] TH1F h
root [1] h.IsA()
(const class TClass*)0x28f1e80
root [2] TH1::Class()
(class TClass*)0x29723a8[/quote]

This is usually done in a different way, you call obj->IsA() to get TClass *, and call InheritsFrom for the resulting pointer:

root [0] TH1F h;
root [1] h.IsA()->InheritsFrom("TH1")
(const Bool_t)1
root [2] h.IsA()->InheritsFrom(TH1::Class())//another way
(const Bool_t)1

In compiled code you can also use dynamic_cast, which can be faster than ROOT’s RTTI.

thanks again