Question

In the following code:

#include "itkImage.h"
#include "itkImageRegionIterator.h"

struct CustomImageBase
{
  virtual void DoSomething() = 0;
};

template <typename TPixel>
struct CustomImage : public itk::Image<TPixel, 2>, public CustomImageBase
{
  void DoSomething()
  {
    itk::Index<2> index;
    index.Fill(0);
    std::cout << this->GetPixel(index);
  }
};

int main(int, char *[])
{
  std::vector<CustomImageBase*> images;

  CustomImage<float>* floatImage = CustomImage<float>::New().GetPointer();
  CustomImage<int>* intImage = CustomImage<int>::New().GetPointer();

  return EXIT_SUCCESS;
}

I get the error: invalid convsion from itk::Image* to CustomImage*

Note that this works fine:

itk::Image<float>* testFloatImage = itk::Image<float>::New().GetPointer();

Since CustomImage inherits from itk::Image, I don't understand the problem?

Was it helpful?

Solution

If B derives from A, you cannot convert A* to B*. If C also derives from A, and your A* really points to a C object instead of a B object, what would happen if you pretend it is a B? The conversion is unsafe. In your case, you know that GetPointer() will always return a CustomImage<T>. The compiler does not know that. You can tell it by using a cast:

CustomImage<float>* floatImage = static_cast<CustomImage<float>*>(CustomImage<float>::New().GetPointer());

Edit: this is precisely why the conversion is unsafe: after reading the comments on your question, I don't believe CustomImage<float>::New().GetPointer() really points to a CustomImage, and if not, the cast would simply turn compiler errors into runtime errors.

OTHER TIPS

Since CustomImage inherits from itk::Image, I don't understand the problem?

Since CustomImage inherits from itk::Image, this means that CustomImage* can be implicitly converted to itk::Image*. However, the compiler is complaining about the opposite conversion:

invalid convesion from itk::Image* to CustomImage*

This requires an explicit type cast.

I can't compile your code since I don't have the pre-requisites, and you don't say which line of the code the compiler doesn't like, so it's hard to provide further help at this point.

Suppose this was allowed. Now consider the following:

struct yet_another_image : public itk::Image<TPixel, 2> {
}

yet_another_image img;
itk::Image<TPixel, 2>* ptr = &img; // ok
CustomImage* bad = ptr; // oops!

You can safely convert from a pointer to a derived class to a pointer to base class, but you can't safely convert the other way around, because you don't know if the object pointed to has the correct type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top