How to get the type of an object?

Hi,

i’m trying to do a thing like this: i want to make a function that behaves differently if the argument is a TH1 or is a TTree.

i was thinking of something like :

void select(string base)
{
TObject *oggetto =gDirectory->Get(base.c_str());
if(oggetto is a TH1)
   {
   action1
    }
else
    {
    action2
    } 
} 

There is a way to do this?
Thank you

To be more specific i’m tring to cont the number of zeros of a TTree or a TH1F.

i wrote this

void tree(string base);
void th1(string base);
void supercontazeri(string base)
{
TObject *oggetto =gDirectory->Get(base.c_str());
if((TTree *)oggetto->IsA())
	{
	tree(base);
	}
else
	{
	th1(base);
	}
}
/*********************************************************************************
*********************************************************************************/
void tree(string base)
{
int nzero =0;
double entry =0;
//TFile *myfile=TFile::Open(base.c_str());
TTree *atree=(TTree *)gDirectory->Get(base.c_str());
atree->SetBranchAddress("PETot",&entry);

int nentries=atree->GetEntries();
for(int i=0;i<nentries;i++)
	{
	atree->GetEntry(i);
	if(entry==0)
		{
		nzero++;
		}
	}
cout<<"nentries: "<<nentries<<endl;
cout<<"nzero :"<<nzero<<endl;
}
/*********************************************************************************
*********************************************************************************/
void th1(string base)
{
int nzero =0;
int nbins1 =0;
Stat_t bincontent1 =0;

TH1 *ath1=(TH1 *)gDirectory->Get(base.c_str());

nbins1 = ath1->GetNbinsX();
for (int i=0; i<nbins1; i++)
	{
	bincontent1 = ath1->GetBinContent(i+1);
	if(bincontent1==0)
		{
		nzero++;
		}
    }
cout<<"nentries: "<<nbins1<<endl;
cout<<"nzero :"<<nzero<<endl;
}

the th1 function doesn’t work in this way but used in a script alone works very nice.
where is the mistake?

Hi,

use dynamic_cast<TH1*>(obj) in compiled code (see any C++ manual); use obj->InheritsFrom(TH1::Class()) in an interpreted macro (see root.cern.ch/root/html/TObject#T … heritsFrom).

Axel.

Your test is wrong. Instead do:

TObject *oggetto =gDirectory->Get(base.c_str()); if(oggetto->InheritsFrom("TTree")) { tree(base); } else { th1(base); }

Rene

thank you all for the help!

what is the use for obj->IsA() then? or where i can find the answer?

Amir

obj->IsA() return the exact type (TClass*) of the object.
For example if obj is a TH1F,
obj->IsA() return TH1F::Class().
To test if an object derives from TH1, use one of the forms
1-if (obj->InheritsFrom(“TH1”))
2- if (obj->InheritsFrom(TH1::Class()))

The second form requires #include “TH1.h” in your C++ file.

Rene

Thank you very much Rene
Amir