Re: TClonesArray typecasting

From: Christian Holm Christensen <cholm_at_nbi.dk>
Date: Wed, 15 Nov 2006 10:50:15 +0800


Hi All,

On Tue, 2006-11-14 at 19:48 +0100, Rene Brun wrote:
> Replace

> (TH1F *) bigArr[chan]->Fill(j, value);
> by
> (TH1F *) bigArr[chan])->Fill(j, value);

This is old-style C-like casts, that is generally frowned upon in C++. Instead, you should use one of the 4 cast operators in C++:

        dynamic_cast<T>(o) 
        Returns 0 if o is of a class that doesn't doesn't inherit from
        T.  Is expensive. T must be a reference or pointer type. 
        
        static_cast<T>(o)
        Casts o to an object of type T.  T must be a reference or
        pointer type. 
        
        const_cast<T>(o)
        Adds or removes const and/or volatile qualification of object o
        of unqualified type T. 
        
        reinterpret_cast<T>(o)
        Cast to anything.  This is what is closest to the C-style cast.
        This cast should never really be used if at all avoidable. 
        

In your case, it's probably best to do

        static_cast<TH1*>(bigArr[chan])->Fill(j,value);
        

since you _know_ that the objects stored in bigArr are of class TH1 or derived classes.

When reading from a file, it's best to use dynamic_cast, as you may not know the type of the object returned. Suppose there's an object in the file named `o' and it's of class TH1F. If you do

        TH2* h = dynamic_cast<TH2*>(file->Get("o"))
        

You will get a null pointer back, since `o' is not of type TH2 or any of it's decedents. However, if you do one of

        TH2* h = static_cast<TH2*>(file->Get("o"))
        TH2* h = (TH2*)(file->Get("o"))
        

you will get a pointer back, but it will not be valid - i.e., the program will fail at runtime.

The basic type system of C++ is pretty rich, but by using C-style casts you are completely circumventing that.

Yours,

-- 
 ___  |  Christian Holm Christensen 
  |_| |  -------------------------------------------------------------
    | |  Address: Sankt Hansgade 23, 1. th.  Phone:  (+45) 35 35 96 91
     _|           DK-2200 Copenhagen N       Cell:   (+45) 24 61 85 91
    _|            Denmark                    Office: (+45) 353  25 404
 ____|   Email:   cholm_at_nbi.dk               Web:    www.nbi.dk/~cholm
 | |
Received on Wed Nov 15 2006 - 03:50:26 MET

This archive was generated by hypermail 2.2.0 : Mon Jan 01 2007 - 16:32:02 MET