[geos-devel] a question about the conversion from Geometry* to Polygon*

Mateusz Loskot mateusz at loskot.net
Thu Mar 26 05:55:23 EDT 2009


南野秀一 南野秀一 wrote:
> I use the following function to get the intersection of two polygons
> which have holes and the value returned is Geometry *.
> 
> geos::precision::EnhancedPrecisionOp:: intersection(Poly_A,Poly_B);

The EnhancedPrecisionOp::intersection()  returns pointer to Geometry,
as the function prototype says:

http://trac.osgeo.org/geos/browser/trunk/source/headers/geos/precision/EnhancedPrecisionOp.h#L45

Geometry is a base class of all geometry types, Polygon included.

 > If getGeometryTypeId() tells me the geometry returned is a polygon,
 > how can I get a pointer Polygon * from Geometry * safely ?

Stick to basics of C++ programming language and use dynamic_cast 
operator to cast pointer/reference to base class to pointer/reference to 
  subclass

Geometry* pg = ...;
Polygon* p = dynamic_cast<Polygon*>(pg);

 > If I convert it directly, is it always safe ?

It is, as long as you check:
1. actual type of geometry using getGeometryTypeId etc.
2. check if dynamic_cast succeede testing pointer against nullptr

Best regards,
-- 
Mateusz Loskot, http://mateusz.loskot.net
Charter Member of OSGeo, http://osgeo.org


More information about the geos-devel mailing list