Check the class of objects

Urban Hafner urban at bettong.net
Thu Jun 5 08:25:47 PDT 2008


Mael wrote:
> Since I'm building several image classes (depending on the characteristics of the image, such as grey / color, byte / float, etc), I can either include a flag in each image that tells its class ("I'm a color-byte image", "I'm a grey-byte image", etc.), or use many if( cast(ColorByteImage)img !is null ) { doactionColorByte ; } to check the type. What would be the most efficient way to test the type of the class ? How is the cast(Class)v construct implemented in the compiler (I guess there's some equivalent of a "i'm a color-byte image" flag in the class structure) ?

I think you should have each class report it's "class". This way it's 
easy to add new subclass to your Image class. If you do it in the Image 
class (your second idea) you would have to change the Image class every 
time you add a new subclass! This is (IMHO) bad design as the parent 
class should only contain stuff that's the same for all subclasses. 
After all, if that's not the case, what's the point of having subclasses 
at all?

Urban


More information about the Digitalmars-d-learn mailing list