[Gdal-dev] GDALDataset as a Base Class

Mateusz Loskot mateusz at loskot.net
Tue Aug 29 22:26:58 EDT 2006


Mateusz Loskot wrote:
> Matt Hanson wrote:
>> Any ideas on what my derived class
>> constructor should look like then?
> 
> I would use "named constructor idiom" and factory method:
> Here is the concept in very short:
> 
> class GSImage : public GDALDataset
> {
> public:
>   static GSImage* Create(const char* file)
>   {
>      return static_cast<GSImage*>( GDALOpen(file, GA_ReadOnly ) );
>   }
> };
> 
> GSImage* pImage = GSImage::create("myfile.png");

Let me unsay it ;-)
The solution above forces you to still play with pointers.
So, with current design of GDALDataset, it's much better to encapsulate
GDALDataset as a private member of GSImage class than inheritance.
Certainly, composition with its direct lifetime control.

GSImage
{
public:
   GSImage(const char* filename) : ds(0)
   {
      ds = GDALOpen(filename, ...);
   }
   // Add your own or replicate GDALDataset interface

private:
   GDALDataset* ds;
}

Certainly, here you need to (re)design your own interface,
as minimal as needed to use GSImage, or replicate whole
interface after GDALDataset <--- may seem as a redundant work
in comparison of encapsulation, but composition is much better
in wide terms of flexibility.

Side note, inheritance is always easier to use, but
composition/aggregation is much more flexible.

Are you sure GSImage is a GDALDatase?
This is the question from the same family like
Is a circle an elipse but with two radiuses of the same length?

If you're interested in considering this design deeply,
I'd suggest you to look at the Liskov Substitution Principle (LSP)
that's pretty simple to understand but helps much with design
decisions :-)

Cheers
-- 
Mateusz Loskot
http://mateusz.loskot.net



More information about the Gdal-dev mailing list