[Insight-developers] UpCast/DownCast and SmartPointers

Bill Hoffman bill.hoffman at kitware.com
Thu Jun 15 12:10:15 EDT 2000


I think I have figured out a convention that will allow polymorphism 
and dynamic casts to be used with the smart pointer classes.

The convention has the following two rules:

1. If a function takes a pointer to an itkObject (or sub class),
it must use a raw C++ pointer for the argument.  This is a bit
different than the current Insight code as we used to use
::Pointer everywhere.


// Example:
// foo takes an itkObject as an argument, so it
// must be a raw c++ pointer.
void foo(itkObject* o)
{
}

2. If a function returns a pointer to an itkObject (or sub class)
it must use the typedef'ed SmartPointer type::Pointer.  This
is the same as the current Insight code.

// Example:
// foobar returns a pointer so it uses the smart pointer
itkImage::Pointer foobar()
{
    return itkImage::New();
}


// examples of using the above functions:
main()
{
// call foobar to create an itkImage object 
   itkImage::Pointer i = foobar();

// pass the itkImage object to a function that 
// works on its superclass itkImage
// NOTE: no dynamic_cast is required here, because
// an itkImage is an itkObject.  
   foo(i);
}



For safe down casting use the following syntax:

itkObject::Pointer o(itkImage::New());
itkImage::Pointer image = dynamic_cast<itkImage*>(o.GetPointer());











More information about the Insight-developers mailing list