[osg-users] RE : Re: Converting a Drawable object to a Geometry object

Ulrich Hertlein u.hertlein at sandbox.de
Wed Jul 30 18:52:29 PDT 2008

Hi Franclin,

> Downcasting from a derived class to a parent class is possible with the 
> dynamic_cast operator. From what you have written in your mail, it looks like
> the snippet won't compile at all, I can bet something it will as I tried it a
> couple of hours ago. Try it yourself and let me know.

The code is correct and will compile, it's just that the casts won't work as you 

Okay, let's see:
>> osg::Geode myGeode = new osg::Geode;
>> myGeode->addDrawable(new osg::ShapeDrawable(new osg::Box(osg::Vec3(),1,1,1)));
>> osg::Drawable* myDrawable = myGeode->getDrawable(0);

myDrawable is a Drawable* to a ShapeDrawable
This is fine since Drawable is a base class of ShapeDrawable.
(I assume there aren't any other Drawables in myGeode and the first one is 
actually the ShapeDrawable you added.)

> osg::Geometry* myGeom = myDrawable->asGeometry();

If you take a look at 'osg::Drawable' you'll see that this actually *always* 
returns 0 and ShapeDrawable doesn't override it (Geometry is the only class that 
overrides it).

However, even doing what the comment says (and what you're doing for 'myGeom2'):

osg::Geometry* geom = dynamic_cast<osg::Geometry*>(this)

This cannot succeed since the *object* is-a ShapeDrawable (even though the 
pointer is Drawable*).

> Of course, downcasting from shapedrawable to geometry would have not worked
> and even worse would have not compiled at all.

Agreed.  But introducing a Drawable* doesn't help because it doesn't change the 
type of the object the pointer is pointing to.

ShapeDrawable* shape = new ShapeDrawable(...)
Drawable* drawable = dynamic_cast<Drawable*>(shape); // OK, is a base class
Geometry* geom = dynamic_cast<Geometry*>(drawable); // is always 0

I'm probably not explaining this as clearly as possible but try to think of it 
this way: you have a base class 'Vehicle' and two derived classes 'Car' and 
'Plane'.  You can create a 'Plane' and have a 'Vehicle' pointer to it but you 
can't cast that pointer to a 'Car'.

Hope this helps.


More information about the osg-users mailing list